Example usage for org.apache.commons.net.ftp FTPClient disconnect

List of usage examples for org.apache.commons.net.ftp FTPClient disconnect

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient disconnect.

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Closes the connection to the FTP server and restores connection parameters to the default values.

Usage

From source file:org.mule.transport.ftp.FtpConnector.java

/**
 * Well get the output stream (if any) for this type of transport. Typically this
 * will be called only when Streaming is being used on an outbound endpoint
 *
 * @param endpoint the endpoint that releates to this Dispatcher
 * @param event the current event being processed
 * @return the output stream to use for this request or null if the transport
 *         does not support streaming/*from www  . j  a v  a 2s  .com*/
 */
@Override
public OutputStream getOutputStream(OutboundEndpoint endpoint, MuleEvent event) throws MuleException {
    try {
        final EndpointURI uri = endpoint.getEndpointURI();
        String filename = getFilename(endpoint, event.getMessage());

        final FTPClient client;
        try {
            client = this.createFtpClient(endpoint);
        } catch (Exception e) {
            throw new ConnectException(e, this);
        }

        try {
            OutputStream out = client.storeFileStream(filename);
            if (out == null) {
                throw new IOException("FTP operation failed: " + client.getReplyString());
            }

            return new CallbackOutputStream(out, new CallbackOutputStream.Callback() {
                public void onClose() throws Exception {
                    try {
                        if (!client.completePendingCommand()) {
                            client.logout();
                            client.disconnect();
                            throw new IOException("FTP Stream failed to complete pending request");
                        }
                    } finally {
                        releaseFtp(uri, client);
                    }
                }
            });
        } catch (Exception e) {
            logger.debug("Error getting output stream: ", e);
            releaseFtp(uri, client);
            throw e;
        }
    } catch (ConnectException ce) {
        // Don't wrap a ConnectException, otherwise the retry policy will not go into effect.
        throw ce;
    } catch (Exception e) {
        throw new DispatchException(CoreMessages.streamingFailedNoStream(), event, endpoint, e);
    }
}

From source file:org.mule.transport.ftp.FtpMessageDispatcher.java

@Override
public RetryContext validateConnection(RetryContext retryContext) {
    FTPClient client = null;
    try {/*from   ww w  .  jav  a  2  s . c  o  m*/
        client = connector.createFtpClient(endpoint);
        client.sendNoOp();
        client.logout();
        client.disconnect();

        retryContext.setOk();
    } catch (Exception ex) {
        retryContext.setFailed(ex);
    } finally {
        try {
            if (client != null) {
                connector.releaseFtp(endpoint.getEndpointURI(), client);
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to release ftp client " + client, e);
            }

        }
    }

    return retryContext;
}

From source file:org.mule.transport.ftp.FtpMessageReceiver.java

@Override
public RetryContext validateConnection(RetryContext retryContext) {
    FTPClient client = null;
    try {/*  w w  w.  j av  a2 s.  c  o m*/
        client = connector.createFtpClient(endpoint);
        client.sendNoOp();
        client.logout();
        client.disconnect();

        retryContext.setOk();
    } catch (Exception ex) {
        retryContext.setFailed(ex);
    } finally {
        try {
            if (client != null) {
                connector.releaseFtp(endpoint.getEndpointURI(), client);
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to release ftp client " + client, e);
            }
        }
    }

    return retryContext;
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {//from   w ww.j  av  a  2 s  .  c om
        ftpClient.connect(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort());
        ftpClient.login("anonymous", "anonymous");
        ftpClient.enterLocalPassiveMode();
        String filePath = url.getPath();
        String time = ftpClient.getModificationTime(filePath);
        //logger.debug("server replied: " + time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timePart = time.split(" ")[1];
        Date modificationTime = dateFormat.parse(timePart);
        //logger.debug("parsed time: " + modificationTime);
        return modificationTime.getTime();
    } catch (Exception e) {
        logger.error("failed to parse time for url: " + url, e);
        return 0;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

From source file:org.opennms.systemreport.formatters.FtpSystemReportFormatter.java

@Override
public void end() {
    m_zipFormatter.end();/*  w  w  w .  j  av  a2  s  . co m*/
    IOUtils.closeQuietly(m_outputStream);

    final FTPClient ftp = new FTPClient();
    FileInputStream fis = null;
    try {
        if (m_url.getPort() == -1 || m_url.getPort() == 0 || m_url.getPort() == m_url.getDefaultPort()) {
            ftp.connect(m_url.getHost());
        } else {
            ftp.connect(m_url.getHost(), m_url.getPort());
        }
        if (m_url.getUserInfo() != null && m_url.getUserInfo().length() > 0) {
            final String[] userInfo = m_url.getUserInfo().split(":", 2);
            ftp.login(userInfo[0], userInfo[1]);
        } else {
            ftp.login("anonymous", "opennmsftp@");
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            LOG.error("FTP server refused connection.");
            return;
        }

        String path = m_url.getPath();
        if (path.endsWith("/")) {
            LOG.error("Your FTP URL must specify a filename.");
            return;
        }
        File f = new File(path);
        path = f.getParent();
        if (!ftp.changeWorkingDirectory(path)) {
            LOG.info("unable to change working directory to {}", path);
            return;
        }
        LOG.info("uploading {} to {}", f.getName(), path);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        fis = new FileInputStream(m_zipFile);
        if (!ftp.storeFile(f.getName(), fis)) {
            LOG.info("unable to store file");
            return;
        }
        LOG.info("finished uploading");
    } catch (final Exception e) {
        LOG.error("Unable to FTP file to {}", m_url, e);
    } finally {
        IOUtils.closeQuietly(fis);
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:org.openspice.vfs.ftp.FtpVVolume.java

public FTPClient getConnectedFTPClient() {
    Print.println(Print.VFS, "Trying to connect to FTP server ....");
    final FTPClient ftpc = this.getFTPClient();
    try {//from   w  ww . j  a  v  a 2  s.  c o m
        if (!ftpc.isConnected()) {
            Print.println(Print.VFS, "Not connected - trying to reconnect");
            this.reconnect(ftpc);
        }
        ftpc.noop();
    } catch (final FTPConnectionClosedException e) {
        try {
            ftpc.disconnect();
            this.reconnect(ftpc);
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    //      try {
    ftpc.enterLocalPassiveMode();
    //         ftpc.setSoTimeout( 30 * 1000 );         //   Set 30 second timeout.
    //      } catch ( SocketException e ) {
    //         throw new RuntimeException( e );
    //      }
    return ftpc;
}

From source file:org.oss.digitalforms.MobileFormsImpl.java

private void ftpValidations(String ftpHost, String user, String password) throws Exception {
    FTPClient ftp = new FTPClient();
    ftp.connect(ftpHost);//w ww. ja v  a  2s  .c  o  m
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
    }
    ftp.login(user, password);
    ftp.listFiles();
    ftp.disconnect();
}

From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java

/**
 * @see JavaExecutable#execute(TaskResult[])
 *///from www  .  ja  va  2 s  .c o  m
@Override
public Serializable execute(TaskResult... results) throws IOException {
    List<String> filesRelativePathName;
    FTPClient ftpClient = new FTPClient();

    try {
        //connect to the server
        ftpClient.connect(ftpHostname, ftpPort);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            throw new IOException("Exception in connecting to FTP Server");
        }
        //login to the server
        if (!ftpClient.login(ftpUsername, ftpPassword)) {
            throw new IOException("Logging refused. check the FTP_USERNAME and FTP_PASSWORD values.");
        }

        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode();

        getOut().println("Connected");

        switch (ftpMode) {
        //FTP mode is GET
        case GET:
            filesRelativePathName = ftpGet(ftpClient);
            break;

        //FTP mode is PUT
        case "PUT":
            filesRelativePathName = ftpPut(ftpClient);
            break;

        default:
            throw new IllegalArgumentException("FTP MODE can only be " + PUT + " or " + GET);

        }
    } finally {
        // log out and disconnect from the server
        ftpClient.logout();
        ftpClient.disconnect();
        getOut().println("Disconnected");
    }
    return (Serializable) filesRelativePathName;
}

From source file:org.pepstock.jem.node.resources.impl.ftp.FtpFactory.java

/**
 * Creates and configures a FtpClient instance based on the
 * given properties./* w w  w  . ja  v  a  2s .co  m*/
 * 
 * @param properties the ftp client configuration properties
 * @return remote input/output steam
 * @throws JNDIException if an error occurs creating the ftp client
 */
private Object createFtpClient(Properties properties) throws JNDIException {
    // URL is mandatory
    String ftpUrlString = properties.getProperty(CommonKeys.URL);
    if (ftpUrlString == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.URL);
    }

    // creates URL objects
    // from URL string
    URL ftpUrl;
    try {
        ftpUrl = new URL(ftpUrlString);
    } catch (MalformedURLException e) {
        throw new JNDIException(NodeMessage.JEMC233E, e, ftpUrlString);
    }
    // checks scheme
    // if SSL, activates a FTPS
    if (!ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL)
            && !ftpUrl.getProtocol().equalsIgnoreCase(FTPS_PROTOCOL)) {
        throw new JNDIException(NodeMessage.JEMC137E, ftpUrl.getProtocol());
    }

    // gets port the host (from URL)
    int port = ftpUrl.getPort();
    String server = ftpUrl.getHost();

    // User id is mandatory
    String username = properties.getProperty(CommonKeys.USERID);
    if (username == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.USERID);
    }

    // password is mandatory
    String password = properties.getProperty(CommonKeys.PASSWORD);
    if (password == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.PASSWORD);
    }

    // checks if as input stream or not
    boolean asInputStream = Parser
            .parseBoolean(properties.getProperty(FtpResourceKeys.AS_INPUT_STREAM, "false"), false);

    String remoteFile = null;
    String accessMode = null;
    if (asInputStream) {
        // remote file is mandatory
        // it must be set by a data description
        remoteFile = properties.getProperty(FtpResourceKeys.REMOTE_FILE);
        if (remoteFile == null) {
            throw new JNDIException(NodeMessage.JEMC136E, FtpResourceKeys.REMOTE_FILE);
        }
        // access mode is mandatory
        // it must be set by a data description
        accessMode = properties.getProperty(FtpResourceKeys.ACTION_MODE, FtpResourceKeys.ACTION_READ);
    }

    // creates a FTPclient 
    FTPClient ftp = ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL) ? new FTPClient() : new FTPSClient();

    // checks if binary
    boolean binaryTransfer = Parser.parseBoolean(properties.getProperty(FtpResourceKeys.BINARY, "false"),
            false);

    // checks if must be restarted
    long restartOffset = Parser.parseLong(properties.getProperty(FtpResourceKeys.RESTART_OFFSET, "-1"), -1);

    // checks and sets buffer size
    int bufferSize = Parser.parseInt(properties.getProperty(FtpResourceKeys.BUFFER_SIZE, "-1"), -1);

    try {
        // reply code instance
        int reply;
        // connect to server
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();
        // if not connected for error, EXCEPTION
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new JNDIException(NodeMessage.JEMC138E, reply);
        }
        // login!!
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        // set all ftp properties
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // sets restart offset if has been set
        if (restartOffset >= 0) {
            ftp.setRestartOffset(restartOffset);
        }

        // sets buffer size
        if (bufferSize >= 0) {
            ftp.setBufferSize(bufferSize);
        }

        // if is not related to a data descritpion,
        // returns a FTP object
        if (!asInputStream) {
            return new Ftp(ftp);
        }

        // checks if is in WRITE mode
        if (accessMode.equalsIgnoreCase(FtpResourceKeys.ACTION_WRITE)) {
            // gets outputstream
            // using the file name passed by data descritpion
            OutputStream os = ftp.storeFileStream(remoteFile);
            if (os == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns outputstream
            return new FtpOutputStream(os, ftp);
        } else {
            // gest inputstream
            // using the file name passed by data descritpion
            InputStream is = ftp.retrieveFileStream(remoteFile);
            if (is == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns inputstream 
            return new FtpInputStream(is, ftp);
        }
    } catch (SocketException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    } catch (IOException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    }
}

From source file:org.pepstock.jem.node.resources.impl.ftp.FtpUtil.java

/**
 * Close the FTP client connection//from   w  w w  . j  a va2 s  . com
 * @param ftp ftp client instance
 * @throws IOException if any IO error occurs
 */
public static void close(FTPClient ftp) throws IOException {
    try {
        // checks if connected
        if (ftp.isConnected()) {
            // close FTP connection
            ftp.logout();
        }
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                // ignore
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}