The following few lines are part of my servlet that give me an error "java.lang.NullPointerException"
ServletContext context = getServletContext();
InputStream kapil= context.getResourceAsStream("Desktop/images.jpg");
//the above line generates the exception
BufferedImage bufferedImage = ImageIO.read(kapil);
You edited your post. Are you sure it's a NullPointerException and not a IllegalArgumentException?
JavaDocs:
ServletContext.getResourceAsStream() will return null if it cannot find the file you are looking for.
ImageIO.read() throws an IllegalArgumentExeception when the parameter is null. The mentioned input is probably the ImageIO input parameter.
I'd guess that indeed the Input file isn't found.
That would match your original posts problem. Try the following:
ServletContext context = getServletContext();
InputStream kapil= context.getResourceAsStream("Desktop/images.jpg");
if (kapil != null){
//the above line generates the exception
BufferedImage bufferedImage = ImageIO.read(kapil);
} else {
// Use a logging framework if you have it.
System.out.println("The input stream is null!");
}
Related
According to the Documentation,
java.io.FileDescriptor works for opening a file having a specific name. If there is any content present in that file it will first erase
all that content and put “Beginning of Process” as the first line.
My FILE.txt file contains content as my name 'Jaimin Modi' only.
Now, below is one sample for the use of FileDescriptor class in java:
import java.io.*;
public class NewClass
{
public static void main(String[] args) throws IOException
{
// Initializing a FileDescriptor
FileDescriptor geek_descriptor = null;
FileOutputStream geek_out = null;
// HERE I'm writing "GEEKS" in my file
byte[] buffer = {71,69,69,75,83};
try{
geek_out = new FileOutputStream("FILE.txt");
// This getFD() method is called before closing the output stream
geek_descriptor = geek_out.getFD();
// writes byte to file output stream
geek_out.write(buffer);
// USe of sync() : to sync data to the source file
geek_descriptor.sync();
System.out.print("\nUse of Sync Successful ");
}
catch(Exception excpt)
{
// if in case IO error occurs
excpt.printStackTrace();
}
finally
{
// releases system resources
if(geek_out!=null)
geek_out.close();
}
}
}
Am getting below output/content in FILE.txt as 'GEEKS'.
So, What I have done next is just commented the lines for the use of FileDescriptor.
Commented below lines :
FileDescriptor geek_descriptor = null;
geek_descriptor = geek_out.getFD();
geek_descriptor.sync();
and again changed content in FILE.txt as 'Jaimin Modi'.
then just executed. What am getting in FILE.txt :
'GEEKS'..!!
Am getting the same result with and without the use of FileDescriptor.
So, What is the main use of FileDescriptor here. Confused a little. Please guide.
I am getting fortify path manipulation vulnerability for creating a file with new keyword
I have tried to sanitize the path before passing it to File object, but the problem persists.
Tried this link also:
https://www.securecoding.cert.org/confluence/display/java/FIO00-J.+Do+not+operate+on+files+in+shared+directories
public static String sanitizePath(String sUnsanitized) throws URISyntaxException, EncodingException {
String sSanitized = SAPI.encoder().canonicalize(sUnsanitized);
return sSanitized;
}
//// the main method code snippet /////
String sSanitizedPath = Utils.sanitizePath(file.getOriginalFilename());
-- fortify scan detects problem here ..in below line --
File filePath = new File(AppInitializer.UPLOAD_LOCATION, sSanitizedPath);
String canonicalPath = filePath.getCanonicalPath();
FileOutputStream fileOutputStream = new FileOutputStream(canonicalPath);
After the santizePath , I thought the scan will be not pick ,vulnerabilit but , it did.
This "sUnsanitized" variable comes from user input? Maybe this is your real problem.
Never trust in user input its a number one rule to develpment.
I have a small Java Application running inside IBM Integration Bus, which is installed in an AIX Server with the character encoding set to ISO-8959-1.
My application is creating a ZIP File with the filenames received as a parameter. I have a file called "Websërvícès Guide.pdf" in the filesystem which I wanted to zip but I'm unable.
This is my code:
String zipFilePath = "/tmp/EventAttachments_2018.01.25.11.39.34.zip";
// Streams buffer
int BUFFER = 2048;
// Open I/O Buffered Streams
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFilePath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
// Oprn File Stream to my file
Path currentFilePath = Paths.get("/tmp/Websërvícès Guide.pdf");
InputStream fi = Files.newInputStream(currentFilePath, StandardOpenOption.READ);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry("Websërvícès Guide.pdf");
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
out.close();
Which is throwing a "File Not Found" exception in the Files.newInputStream line.
I have read that Java is not working properly when checking it files with special characters exists and so on. I'm not able to perform changes in the JVM Parameters as code is executed inside a IBM JVM.
Any idea on how to solve this issue and pack the file properly in the ZIP?
Thank you
Can you try to pass following flag to while running your java program
-Dsun.jnu.encoding=UTF-8
First: In your code, you are not taking care of any Exceptions that could be thrown. I would suggest to handle the exceptions of the method or make the method throw the exception and handle it on a higher level. But somewhere you need to handle the exception.
Maybe that's already the problem. (see https://stackoverflow.com/a/155655/8896833)
Second: According to ISO-8959-1 all the characters used in your filename should be covered. Are you really sure about the path your program is working in at the moment you are trying to access the file?
Try to use URLDecoder class method decode(String string, String encoding);.
For example:
String path = URLDecoder.decode("Websërvícès Guide.pdf", "UTF-8"));
hi i'm working on a project in which i need to make changes to BASE64 string of an image(jpg)...so at first when i didn't made any changes, the ImageReader was properly working and my image was displayed properly..but when i made changes to my BASE64 string the above exception came..i searched a lot and came to know that im==null comes when ByteStream is not jpeg,png,gif..etc..so what if i have a new type of ByteStream...what should i use?? or what ever my BASE64 string is i need to convert that to an image..so how can i do that??
here is my code snippet:this is to convert BASE64 string to an image
public static BufferedImage decodeToImage(String imageString) throws IOException {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
}
catch (Exception e) {
e.printStackTrace();
}
ImageIO.write(image, "jpg", new File("d:/CopyOfTestImage.jpg"));
return image;
}
Have a look at the Javadocs for ImageIO.read:
Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned. [emphasis mine]
The read method can return null, yet you are not checking for this. In fact the method is probably returning null, which is why ImageIO.write throws an exception when you pass null into it.
First things first, you need to check for error conditions and handle them appropriately (including the null return, but also including any exceptions that are thrown, which you currently catch and ignore).
Now if you're getting null back from ImageIO.read, it means the bytes you passed into the read method did not appear to be a valid image in any known format. You need to look in more detail at the modifications you're making to the base64 string, and ensure that what you're doing is valid, and results in a valid image. Alternatively, if you're getting some other exception thrown, then you need to handle that appropriately.
(As a general rule, don't throw away/skip over errors, because then when things go wrong you have no idea why!)
change this line:
ImageIO.write(image, "jpg", new File("d:/CopyOfTestImage.jpg"));
to something like this
image = ImageIO.read(getClass().getResource("/resources/CopyOfTestImage.jpg"));
I know this has probably been asked 10000 times, however, I can't seem to find a straight answer to the question.
I have a LOB stored in my db that represents an image; I am getting that image from the DB and I would like to show it on a web page via the HTML IMG tag. This isn't my preferred solution, but it's a stop-gap implementation until I can find a better solution.
I'm trying to convert the byte[] to Base64 using the Apache Commons Codec in the following way:
String base64String = Base64.encodeBase64String({my byte[]});
Then, I am trying to show my image on my page like this:
<img src="data:image/jpg;base64,{base64String from above}"/>
It's displaying the browser's default "I cannot find this image", image.
Does anyone have any ideas?
Thanks.
I used this and it worked fine (contrary to the accepted answer, which uses a format not recommended for this scenario):
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();
According to the official documentation Base64.encodeBase64URLSafeString(byte[] binaryData) should be what you're looking for.
Also mime type for JPG is image/jpeg.
That's the correct syntax. It might be that your web browser does not support the data URI scheme. See Which browsers support data URIs and since which version?
Also, the JPEG MIME type is image/jpeg.
You may also want to consider streaming the images out to the browser rather than encoding them on the page itself.
Here's an example of streaming an image contained in a file out to the browser via a servlet, which could easily be adopted to stream the contents of your BLOB, rather than a file:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
ServletOutputStream sos = resp.getOutputStream();
try {
final String someImageName = req.getParameter(someKey);
// encode the image path and write the resulting path to the response
File imgFile = new File(someImageName);
writeResponse(resp, sos, imgFile);
}
catch (URISyntaxException e) {
throw new ServletException(e);
}
finally {
sos.close();
}
}
private void writeResponse(HttpServletResponse resp, OutputStream out, File file)
throws URISyntaxException, FileNotFoundException, IOException
{
// Get the MIME type of the file
String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
if (mimeType == null) {
log.warn("Could not get MIME type of file: " + file.getAbsolutePath());
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mimeType);
resp.setContentLength((int)file.length());
writeToFile(out, file);
}
private void writeToFile(OutputStream out, File file)
throws FileNotFoundException, IOException
{
final int BUF_SIZE = 8192;
// write the contents of the file to the output stream
FileInputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
for (int count = 0; (count = in.read(buf)) >= 0;) {
out.write(buf, 0, count);
}
}
finally {
in.close();
}
}
If you don't want to stream from a servlet, then save the file to a directory in the webroot and then create the src pointing to that location. That way the web server does the work of serving the file. If you are feeling particularly clever, you can check for an existing file by timestamp/inode/crc32 and only write it out if it has changed in the DB which can give you a performance boost. This file method also will automatically support ETag and if-modified-since headers so that the browser can cache the file properly.