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

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

Introduction

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

Prototype

public boolean isConnected() 

Source Link

Document

Returns true if the client is currently connected to a server.

Usage

From source file:org.middleheaven.io.repository.ftp.TestFTP.java

private FTPClient connect() {
    try {/*  w  ww.  j av  a2 s .c om*/
        FTPClient ftp = new FTPClient();
        if (!ftp.isConnected()) {
            ftp.connect("184.107.197.226");
            ftp.login("javabuil", "%Q&4pr|!O}=");
        }

        return ftp;
    } catch (IOException e) {
        throw ManagedIOException.manage(e);
    }
}

From source file:org.mousephenotype.dcc.crawler.Downloader.java

private void closeOpenConnections() {
    // close all ftp connections
    Iterator<Entry<String, FTPClient>> ci = ftpConnections.entrySet().iterator();
    while (ci.hasNext()) {
        Entry<String, FTPClient> item = ci.next();
        FTPClient c = item.getValue();
        if (c.isConnected()) {
            try {
                c.logout();/*from  ww  w  .  j a va2s. c  o  m*/
                c.disconnect();
                logger.debug("Downloader has disconnected from '{}'", item.getKey());
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        ci.remove();
    }

    // close all sftp channels (before closing sessions)
    Iterator<Entry<String, ChannelSftp>> ch = sftpChannels.entrySet().iterator();
    while (ch.hasNext()) {
        Entry<String, ChannelSftp> item = ch.next();
        ChannelSftp c = item.getValue();
        if (c.isConnected()) {
            c.disconnect();
            logger.debug("Downloader has closed sftp channel with '{}'", item.getKey());
        }
        ch.remove();
    }

    // close all sftp sessions
    Iterator<Entry<String, Session>> se = sftpSessions.entrySet().iterator();
    while (se.hasNext()) {
        Entry<String, Session> item = se.next();
        Session c = item.getValue();
        if (c.isConnected()) {
            c.disconnect();
            logger.debug("Downloader has closed sftp session with '{}'", item.getKey());
        }
        se.remove();
    }
}

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

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {//from w  w  w .j av  a  2s .  co m
        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 a  va  2 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 w w. j a va2s  .  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.pepstock.jem.node.resources.impl.ftp.FtpUtil.java

/**
 * Close the FTP client connection/*  w  ww  .  ja v  a 2 s  .c  o  m*/
 * @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);
            }
        }
    }
}

From source file:org.programmatori.domotica.own.plugin.remote.FTPUtility.java

/**
 * Funzione che consente la disconnessione da un Server FTP
 * //w  ww.ja  v  a2 s .  com
 * @param ftp Offetto di tipo FTPClient utilizzato per l'accesso
 * @return >0 se tutto funziona correttamente; <0 in caso di errori
 */
public static int disconnect(FTPClient ftp) {
    if (ftp.isConnected()) {
        try {
            ftp.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }
    log.info("Disconnessione avvenuta con successo.");
    return 1;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*w  w  w . j av a  2  s.co  m*/
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:org.spongepowered.repoindexer.FTPUtils.java

public static boolean uploadFTP(String user, String pass, String server, File local, String remoteLocation) {
    FTPClient ftpClient = new FTPClient();
    boolean done = false;
    try {/*  w  ww . j a va 2s  . c  o  m*/

        ftpClient.connect(server);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        InputStream inputStream = new FileInputStream(local);
        done = ftpClient.storeFile(remoteLocation, inputStream);
        inputStream.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
        return false;
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return done;
    }
}

From source file:org.wso2.carbon.connector.FileFtpOverProxy.java

/**
 * Send file FTP over Proxy.//from  w w  w .jav a2s .c  o  m
 *
 * @param proxyHost      Name of the proxy host.
 * @param proxyPort      Proxy port number.
 * @param proxyUsername  User name of the proxy.
 * @param proxyPassword  Password of the proxy.
 * @param ftpServer      FTP server.
 * @param ftpPort        Port number of FTP.
 * @param ftpUsername    User name of the FTP.
 * @param ftpPassword    Password of the FTP.
 * @param messageContext he message context that is generated for processing the ftpOverHttp method.
 * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server.
 */
public boolean ftpOverHttp(String proxyHost, String proxyPort, String proxyUsername, String proxyPassword,
        String ftpServer, String ftpPort, String ftpUsername, String ftpPassword,
        MessageContext messageContext) {
    String keepAliveTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.KEEP_ALIVE_TIMEOUT);
    String controlKeepAliveReplyTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT);
    String targetPath = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_PATH);
    String targetFile = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_FILE);
    String binaryTransfer = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.BINARY_TRANSFER);
    String localActive = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.LOCAL_ACTIVE);
    boolean resultStatus = false;
    InputStream inputStream = null;

    final FTPClient ftp;
    if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)
            && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) {
        proxyHost = proxyHost.trim();
        proxyPort = proxyPort.trim();
        proxyUsername = proxyUsername.trim();
        proxyPassword = proxyPassword.trim();
        ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword);
    } else {
        ftp = new FTPClient();
    }
    //Set the time to wait between sending control connection keep alive messages when
    // processing file upload or download (Zero (or less) disables).
    keepAliveTimeout = keepAliveTimeout.trim();
    if (StringUtils.isNotEmpty(keepAliveTimeout)) {
        ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout.trim()));
    }
    //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.)
    if (StringUtils.isNotEmpty(controlKeepAliveReplyTimeout)) {
        ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout.trim()));
    }
    try {
        int reply;
        ftpPort = ftpPort.trim();
        int IntFtpPort = Integer.parseInt(ftpPort);
        if (IntFtpPort > 0) {
            ftp.connect(ftpServer, IntFtpPort);
        } else {
            ftpServer = ftpServer.trim();
            ftp.connect(ftpServer);
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    " Connected to " + ftpServer + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort()));
        }
        // After connection attempt, should check the reply code to verify success.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP ftpServer refused connection.");
        }
        if (ftp.login(ftpUsername, ftpPassword)) {
            if (StringUtils.isNotEmpty(binaryTransfer)) {
                if (Boolean.valueOf(binaryTransfer.trim())) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                } else {
                    // in theory this should not be necessary as servers should default to ASCII
                    // but they don't all do so - see NET-500
                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                }
            } else {
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }
            // Use passive mode as default because most of us are behind firewalls these days.
            if (StringUtils.isNotEmpty(localActive)) {
                if (Boolean.valueOf(localActive.trim())) {
                    ftp.enterLocalActiveMode();
                } else {
                    ftp.enterLocalPassiveMode();
                }
            } else {
                ftp.enterLocalPassiveMode();
            }
            inputStream = new ByteArrayInputStream(
                    messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes());
            if (StringUtils.isNotEmpty(targetPath)) {
                ftp.changeWorkingDirectory(targetPath);
                ftp.storeFile(targetFile, inputStream);
                if (log.isDebugEnabled()) {
                    log.debug("Successfully FTP transfered the File");
                }
            }
            // check that control connection is working
            if (log.isDebugEnabled()) {
                log.debug("The code received from the server." + ftp.noop());
            }
            resultStatus = true;
        } else {
            ftp.logout();
            handleException("Error while login ftp server.", messageContext);
        }
    } catch (FTPConnectionClosedException e) {
        // log.error("Server closed connection " + e.getMessage(), e);
        handleException("Server closed connection: " + e.getMessage(), e, messageContext);
    } catch (IOException e) {
        //log.error("Error occurred while uploading:" + e.getMessage(), e);
        handleException("Could not connect to FTP ftpServer: " + e.getMessage(), e, messageContext);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
                ftp.logout();
            } catch (IOException f) {
                log.error("Error while disconnecting/logging out ftp server");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException f) {
                log.error("Error while closing inputStream");
            }
        }
    }
    return resultStatus;
}