Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * $Id: SftpUtil.java 21125 2011-01-26 21:21:10Z dzapata $
   * --------------------------------------------------------------------------------------
   * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
   *
   * The software in this package is published under the terms of the CPAL v1.0
   * license, a copy of which has been included with this distribution in the
   * LICENSE.txt file.
   */
 
 package org.mule.transport.sftp;
 
 import java.io.File;
 import java.util.Date;
 
Contains reusable methods not directly related to usage of the jsch sftp library (they can be found in the class SftpClient).

Author(s):
Magnus Larsson
 
 public class SftpUtil
 {
    
Logger
 
     private static final Logger logger = Logger.getLogger(SftpUtil.class);
 
     private SftpConnector connector;
     private ImmutableEndpoint endpoint;
 
     private static final boolean KEEP_FILE_ON_ERROR_DEFAULT = true;
     private static final boolean USE_TEMP_FILE_TIMESTAMP_SUFFIX_DEFAULT = false;
     private static final long SIZE_CHECK_WAIT_TIME_DEFAULT = -1;
 
     private final static Object lock = new Object();
 
     public SftpUtil(ImmutableEndpoint endpoint)
     {
         this. = endpoint;
         this. = (SftpConnectorendpoint.getConnector();
     }
 
     public String createUniqueSuffix(String filename)
     {
 
         // TODO. Add code for handling no '.'
         int fileTypeIdx = filename.lastIndexOf('.');
         String fileType = filename.substring(fileTypeIdx); // Let the fileType
                                                            // include the leading '.'
 
         filename = filename.substring(0, fileTypeIdx); // Strip off the leading '/'
                                                        // from the filename
 
         SimpleDateFormat timestampFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
         String timstampStr = '_' + timestampFormatter.format(new Date());
 
         return filename + timstampStr + fileType;
     }
 
     public String getTempDirInbound()
     {
         String endpointValue = (String.getProperty(.);
         if (endpointValue != null)
         {
             return endpointValue;
         }
 
         String connectorValue = .getTempDirInbound();
         if (connectorValue != null)
         {
             return connectorValue;
         }
 
         return null;
     }
 
     public boolean isUseTempDirInbound()
     {
         return getTempDirInbound() != null;
     }
 
     public String getTempDirOutbound()
     {
         String endpointValue = (String.getProperty(.);
         if (endpointValue != null)
         {
             return endpointValue;
         }
 
         String connectorValue = .getTempDirOutbound();
         if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }
    public boolean isUseTempDirOutbound()
    {
        return getTempDirOutbound() != null;
    }
    public void cleanupTempDir(SftpClient sftpClientString transferFileNameString tempDir)
    {
        String tempDirAbs = sftpClient.getAbsolutePath(.getEndpointURI().getPath() + "/" + tempDir);
        try
        {
            sftpClient.changeWorkingDirectory(tempDirAbs);
            sftpClient.deleteFile(transferFileName);
        }
        catch (Exception e)
        {
            .error("Could not delete the file '" + transferFileName + "' from the temp directory '"
                         + tempDirAbs + "'"e);
        }
    }
    public long getSizeCheckWaitTime()
    {
        if (endpointValue != null)
        {
            return Long.valueOf((StringendpointValue);
        }
        Long connectorValue = .getSizeCheckWaitTime();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return ;
    }
    public String getArchiveDir()
    {
        String endpointValue = (String.getProperty(.);
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getArchiveDir();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }
    {
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getArchiveTempReceivingDir();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }
    {
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getArchiveTempSendingDir();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }
    public boolean isUseTempFileTimestampSuffix()
    {
        if (endpointValue != null)
        {
            return Boolean.valueOf((StringendpointValue);
        }
        Boolean connectorValue = .isUseTempFileTimestampSuffix();
        if (connectorValue != null)
        {
            return connectorValue;
        }
    }
    public String getDuplicateHandling()
    {
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getDuplicateHandling();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return ;
    }
    public String getIdentityFile()
    {
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getIdentityFile();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }
    public String getPassphrase()
    {
        String endpointValue = (String.getProperty(.);
        if (endpointValue != null)
        {
            return endpointValue;
        }
        String connectorValue = .getPassphrase();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return null;
    }

    
Changes the directory to the temp-dir on the outbound endpoint. Will create the directory if it not already exists.

Note, this method is synchronized because it in rare cases can be called from two threads at the same time and thus cause an error.

Parameters:
sftpClient
endpointDir
Throws:
java.io.IOException
    public void cwdToTempDirOnOutbound(SftpClient sftpClientString endpointDirthrows IOException
    {
        String tempDir = getTempDirOutbound();
        String tempDirAbs = sftpClient.getAbsolutePath(endpointDir + "/" + tempDir);
        // We need to have a synchronized block if two++ threads tries to
        // create the same directory at the same time
        synchronized ()
        {
            // Try to change directory to the temp dir, if it fails - create it
            try
            {
                // This method will throw an exception if the directory does not
                // exist.
                sftpClient.changeWorkingDirectory(tempDirAbs);
            }
            catch (IOException e)
            {
                .info("Got an exception when trying to change the working directory to the temp dir. "
                            + "Will try to create the directory " + tempDirAbs);
                sftpClient.changeWorkingDirectory(endpointDir);
                sftpClient.mkdir(tempDir);
                // Now it should exist!
                sftpClient.changeWorkingDirectory(tempDirAbs);
            }
        }
    }
    public boolean isKeepFileOnError()
    {
        if (endpointValue != null)
        {
            return Boolean.valueOf((StringendpointValue);
        }
        Boolean connectorValue = .isKeepFileOnError();
        if (connectorValue != null)
        {
            return connectorValue;
        }
        return ;
    }

    
Should be moved to a util class that is not based on an endpoint... TODO: why is this method synchronized?

Parameters:
input
destination
Throws:
java.io.IOException
    public synchronized void copyStreamToFile(InputStream inputFile destinationthrows IOException
    {
        try
        {
            File folder = destination.getParentFile();
            if (!folder.exists())
            {
                throw new IOException("Destination folder does not exist: " + folder);
            }
            if (!folder.canWrite())
            {
                throw new IOException("Destination folder is not writeable: " + folder);
            }
            FileOutputStream output = new FileOutputStream(destination);
            try
            {
                IOUtils.copy(inputoutput);
            }
            finally
            {
                if (output != nulloutput.close();
            }
        }
        catch (IOException ex)
        {
            setErrorOccurredOnInputStream(input);
            throw ex;
        }
        catch (RuntimeException ex)
        {
            setErrorOccurredOnInputStream(input);
            throw ex;
        }
        finally
        {
            if (input != nullinput.close();
        }
    }
    public void setErrorOccurredOnInputStream(InputStream inputStream)
    {
        if (isKeepFileOnError())
        {
            // If an exception occurs and the keepFileOnError property is
            // true, keep the file on the originating endpoint
            // Note: this is only supported when using the sftp transport on
            // both inbound & outbound
            if (inputStream != null)
            {
                if (inputStream instanceof ErrorOccurredDecorator)
                {
                    // Ensure that the SftpInputStream or
                    // SftpFileArchiveInputStream knows about the error and
                    // dont delete the file
                    ((ErrorOccurredDecoratorinputStream).setErrorOccurred();
                }
                else
                {
                    .warn("Class "
                                + inputStream.getClass().getName()
                                + " did not implement the 'ErrorOccurred' decorator, errorOccured=true could not be set.");
                }
            }
        }
    }
New to GrepCode? Check out our FAQ X