While converting the InputStream to BufferedImage I am getting the below error
byte[] imgBytes = decoder.decode(encodedStr);
This line is executing fine and generating the byte array properly
InputStream in = new ByteArrayInputStream(imgBytes);
BufferedImage bImageFromConvert = ImageIO.read(in);
This line is giving error as it is unable to read the InputStream properly
Below is the error
javax.imageio.IIOException: Error reading PNG image data
at com.sun.imageio.plugins.png.PNGImageReader.readImage(Unknown Source)
at com.sun.imageio.plugins.png.PNGImageReader.read(Unknown Source)
at javax.imageio.ImageIO.read(Unknown Source)
at javax.imageio.ImageIO.read(Unknown Source)
at DecodeSignatureFile.generateImage(DecodeSignatureFile.java:252)
at DecodeSignatureFile.getContents(DecodeSignatureFile.java:176)
at DecodeSignatureFile.process(DecodeSignatureFile.java:322)
at DecodeSignatureFile.main(DecodeSignatureFile.java:334)
Caused by: java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readFully(Unknown Source)
at com.sun.imageio.plugins.png.PNGImageReader.decodePass(Unknown Source)
at com.sun.imageio.plugins.png.PNGImageReader.decodeImage(Unknown Source)
... 8 more
The error likely occurs before. In Java a String encodedStr is often not suitable to hold binary data. Compare those imgBytes to the original image.
Of course it depends on the encoding and decoding. But the rest looks okay.
Related
In my program I download from server a XML file as String and sign it with certificate. Everything works fine when I run the program from Eclipse. But when I am exporting it to .jar file, the following error occurs. Where should I look for the problem?
eu.europa.esig.dss.DSSException: Unable to parse content (XML expected)
at eu.europa.esig.dss.DomUtils.buildDOM(DomUtils.java:242)
at eu.europa.esig.dss.DomUtils.buildDOM(DomUtils.java:209)
at eu.europa.esig.dss.xades.signature.EnvelopedSignatureBuilder.buildRootDocumentDom(EnvelopedSignatureBuilder.java:75)
at eu.europa.esig.dss.xades.signature.XAdESSignatureBuilder.build(XAdESSignatureBuilder.java:179)
at eu.europa.esig.dss.xades.signature.XAdESLevelBaselineB.getDataToSign(XAdESLevelBaselineB.java:72)
at eu.europa.esig.dss.xades.signature.XAdESService.getDataToSign(XAdESService.java:92)
at pl.btech.signer.Signer.signFilesWithMSCAPI(Signer.java:116)
at pl.btech.signer.Signer.signXML(Signer.java:58)
at pl.btech.signer.GuiController$1.run(GuiController.java:124)
Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.skipChar(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at eu.europa.esig.dss.DomUtils.buildDOM(DomUtils.java:240)
... 8 more
EDIT:
It is fragment of code where error occurs. content is XML string which I get form server.
File srcFile = File.createTempFile("src", ".xml");
FileWriter writer = new FileWriter(srcFile);
writer.write(content);
writer.close();
DSSDocument doc = new FileDocument(srcFile));
ToBeSigned dataToSign = service.getDataToSign(doc, parameters);
FileWriter uses the default charset of the platform. This varies per application deployment, so that is not feasible. If the XML is always in UTF-8, do:
Path srcFile = Files.createTempFile("src", ".xml");
Files.write(srcFile, content.getBytes(StandardCharsets.UTF_8));
// Or:
// Files.write(srcFile, Collections.singletonList(content));
Avoid FileWriter/FileReader.
I am using an ObjectInputStream and ObjectOutputStream for my client to talk to a server over TCP. The client is not able to receive a response back from the server... when I step through in debug mode the response goes through fine. However, if I run the program without a break point it will throw a NullPointerException exception.
Initialization:
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
Socket socket = null;
socket = new Socket(server, port);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
Code that breaks:
try
{
oos.writeObject(request);
serverResponse = (Message) ois.readObject();
output.append(serverResponse.data + "\n");
}
catch(Exception ex)
{
System.err.println("Error adding car to server: " + ex.getMessage());
return;
}
The code above is throwing the NullPointerException. If I use a break point and step through, I get a server response just fine. I have confirmed that in every instance the server is reading the
Any help would be greatly appreciated!
EDIT STACK TRACE AT EX:
java.lang.NullPointerException
at CarInventoryClient.actionPerformed(CarInventoryClient.java:251)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I suggest you flush the output stream before attempting to read the input stream.
The variable ex shouldn't be null. Can you give us the exact line the exception occurs on.
You should print the whole message. I suspect not printing the type and line the exception is occurring is not helping. If you have an exception with no message getMessage() will return null
try
ex.printStackTrace();
I think the output of this line is probably confusing you:
System.err.println("Error adding car to server: " + ex.getMessage());
An exception does not require a message so it is perfectly normal (as well as a bit inconvenient) that this prints:
Error adding car to server: null
By only printing the exception message you are missing out on logging crucial information such as the exception type as well as the exceptions stack trace. You are better off calling ex.printStackTrace(). Which prints the exception class, message and the stack trace of the exception.
(An elaboration of a comment above, for didactic reasons. OP has confirmed.)
If you get a stack trace that begins with a given line, it means the throw happened on that very line - not within a method called from that line. So looking at the line in question:
> java.lang.NullPointerException
> at CarInventoryClient.actionPerformed(CarInventoryClient.java:251)
serverResponse = (Message) ois.readObject();
The only way this very line could throw an NPE is if ois is null.
This was a race condition.
ois = new ObjectInputStream(socket.getInputStream());
The above line was causing the thread to block in my class's constructor. Java's documentation states that it will block until input headers are received. The action handler was sending then receiving a packet from the server - this woke the constructor code back up and finished the initialization.
When there was a thread sleep, or the debugger was attached, the constructor code would complete before the data was received. However, in real time execution, readObject was being called before the unblocked initialization could finish. This is why ois was being seen as null.
I have a question/problem related to Java Applet security...
I use the Applet that has to take files from server (ASP.NET) and represent the information from it. Applet take files using the code:
URL u = new URL(getCodeBase(), filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
This code appears in two places:
Init() method
Some another method Test() that called manually from JavaScript
So, when I try to load the page with Applet using the URL http://127.0.0.1:8000/Test.aspx, everything works fine and I can read file content from both methods. But if I change the URL on http://localhost:8000/, only the first method works properly and I can get files content and for the second one I get the next error message in JavaConsole:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
What it the difference in this case? Why 'localhost' is impossible in this case? Is there any way how to grant access to 'localhost' the same as 127.0.0.1?
here is simplest applet's example:
public class TestApplet extends Applet {
public void init()
{
System.out.println( "init...");
readDocument();
}
public void readDocument()
{
System.out.println( "read test.txt file...");
URL base = getCodeBase();
String filename = "test.txt";
try {
URL u = new URL(base, filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
System.out.println(d.readLine());
System.out.println("Done!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and next code used on the client side:
<applet archive="/Content/test.jar" code="test.TestApplet.class" name="testApplet" mayscript></applet>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var testApplet = document.testApplet;
testApplet.readDocument();
});
</script>
this code works perfectly when I try to use http://127.0.0.1:8000/Test.aspx
and doesn't work when I user http://localhost:8000/Test.aspx. I java console I see the next:
init...
read test.txt file...
some text...
Done!
read test.txt file...
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at sun.plugin2.applet.Applet2SecurityManager.checkConnect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.TestApplet.readDocument(TestApplet.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
P.S.: Applet is signed.
The problem is the call from JavaScript. If you are using JavaScript to call your method, the permissions of the call get down to the intersection of the JavaScript bridge's permissions (i.e. nothing) and the permissions of your own code - even if your own code is signed.
To avoid this, and use the full privileges of your applet's code, put the security-relevant parts inside a AccessController.doPrivileged(...) call. (Of course, your applet should first check that this can't do anything malicious.)
I have no idea why it works if you are using the IP address directly instead of localhost, though.
localhost is an alias for 127.0.0.1 so you may have to set/fix it in your enviroment. Under Windows you have to edit the file C:\Windows\System32\drivers\etc\hosts.
localhost is typically resolved to both ::1 and 127.0.0.1 and the OS/libc is usually set up so that IPv6 is preferred in these circumstances.
Therefore, it's likely you're allowing only 127.0.0.1 and not IPv6 connections from ::1.
I have a java SAX parser which I would like to call multiple times on the same Handler with different XML files. I am using this in conjunction with iText to create a multi-page PDF document where some pages have one XML tag map and other pages have another. For example,
parser.parse("xmlFile1", handler);
parser.parse("xmlFile2", handler);
When I try to do this, I get a java.lang.RuntimeException thrown with the following stacktrace:
DocumentException: java.lang.RuntimeException: The document is not open.
at com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:695)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.carriageReturn(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.add(Unknown Source)
at com.lowagie.text.Document.add(Unknown Source)
at myClass.myCode(Unknown Source)
org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:223)
at myClass.myCode(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
Does the SaxParser.parse method implicitly call document.close()? Or is there some other problem in my code which I need to isolate and correct?
Reusing the same parser is legal (as long as it is not used concurrently)
The parser triggers an "endDocument". This seems to close the iText document here.. But this is not done by the parser - this is code from your handler.
My program downloads a websites source code, modifies it, creates the file, and then reuploads it through the FTP. However, I receive the following error when trying to open the created file:
java.io.FileNotFoundException: misc.html (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at Manipulator.uploadSource(Manipulator.java:63)
at Start.addPicture(Start.java:130)
at Start$2.actionPerformed(Start.java:83)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
When I navigate to the folder directory and attempt to open "misc.html" with Notepad I receive Access is Denied. My code is fairly simple:
File f = new File(page.sourceFileName);
try {
FileWriter out = new FileWriter(f);
out.write(page.source);
out.close();
} catch (IOException e) {
e.printStackTrace();
} InputStream input = new FileInputStream(f);
This is the vital excerpt from my program. I have copied this into a different test program and it works fine, I create a misc.html file and reopen it with both FileInputStream and manually.
I would be worried about Administrator rights but the Test program works fine when I run it RIGHT after the problem program. I also have checked if the file exists and is a file with File methods and it is as well. Is this a result of me not closing a previous Input/Output properly? I've tried to check everything and I am fairly positive I close all streams as soon as they finish...
Help! :)
UPDATE:
If I comment out the FileInputStream code and just leave the FileWriter the File still is Access Denied. If I remove the FileWriter code, no File is made (so it's certainly not overwriting anything). The FileWriter code is the first time the file is made and no exception is thrown - but I still cannot manually open the file.
If you really have sufficient permissions to read that file, then the thing I can notice is that you are not using streams properly:
out.write(page.source); // if this throws an exception
out.close(); //this is not called, and the file remains open
You must close the streams in a finally block.
FileWriter fw = null;
try {
fw = new FileWriter(f);
fw.write(page.source);
} catch (IOException ex) {
ex.printStackTrace(); //consider a logger
} finally {
IOUtils.closeQuietly(fw);
}
The same goes for the InputStreams
Now, the IOUtils.closeQuietly(fw) is a bit controversial, since it will not report an exception that happens during the closing of a file. And it is from apache commons-io (external dependency). You can replace it with another try-catch inside the finally and then a null check, before calling close(). Luckily this will be a lot easier in Java 7.
This kind of error seems to happen when trying to work on a directory. Sure you don't?
Make some extra log output what you open and close, and return here....
Does your program run in as an Applet or WebStart application? If so, it is likely that the JVM sandbox is preventing your (untrusted) code from accessing the local filesystem.