sparkjava: Load PNG as base64 from InputStream - java

I have the following method to load resources as String where path is the String to the resource on my classpath (which works just fine on plain text):
try (Scanner scanner = new Scanner(MyClass.class.getResourceAsStream(path))) {
return scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
}
Now I want to load a PNG image as a base64 String so I can send it back through sparkjava with Content-Type: image/png.
How can I do that?
Do not use any libraries, only plain old Java.

After setting the MIME type in the header with response.header("Content-Type", "image/png") (look up your MIME type here), you can use this:
try {
return Files.readAllBytes(Paths.get(MyClass.class.getResource(path).toURI()));
} catch (IOException | URISyntaxException exception) {
exception.printStackTrace();
}
return null;
Apart from that, to base64-encode a String in Java 8, you can use the java.util.Base64.Encoder class, so you'd just run the result of the method I posted in my description through
Base64.getMimeEncoder().encodeToString(resourceAsString.getBytes(StandardCharsets.UTF_8))
and send it back as response. I haven't got it to work for me though, for some odd reason. I simply used my framework's static files feature.

Related

MS Graph API: Getting 404 when saving to _layouts folder

I'm using the MS Graph Java SDK to save a file to user's OneDrive and under a given path:
#Test
public void createDriveItem() {
String fileName = "moon.pdf";
String fullPath = "a/_layouts/b" + fileName;
byte[] content = Files.readAllBytes(Paths.get(fileName));
graph.users(userId)
.drive()
.root()
.itemWithPath(encodePath(fullPath))
.content()
.buildRequest()
.put(content);
}
private String encodePath(String path) {
String encoding = StandardCharsets.UTF_8.name();
try {
return URLEncoder.encode(path, encoding);
} catch (UnsupportedEncodingException e) {
return path;
}
}
I'm using MS Graph Java SDK v2.5.0, Java 11.
However, this request fails with 404 : Not Found. It also fails if I don't encode the path. It looks like the /_layouts/ which is making troubles because, once I add something to it, the request works.
Also, I reproduced this error with a number of accounts.
My question is: Is this actually expected? If yes, why does creating the same folder structure work when done through the web UI?
I believe you should not be able to add items into /_layouts/ on SharePoint Online.

From Angular Actual parameter value is "Ébénisterie" but in JAVA getting value "Ã?bénisterie"

From Angular, there is one parameter and the value of that parameter is Ébénisterie but when I print the value of that variable in java then I got Ã?bénisterie can you please let me know how I can convert it to original text Ébénisterie? Which Encode/decode I have to apply?
I have tried the following thing.
new String(readable.getBytes("ISO-8859-15"), "UTF-8");
new String(readable.getBytes("UTF-8"), "ISO-8859-15");
but it's not working.
String readable ="�bénisterie Distinction";
String test = null;
try {
test = new String(readable.getBytes("ISO-8859-15"), "UTF-8");
System.out.println("test"+test);
} catch (UnsupportedEncodingException e) {
}
Expected: Ébénisterie
Actual: �bénisterie
After long research didn't find anything.
So got one solution in mind that BASE64 Encode decode so now from Angularjs sending encoded text and In java side, I have decoded the text.
Here, is the sample code
Angularjs
window.btoa("Ébénisterie")
JAVA
String actualString= new String(Base64.getDecoder().decode("ENCODED STRING"));

How to know whether a string path is Web URL or a File based

I have a text field to acquire location information (String type) from User. It could be file directory based (e.g. C:\directory) or Web url (e.g. http://localhost:8008/resouces). The system will read some predetermined metadata file from the location.
Given the input string, how can I detect the nature of the path location whether it is a file based or Web URL effectively.
So far I have tried.
URL url = new URL(location); // will get MalformedURLException if it is a file based.
url.getProtocol().equalsIgnoreCase("http");
File file = new File(location); // will not hit exception if it is a url.
file.exist(); // return false if it is a url.
I am still struggling to find a best way to tackle both scenarios. :-(
Basically I would not prefer to explicitly check the path using the prefix such as http:// or https://
Is there an elegant and proper way of doing this?
You can check if the location starts with http:// or https://:
String s = location.trim().toLowerCase();
boolean isWeb = s.startsWith("http://") || s.startsWith("https://");
Or you can use the URI class instead of URL, URI does not throw MalformedURLException like the URL class:
URI u = new URI(location);
boolean isWeb = "http".equalsIgnoreCase(u.getScheme())
|| "https".equalsIgnoreCase(u.getScheme())
Although new URI() may also throw URISyntaxException if you use backslash in location for example. Best way would be to either use prefix check (my first suggestion) or create a URL and catch MalformedURLException which if thrown you'll know it cannot be a valid web url.
If you're open to the use of a try/catch scenario being "elegant", here is a way that is more specific:
try {
processURL(new URL(location));
}
catch (MalformedURLException ex){
File file = new File(location);
if (file.exists()) {
processFile(file);
}
else {
throw new PersonalException("Can't find the file");
}
}
This way, you're getting the automatic URL syntax checking and, that failing, the check for file existence.
you can try:
static public boolean isValidURL(String urlStr) {
try {
URI uri = new URI(urlStr);
return uri.getScheme().equals("http") || uri.getScheme().equals("https");
}
catch (Exception e) {
return false;
}
}
note that this will return false for any other reason that invalidates the url, ofor a non http/https url: a malformed url is not necessarily an actual file name, and a good file name can be referring to a non exisiting one, so use it in conjunction with you file existence check.
public boolean urlIsFile(String input) {
if (input.startsWith("file:")) return true;
try { return new File(input).exists(); } catch (Exception e) {return false;}
}
This is the best method because it is hassle free, and will always return true if you have a file reference. For instance, other solutions don't and cannot cover the plethora of protocol schemes available such as ftp, sftp, scp, or any future protocol implementations. So this one is the one for all uses and purposes; with the caveat of the file must exist, if it doesn't begin with the file protocol.
if you look at the logic of the function by it's name, you should understand that, returning false for a non existent direct path lookup is not a bug, that is the fact.

Convert TIF/TIFF to JPG : Bad endianness tag

I am trying to convert TIF / TIFF images to JPG which works fine but for few TIF images I am getting an IllegalArgumentException: Bad endianness tag (not 0x4949 or 0x4d4d).
Exception :
java.io.IOException: Bad endianness tag (not 0x4949 or 0x4d4d).
at com.sun.media.jai.codecimpl.CodecUtils.toIOException(CodecUtils.java:76)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.getNumPages(TIFFImageDecoder.java:98)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.decodeAsRenderedImage(TIFFImageDecoder.java:103)
at com.sun.media.jai.codec.ImageDecoderImpl.decodeAsRenderedImage(ImageDecoderImpl.java:140)
at com.pkg.jae.utils.GenericImageUtils.convertTiffToJpg(GenericImageUtils.java:35)
at com.pkg.jae.utils.GenericImageUtils.main(GenericImageUtils.java:92)
Caused by: java.lang.IllegalArgumentException: Bad endianness tag (not 0x4949 or 0x4d4d).
at com.sun.media.jai.codec.TIFFDirectory.getNumDirectories(TIFFDirectory.java:595)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.getNumPages(TIFFImageDecoder.java:96)
... 4 more
Code Function :
public static void convertTiffToJpg(String strTiffUrl,String strJpgFileDestinationUrl) throws Exception {
try {
FileSeekableStream obj_FileSeekableStream = new FileSeekableStream(new File(strTiffUrl));
ImageDecoder obj_ImageDecoder = ImageCodec.createImageDecoder(EXT_TIFFX, obj_FileSeekableStream, null);
RenderedImage obj_RenderedImage = obj_ImageDecoder.decodeAsRenderedImage();
JAI.create("filestore", obj_RenderedImage,strJpgFileDestinationUrl, EXT_JEPGX);
obj_RenderedImage = null;
obj_ImageDecoder = null;
obj_FileSeekableStream.close();
} catch (Exception ex) {
throw ex;
}
}
If anyone knows the issue and can help in this.
As stated in a comment by bitbank, this means you're passing a JPEG file to it when it expects to get a TIFF file.
Startlingly, this JAI
RenderedOp renderer = JAI.create("fileload", filename);
BufferedImage bi = renderer.getAsBufferedImage();
does not have the same failure and just works regardless of image "kind." Don't use this particular method (passing in the filename) though, see Is JAI closing file handles too early?
I had this issue and it turned out to be a front-end problem. Yes, I was trying to upload the wrong file type, but I was expecting correct handling and a gracious popup message alert. Instead I was getting the error you described.
In my case, I was using extjs and I had a failure function like this:
failure: function (a) {
...some message alert...
}
instead of:
failure: function (f, a) {
...some message alert...
}
and this was throwing that exception, instead of displaying my message alert.

Compare file extension to file header

I'm starting to design an application, that will, in part, run through a directory of files and compare their extensions to their file headers.
Does anyone have any advice as to the best way to approach this? I know I could simply have a lookup table that will contain the file's header signature. e.g., JPEG: \xFF\xD8\xFF\xE0
I was hoping there might be a simper way.
Thanks in advance for your help.
I'm afraid it'll have to be more complicated than that. Not every file type has a header at all, and some (such as RAR) have their characteristic data structures at the end rather than at the beginning.
You may want to take a look at the Unix file command, which does the same job:
http://linux.die.net/man/1/file
http://linux.die.net/man/5/magic
If you don't need to do dirty work on these values (and you don't have linux) you could simply use an external program, like TrID, that is able to do this thing for you.
Maybe you can just work on its output without caring to doing it by yourself.. in anycase if you have just around 20 kinds of files that you will have to manage having a simple lookup table (eg. HashMap<String,byte[]>) is not that bad. Of cours this will work only if desidered file format has a magic number, otherwise you are on your own (or with an external program).
Because of the problem with the missing significant header for some file types (thanks #Michael) I would create a map of extension to a kind of type checker with a simple API like
public interface TypeCheck throws IOException {
public boolean isValid(InputStream data);
}
Now you can code something like
File toBeTested = ...;
Map<String,TypeCheck> typeCheckByExtension = ...;
TypeCheck check = typeCheckByExtension.get(getExtension(toBeTested.getName()));
if (check != null) {
InputStream in = new FileInputStream(toBeTested);
if (check.isValid(in)) {
// process valid file
} else {
// process invalid file
}
in.close();
} else {
// process unknown file
}
The Header check for JPEG for example may look like
public class JpegTypeCheck implements TypeCheck {
private static final byte[] HEADER = new byte[] {0xFF, 0xD8, 0xFF, 0xE0};
public boolean isValid(InputStream data) throws IOException {
byte[] header = new byte[4];
return data.read(header) == 4 && Arrays.equals(header, HEADER);
}
}
For other types with no significant header you can implement completly other type checks.
You can extract the mime type for each file and compare this to a map of mimetype/extension (Map<String, List<String>>, the first String is the mime type, the second is a list of valid extensions).
Resources :
Get the Mime Type from a File
JMimeMagic
On the same topic :
Java - HowTo extract MimeType from a byte[]
Getting A File's Mime Type In Java
You can know the file type of file reading the header using apache tika. Following code need apache tika jar.
InputStream is = MainApp.class.getResourceAsStream("/NetFx20SP1_x64.txt");
BufferedInputStream bis = new BufferedInputStream(is);
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY,MainApp.class.getResource("/NetFx20SP1_x64.txt").getPath());
MediaType mediaType = detector.detect(bis, md);
System.out.println("MIMe Type of File : " + mediaType.toString());

Categories

Resources