-1

I am working on a java application in which I am facing a problem. When I send a file to a server and an exception is thrown, the file is not sent. How can I retry sending the file?

       public void uploadtxtFile(String localFileFullName, String fileName, String hostDir)
                throws Exception {
            File file = new File(localFileFullName);
            if (!(file.isDirectory())) {
                if (file.exists()) {
                    FileInputStream input = null;
                   try {
                        input = new FileInputStream(new File(localFileFullName));
                        if (input != null) {
                            hostDir = hostDir.replaceAll("//", "/");
                           logger.info("uploading host dir : " + hostDir);
                     //new 

//                       TestThread testThread=new TestThread(hostDir,input);
//                      Thread t=new Thread(testThread);
//                  
//                      try{
//                          t.start();
//                          
//                      }catch(Exception ex){
//                          logger.error("UPLOADE start thread create exception new:" + ex);
//                      }
//                      // new end

                        DBConnection.getFTPConnection().enterLocalPassiveMode();
                        // the below line exeption is come
                      boolean bool = DBConnection.getFTPConnection().storeFile(hostDir, input);
                       //input.close();//new comment
                           if (bool) {
                               logger.info("Success uploading file on host dir :"+hostDir);
                          } else {
                                logger.error("file  not uploaded.");
                        }
                      } else {
                             logger.error("uploading file input null.");
                 }
                 }catch(CopyStreamException cs)
                    {   logger.error("Copy StreamExeption is come "+cs);
                    } catch(Exception ex)
                    {
                         logger.error("Error in connection ="+ex);//this is catch where I handle the exeption

                    }finally {
    //                  boolean disconnect= DBConnection.disConnect();
                        input.close();
                   }

                } else {
                     logger.info("uploading file is not exists.");
                }
            }
        }

This is the code and I want to restart the file uploading but I don't have any idea. I tried it using the thread but the exception is thrown again. I also tried to use a while loop, but it loops infinitely and also shows the exception as well as another exception. Below is the thread code that I use:

public void run() {

               System.out.println("Enter Thread TestThread");

               DBConnection.getFTPConnection().enterLocalPassiveMode();
                 //  System.out.println("Error in DBConnection ");
                  //here server timeout error is get


                  boolean bool1=false;

                   boolean bool=true;
                    try {
                    bool = DBConnection.getFTPConnection().storeFile(hostDir1, input1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    e.printStackTrace();


                    }finally {
                        //disconnect();

                    try {
                    input1.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                        e.printStackTrace();
                        }
                   }

                   if (bool) {
                       System.out.println("File is Uploded");
                    } else {

                    while(bool!=true){
                    try {
                         DBConnection.getFTPConnection().enterLocalPassiveMode();
                            bool1=DBConnection.getFTPConnection().storeFile(hostDir1, input1);

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }finally {
                            //disconnect();

                            try {
                            input1.close();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                            e.printStackTrace();
                            }
                    }
                     System.out.println("file  not uploaded."+bool1);
                         bool=bool1;
                   }
            }
              }
    }
              }

Can any one have a solution to how to upload the file to the server?

The exception is shown below:

  1. Software caused connection abort: recv failed
  2. Software caused connection abort: socket write error
  3. org.apache.commons.net.io.CopyStreamException: IOException caught while copying.
Axel
  • 13,939
  • 5
  • 50
  • 79
Ravi Jat
  • 11
  • 1
  • 6
  • How do you know that this is a retryable problem? Does the upload fail only intermittently? – Dakshinamurthy Karra Aug 05 '15 at 06:36
  • Exceptions are thrown for a reason. Instead of trying as hard as possible to ignore them, you should instead focus on finding out why they're thrown in the first place. If, say, your firewall is pulling the plug on that connection, you can retry as often as you want, it won't change anything. Also give [this question](https://stackoverflow.com/q/2126607) a read, and try to inspect your connection with a tool like Wireshark, to see what's really going on there. – Siguza Aug 05 '15 at 06:38
  • i dont know it is retrtyable problem or not but i try to retry it. I don't know how to use the Wireshark to check the connection and my firewall in all ready turn off – Ravi Jat Aug 05 '15 at 07:05
  • i have no idea why the exception is come it bcz its not come every time and i dont know how to solve that its come in this line boolean bool = DBConnection.getFTPConnection().storeFile(hostDir, input);can you have any way to solve that – Ravi Jat Aug 05 '15 at 07:08

2 Answers2

0

Add a static class as below in a class from where you are calling the method which need to be retried:

static class RetryOnExceptionStrategy {
public static final int DEFAULT_RETRIES = 3;
public static final long DEFAULT_WAIT_TIME_IN_MILLI = 2000;

private int numberOfRetries;
private int numberOfTriesLeft;
private long timeToWait;

public RetryOnExceptionStrategy() {
    this(DEFAULT_RETRIES, DEFAULT_WAIT_TIME_IN_MILLI);
}

public RetryOnExceptionStrategy(int numberOfRetries,
        long timeToWait) {
    this.numberOfRetries = numberOfRetries;
    numberOfTriesLeft = numberOfRetries;
    this.timeToWait = timeToWait;
}

/**
 * @return true if there are tries left
 */
public boolean shouldRetry() {
    return numberOfTriesLeft > 0;
}

public void errorOccured() throws Exception {
    numberOfTriesLeft--;
    if (!shouldRetry()) {
        throw new Exception("Retry Failed: Total " + numberOfRetries
                + " attempts made at interval " + getTimeToWait()
                + "ms");
    }
    waitUntilNextTry();
}

public long getTimeToWait() {
    return timeToWait;
}

private void waitUntilNextTry() {
    try {
        Thread.sleep(getTimeToWait());
    } catch (InterruptedException ignored) {
    }
}
}   

Now wrap your method call as below in a while loop :

RetryOnExceptionStrategy errorStrategy=new RetryOnExceptionStrategy();
while(errorStrategy.shouldRetry()){
try{
 //Method Call
}
catch(Exception excep){
 errorStrategy.errorOccured();
}
}

Basically you are just wrapping you method call in while loop which will keep returnig true till your retry count is reached to zero say you started with 3.

Every time an exception occurred, the exception is caught and a method is called which will decrement your retryCount and method call is again executed with some delay.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

A general way of working with such application is:

  1. Create a class, say, UploadWorker which extends Callable as the wrapper. Make the wrapper return any error and detail information you need when it fails.
  2. Create a ExecutorService (basically a thread pool) for this wrapper to run in threads.
  3. Submit your UploadWorker instance and then you get a Future. Call get() on the future to wait in blocking way or simply wait some time for the result.
  4. In case the get() returns you the error message, submit your worker again to the thread pool.
Alex Suo
  • 2,977
  • 1
  • 14
  • 22