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.
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 wonder about a Java error that is repeatedly occurs in MATLAB. It typically occurs when MATLAB is doing some heavy stuff with Java. This can for example be holding Ctrl + Z or Ctrl + Y.
I did by mistake erase the error message before I copied it, but I think that I can pass the core of the problem anyway.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Why did this error occur? I have found some information about this from MATLAB r2007, this due to that Java Swing is thread unsafe and MATLAB lacked support to ensure thread safety. However, that is supposed to have been fixed in MATLAB r2008b. So why do I get it now?
Here is the full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.netbeans.editor.BaseDocument.notifyUnmodify(BaseDocument.java:1465)
at org.netbeans.editor.BaseDocument.notifyModifyCheckEnd(BaseDocument.java:816)
at org.netbeans.editor.BaseDocumentEvent.redo(BaseDocumentEvent.java:336)
at javax.swing.undo.UndoManager.redoTo(Unknown Source)
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
at org.netbeans.editor.ActionFactory$RedoAction.actionPerformed(ActionFactory.java:767)
at org.netbeans.editor.BaseAction.actionPerformed(BaseAction.java:259)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at com.mathworks.widgets.SyntaxTextPaneBase.processKeyEvent(SyntaxTextPaneBase.java:1187)
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.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(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)
Well, based on your stack trace, probably there isn’t any definitive answer to your question, as you have already seen in MATLAB's forum, but given this line, I think there's a possible explanation:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at javax.swing.undo.UndoManager.redoTo(Unknown Source) // <-- here!
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
...
UndoManager class keeps an internal collection of UndoableEdit objects. This collection is actually inherithed from its superclass: CompoundEdit.
The internal implementation of UndoManager#redo() and UndoManager#redoTo(UndoableEdit edit) looks like this:
public class UndoManager extends CompoundEdit implements UndoableEditListener {
...
public synchronized void redo() throws CannotRedoException {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
if (edit == null) {
throw new CannotRedoException();
}
redoTo(edit);
} else {
super.redo();
}
}
...
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
boolean done = false;
while (!done) {
UndoableEdit next = edits.elementAt(indexOfNextAdd++);
next.redo(); // NPE here?
done = next == edit;
}
}
...
}
Considering this implementation and given that Swing's Event Dispatch Thread (EDT) is prone to cause troubles, I think it's probably a threading issue between MATLAB threads and the EDT. Specifically speaking this MATLAB-invoked method could be the source of the problem:
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
Since you say MATLAB needs to do heavy work, it's not unreasonable to think this method is trying to redo some edit that might well not be available anymore or might not be available yet, due to synchronization problems with the EDT.
You can find the ~/.matlab folder which contains MATLAB settings, etc. Use ls -la to show all hidden files and folders.
Open a terminal and execute sudo chmod 757 -R ~/.matlab.
Similarly there is a folder, MATLAB, in Documents.
Execute sudo chmod 757 -R ~/Documents/MATLAB.
Now restart MATLAB without root privileges. It worked for me on Ubuntu 14.04 (Trusty Tahr) and MATLAB 2015a.
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'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.