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.
Related
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.
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've built this actionPerformed method so that it reads a string I pass to the button (I needed to make my own button class to hold this new string) and depending on what it says, it does a different action. One of the possibilities of the string is to be something like: shell(""). This is supposed to run a system command (command line in windows, shell command in unix/linux) in the background. This is the source of the method:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.button) {
if (password != "") {
}
if (action.startsWith("shell(\"")) {
String tmpSHELL = action.substring(7, action.length() - 2);
try {
Process p = Runtime.getRuntime().exec(tmpSHELL);
} catch (IOException e1) {
ErrorDialog error = new ErrorDialog("Error handling your shell action");
System.exit(0);
}
}
else if (action.startsWith("frame(\"")) {
String tmpFRAME = action.substring(7, action.length() - 2);
MenuFrame target = ConfigReader.getFrame(tmpFRAME);
this.parent.setVisible(false);
this.parent.validate();
target.setVisible(true);
target.validate();
}
else if (action.equals("exit()")) {
System.exit(0);
}
else {
ErrorDialog error = new ErrorDialog("You config file contains an invalid action command. Use either shell(), frame() or exit()");
System.exit(0);
}
}
}
I know that I get into the method but I'm not sure if the command is being executed successfully. I'm currently in a windows environment so I made a simple batch script that echos some text then waits for a keystroke before printing the tree of the C: drive. I put the .bat into my working java directory and passed the string shell("test") (test is the name of the batch file). However, when I click the button I get an error dialog (the one I coded above).
Is there something wrong with my code or maybe my understanding of how executing a shell command works in java? The command is throwing an IO exception but I can't seem to figure out why. Thanks in advance for your help.
Stacktrace:
java.io.IOException: Cannot run program "test": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Button.actionPerformed(Button.java:52)
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)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 30 more
The system cannot find the file specified
Your file path is not right. Try passing an absolute file path.
shell("C:/somedirectory/test.bat")
Also, you can test this by removing the string test altogether. Hard code the runtime execution of the batch file by making the if statement always true and passing the path to your batch file to the Runtime.getRuntime().exec()
if (password != "") {
}
if (true) {
String tmpSHELL = action.substring(7, action.length() - 2);
try {
Process p = Runtime.getRuntime().exec("test");
} catch (IOException e1) {
ErrorDialog error = new ErrorDialog("Error handling your shell action");
System.exit(0);
}
}
This should produce the same error. Then replace the file path with an absolute file path and you should be able to execute the batch file.
Process p = Runtime.getRuntime().exec("C:/somedirectory/test.bat");
On Windows try command line:
"cmd test /c"
It's because the command test isn't found in the system PATH environment variable.
If you go to the command line and type test it will fail. This is what the exception is indicating.
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.