Java FTP not working inside SwingWorker Thread - java

I have a simple GUI program that does some interactions with a database then once its completed ftps up some files to a server. This has worked perfectly until I added a SwingWorker thread to keep the GUI responsive.
The code I am using works fine if I put it in its standalone project but inside this project (SwingWorker thread) it gives me the following error:
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at sun.nio.cs.StreamDecoder.read0(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at it.sauronsoftware.ftp4j.NVTASCIIReader.readLine(NVTASCIIReader.java:105)
at it.sauronsoftware.ftp4j.FTPCommunicationChannel.read(FTPCommunicationChannel.java:142)
at it.sauronsoftware.ftp4j.FTPCommunicationChannel.readFTPReply(FTPCommunicationChannel.java:187)
at it.sauronsoftware.ftp4j.FTPClient.openActiveDataTransferChannel(FTPClient.java:3511)
at it.sauronsoftware.ftp4j.FTPClient.openDataTransferChannel(FTPClient.java:3475)
at it.sauronsoftware.ftp4j.FTPClient.upload(FTPClient.java:2641)
at it.sauronsoftware.ftp4j.FTPClient.upload(FTPClient.java:2550)
at it.sauronsoftware.ftp4j.FTPClient.upload(FTPClient.java:2421)
at GUI$MatchFiles.doInBackground(GUI.java:1602)
at GUI$MatchFiles.doInBackground(GUI.java:1)
at javax.swing.SwingWorker$1.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at javax.swing.SwingWorker.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Any ideas?
EDIT:
I assume you mean something like this? Please note this is a very trimmed down version, I have removed a lot of superfluous code. I cant see any of it affecting this.
class Worker extends SwingWorker<Integer, Integer>{
protected Integer doInBackground() throws Exception{
FTPClient client = new FTPClient();
client.connect(url);
client.login(username, password);
client.setPassive(false);
client.changeDirectory(uploaddirectory);
client.upload(new File(fileuploadpath));
client.disconnect(true);
}
protected void done() {
System.out.println("Done");
}
}
As said, I take this code inside the swingworker and put it in its own class and it runs perfect.

It looks like your socket is cut-off by your firewall or anti-virus... Try disabling the firewall and anti-virus and re-run your program...

Related

java.net.SocketException: Permission denied: connect. What could be the cause and how to avoid it?

I'm running into a java.net.SocketException (Permission denied: connect) when sending a lot of requests to a server. I've tried the -Djava.net.preferIPv4Stack=true option as mentioned in other threads.
This issue only occurs after a lot of connections have already been made. The following code can be used to reproduce the issue:
public class Example {
public static void main(String[] args) {
if(args.length == 1) {
System.out.println(args[0]);
for(int i = 0; i < Integer.MAX_VALUE; i++) {
requestURL(args[0]);
}
}
}
public static void requestURL(String targetUrl) {
URL url = new URL(targetUrl);
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//handle response here
rd.close();
httpCon.disconnect();
}
}
The code will successfully send the requests until the Exception occurs. This has been verified in the server's log files.
Please run the sample code only against a server that you are permitted to, as it generates quite a bit of traffic / load on the server.
So the question now is: How to avoid that Exception? Or any workarounds? And what is the actually issue here?
EDIT
added httpCon.disconnect(). (doesn't solve the problem)
EDIT #2 (StackTrace)
java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(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.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.connect(Unknown Source)
at Example.requestUrl(Example.java)
at Example.main(Example.java)
When the issue occurs no further requests are sent to the server (no log entries on the server and no SYN packets (sniffed with tcpdump)).
EDIT #3
I've forgotten to run the application with the -Djava.net.preferIPv4Stack=true argument.
It hasn't thrown an exception yet when using both, the aforementioned argument and the httpCon.disconnect() method.
Try to use httpCon.disconnect() to be sure to realease the socket after you finish to read the response.

Java Game - ClassCastException

I am developing a simple java game and my scrollbar is raising an exception.
The scrollbar is supposed to be a "gameslider".
Exception in thread "Thread-3" java.lang.ClassCastException: sun.java2d.NullSurfaceData cannot be cast to sun.java2d.d3d.D3DSurfaceData
at sun.java2d.d3d.D3DRenderer.copyArea(Unknown Source)
at sun.java2d.d3d.D3DSurfaceData.copyArea(Unknown Source)
at sun.java2d.SunGraphics2D.doCopyArea(Unknown Source)
at sun.java2d.SunGraphics2D.copyArea(Unknown Source)
at javax.swing.BufferStrategyPaintManager.copyArea(Unknown Source)
at javax.swing.RepaintManager.copyArea(Unknown Source)
at javax.swing.JViewport.blitDoubleBuffered(Unknown Source)
at javax.swing.JViewport.windowBlitPaint(Unknown Source)
at javax.swing.JViewport.setViewPosition(Unknown Source)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.hsbStateChanged(Unknown Source)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.fireStateChanged(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.setRangeProperties(Unknown Source)
at javax.swing.DefaultBoundedRangeModel.setValue(Unknown Source)
at javax.swing.JScrollBar.setValue(Unknown Source)
at GameEnvironment.GamePanel.gameUpdate(GamePanel.java:171)
at GameEnvironment.GamePanel.run(GamePanel.java:73)
at java.lang.Thread.run(Unknown Source)
Code Line is following:
if (reachedMiddle)
scrollPane.getHorizontalScrollBar().setValue(player.getX() - (widthHorizontalScrollBar / 2));
The exception will be raised more or less randomly. I didnt figured it out so far.
I would make sure this code is run on the GUI Event Thread. If you call the Swing components on other threads you can get strange, randonm errors.
Have a look at using SwingUtilities.invokeLater(Runnable) to perform the tasks where the Swing components are updated.

Handle Applet throwing java.lang.ExceptionInInitializerError preventing it from running

We are developing java applet and embedding it in our web pages. When the applet is loaded via HTML APPLET tags, the browser/JVM prompts the user to allow it to run. When we hit cancel, the java console indicates the following exception:
java.lang.RuntimeException: java.lang.ExceptionInInitializerError
at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(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.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.security.AccessControlException: access denied (java.lang.RuntimePermission getenv.TEMP)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.System.getenv(Unknown Source)
at downLoadApp.<clinit>(downLoadApp.java:15)
... 21 more
Exception: java.lang.RuntimeException: java.lang.ExceptionInInitializerError
Now, I realize it's most likely because the class java tried to load was prevented from loading, and therefore the exception is thrown, but how do we gracefully handle this situation in the browser? I'd like to detect that the applet was denied and post a reasonable response to the condition, but I'm unaware of how to catch this exception since it appears to have been thrown by the JVM in reaction to not getting the jar file to load rather than code written in it...
Ideas?
Thanks!
You can catch the access control exception by putting the call to System.getenv in downLoadApp.java line 15 in a try-catch statement. That is, instead of this:
static String tmp = System.getenv("TEMP");
you should have:
static String tmp;
static {
try {
tmp = System.getenv("TEMP");
} catch (java.security.AccessControlException ace) {
// tmp is not set, maybe use some default value?
}
}
Do you call System.getenv("TEMP") somewhere in the static context of the downLoadApp class? Most probably this is in the initializer of a static field, but it could be in a static code block.
This is the place where it fails (a java.security.AccessControlException is thrown). The rest of the stack trace are errors following from that. You need to catch this exception to detect that you don't have the appropriate permissions.
As you can't catch exceptions of static field initializers, you need to move the call to getenv into a method or a static code block.
I don't think that you can catch this exception as this is thrown by JVM while loading applet.

JApplet gets a java.lang.OutOfMemoryError exception on ObjectInputStream.readObject(Unknown Source)

I've written a JApplet that that connects to a server. On connecting it receives an ImageIcon. On receipt it send a String "I" to the server to confirm. This signals the server to send the next imageIcon.
while(noExceptions){
try{
Object something = in.readObject();
if(something instanceof ImageIcon){
camDisplay.setIcon( (ImageIcon)something );
validate();
sendMessage("I");
}else{
System.out.println("What the hell was that?!");
}
Runtime rt = Runtime.getRuntime();
rt.gc();
}catch(Exception e){
noExceptions=false;
...
}
}
I added the call to the garbage collector when I first got the exception but it didn't help. I put in some printlns and it always crashes on the 128th image. Exception is thrown at Object something = in.readObject();
camDisplay is a JLabel that is shown in the applet.
Exception in thread "Thread-12" java.lang.OutOfMemoryError: Java heap space
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at javax.swing.ImageIcon.readObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at RoboClient.run(RoboClient.java:226)
at java.lang.Thread.run(Unknown Source)
FIX:
System.out.println((sendImageCount++)+" send image");
out.writeUnshared( new ImageIcon(_image) );
out.flush();
if(sendImageCount>100){
out.reset();
sendImageCount=0;
}
See ObjectOutputStream.reset() and ObjectOutputStream.writeUnshared().
One crude way to address this problem is to flush the inputstream after retrieving every x(say 50 in this case) ImageIcons and close the inputStream and reOpen to get the remaining ImageIcons. Now the GC will be able to garbage the earlier retrived imageicons.
Looks like the Inputstream holds the references of the ImageIcons which is preventing from Gced.

ISSUE java.lang.IllegalStateException: zip file closed

I have created a jar file which throws the below error, it's a simple swing app which inserts a row when I press a button, not sure where I am going wrong please advise.
private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
setatmid(jTextField2.getText());
setaa10(Integer.parseInt(jTextField3.getText()));
setaa20(Integer.parseInt(jTextField4.getText()));
setaa50(Integer.parseInt(jTextField5.getText()));
setaa100(Integer.parseInt(jTextField6.getText()));
try{
System.err.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "agents";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
con = DriverManager.getConnection(url+db,"root","");
Statement st = con.createStatement();
String query="INSERT INTO schedule_data (`s_ID`, `schedule_date`, `atmID`, `notification`) VALUES ('"+System.currentTimeMillis()+"','2010-09-15','"+getatmid()+"','null')";
st.executeUpdate(query);
System.err.println("1 row affected");
} catch(Exception e) {
e.printStackTrace();
}
}
Error:
java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(Unknown Source)
at java.util.zip.ZipFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getJarEntry(Unknown Source)
at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
at sun.misc.URLClassPath.getResource(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at atmguis.atm.jButton20ActionPerformed(atm.java:588)
at atmguis.atm.access$1600(atm.java:25)
at atmguis.atm$17.actionPerformed(atm.java:226)
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)
The method involved is being called from the Event Dispatch Thread. I'm sure this is a part of the problem. You are trying to access the JAR file containing the com.mysql.jdbc.Driver class from this thread. This is where the error is being thrown. I have to wonder if there is some sort of concurrency issue here. Here are a couple of general notes, things that should be addressed. Once you have addressed these issues, see if you are still having a problem.
You should not be doing a database query from inside the EDT. You should collect the information you need from the swing components and then use a Runnable object to execute the SQL query on a different thread. Do a search on SO for executing code on or off the EDT to find examples of how to do this. This will ensure that your UI doesn't lock up while you wait for your SQL results.
Opening and closing a database connection every time you need one is something better left to the SQL driver and its built-in connection pooling abilities. This method should be declared on some sort of controller object which already has a reference to the SQL connection. Then, when this method is called, you call your thread as in the last step, and that thread uses the reference to the SQL connection that it already has.
This will take the line that's throwing the exception and move it out of the EDT into some sort of setup phase, presumably where you will have better luck accessing the class file. Certainly it will be a much more controlled environment than within the EDT. If there continues to be a problem accessing it, it will be easier to debug in the more controlled environment.
As an added bonus, you will also be designing your application in much more robust way.

Categories

Resources