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

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

Introduction

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

Prototype

public boolean logout() throws IOException 

Source Link

Document

Logout of the FTP server by sending the QUIT command.

Usage

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

@Override
public RetryContext validateConnection(RetryContext retryContext) {
    FTPClient client = null;
    try {//w w  w .  ja v a2 s.  co 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.n52.sos.importer.controller.Step1Controller.java

@Override
public boolean isFinished() {

    if (step1Panel != null && step1Panel.getFeedingType() == Step1Panel.CSV_FILE) {
        final String filePath = step1Panel.getCSVFilePath();
        if (filePath == null) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }/*from   w w w. j ava 2 s  .c  om*/
        // checks one-time feed input data for validity
        if (filePath.equals("")) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }

        final File dataFile = new File(filePath);
        if (!dataFile.exists()) {
            JOptionPane.showMessageDialog(null, "The specified file does not exist.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.isFile()) {
            JOptionPane.showMessageDialog(null, "Please specify a file, not a directory.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.canRead()) {
            JOptionPane.showMessageDialog(null, "No reading access on the specified file.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
        readFile(dataFile, step1Panel.getFileEncoding());
    } else if (step1Panel != null && (step1Panel.getFeedingType() == Step1Panel.FTP_FILE)) {
        // checks repetitive feed input data for validity
        if (step1Panel.getUrl() == null || step1Panel.getUrl().equals("")) {
            JOptionPane.showMessageDialog(null, "No ftp server was specified.", "Server missing",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (step1Panel.getFilenameSchema() == null || step1Panel.getFilenameSchema().equals("")) {
            JOptionPane.showMessageDialog(null, "No file/file schema was specified.",
                    "File/file schema missing", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        // ftp client
        FTPClient client;

        // proxy
        final String pHost = System.getProperty("proxyHost", "proxy");
        int pPort = -1;
        if (System.getProperty("proxyPort") != null) {
            pPort = Integer.parseInt(System.getProperty("proxyPort"));
        }
        final String pUser = System.getProperty("http.proxyUser");
        final String pPassword = System.getProperty("http.proxyPassword");
        if (pHost != null && pPort != -1) {
            if (pUser != null && pPassword != null) {
                client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
            }
            client = new FTPHTTPClient(pHost, pPort);
        } else {
            client = new FTPClient();
        }

        // get first file
        if (step1Panel.getFeedingType() == Step1Panel.FTP_FILE) {
            final String csvFilePath = System.getProperty("user.home") + File.separator + ".SOSImporter"
                    + File.separator + "tmp_" + step1Panel.getFilenameSchema();

            // if back button was used: delete old file
            if (new File(csvFilePath).exists()) {
                new File(csvFilePath).delete();
            }

            try {
                client.connect(step1Panel.getUrl());
                final boolean login = client.login(step1Panel.getUser(), step1Panel.getPassword());
                if (login) {
                    // download file
                    final int result = client.cwd(step1Panel.getDirectory());
                    if (result == 250) { // successfully connected
                        final File outputFile = new File(csvFilePath);
                        final FileOutputStream fos = new FileOutputStream(outputFile);
                        client.retrieveFile(step1Panel.getFilenameSchema(), fos);
                        fos.flush();
                        fos.close();
                    }
                    final boolean logout = client.logout();
                    if (logout) {
                        logger.info("Step1Controller: cannot logout!");
                    }
                } else {
                    logger.info("Step1Controller: cannot login!");
                }

                final File csv = new File(csvFilePath);
                if (csv.length() != 0) {
                    step1Panel.setCSVFilePath(csvFilePath);
                    readFile(new File(csvFilePath), step1Panel.getFileEncoding());
                } else {
                    csv.delete();
                    throw new IOException();
                }

            } catch (final SocketException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            } catch (final IOException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
    }

    return true;
}

From source file:org.n52.sos.importer.feeder.task.OneTimeFeeder.java

private DataFile getRemoteFile(final Configuration config) {
    File dataFile = null;//  w w  w  . j  a  v  a2 s . c  o m

    // ftp client
    FTPClient client;

    // proxy
    final String pHost = System.getProperty("proxyHost", "proxy");
    int pPort = -1;
    if (System.getProperty("proxyPort") != null) {
        pPort = Integer.parseInt(System.getProperty("proxyPort"));
    }
    final String pUser = System.getProperty("http.proxyUser");
    final String pPassword = System.getProperty("http.proxyPassword");
    if (pHost != null && pPort != -1) {
        LOG.info("Using proxy for FTP connection!");
        if (pUser != null && pPassword != null) {
            client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
        }
        client = new FTPHTTPClient(pHost, pPort);
    } else {
        LOG.info("Using no proxy for FTP connection!");
        client = new FTPClient();
    }

    // get first file
    final String directory = config.getConfigFile().getAbsolutePath();
    dataFile = FileHelper.createFileInImporterHomeWithUniqueFileName(directory + ".csv");

    // if back button was used: delete old file
    if (dataFile.exists()) {
        dataFile.delete();
    }

    try {
        client.connect(config.getFtpHost());
        final boolean login = client.login(config.getUser(), config.getPassword());
        if (login) {
            LOG.info("FTP: connected...");
            // download file
            final int result = client.cwd(config.getFtpSubdirectory());
            LOG.info("FTP: go into directory...");
            if (result == 250) { // successfully connected
                final FileOutputStream fos = new FileOutputStream(dataFile);
                LOG.info("FTP: download file...");
                client.retrieveFile(config.getFtpFile(), fos);
                fos.flush();
                fos.close();
            } else {
                LOG.info("FTP: cannot go to subdirectory!");
            }
            final boolean logout = client.logout();
            if (!logout) {
                LOG.info("FTP: cannot logout!");
            }
        } else {
            LOG.info("FTP:  cannot login!");
        }

    } catch (final SocketException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    } catch (final IOException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    }

    return new DataFile(config, dataFile);
}

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

/**
 * @see JavaExecutable#execute(TaskResult[])
 *//*  w  w w. ja  v  a  2 s.co 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 ww .  ja va  2  s. c  om*/
 * 
 * @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/*w w w. jav  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.ramadda.repository.monitor.FtpAction.java

/**
 * _more_/* www.ja va 2  s  .  c om*/
 *
 *
 * @param monitor _more_
 * @param entry _more_
 */
protected void entryMatched(EntryMonitor monitor, Entry entry) {
    FTPClient ftpClient = new FTPClient();
    try {
        Resource resource = entry.getResource();
        if (!resource.isFile()) {
            return;
        }
        if (server.length() == 0) {
            return;
        }

        String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false);
        ftpClient.connect(server);
        if (user.length() > 0) {
            ftpClient.login(user, password);
        }
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            monitor.handleError("FTP server refused connection:" + server, null);

            return;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (directory.length() > 0) {
            ftpClient.changeWorkingDirectory(directory);
        }

        String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate);

        InputStream is = new BufferedInputStream(
                monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath())));
        boolean ok = ftpClient.storeUniqueFile(filename, is);
        is.close();
        if (ok) {
            monitor.logInfo("Wrote file:" + directory + " " + filename);
        } else {
            monitor.handleError("Failed to write file:" + directory + " " + filename, null);
        }
    } catch (Exception exc) {
        monitor.handleError("Error posting to FTP:" + server, exc);
    } finally {
        try {
            ftpClient.logout();
        } catch (Exception exc) {
        }
        try {
            ftpClient.disconnect();
        } catch (Exception exc) {
        }
    }
}

From source file:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_/*from www  .j  a  v  a 2s . c o m*/
 *
 * @param ftpClient _more_
 */
private static void closeConnection(FTPClient ftpClient) {
    try {
        ftpClient.logout();
    } catch (Exception exc) {
    }
    try {
        ftpClient.disconnect();
    } catch (Exception exc) {
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_//from   w  ww  .  j av  a 2 s . c o m
 *
 * @param ftpClient _more_
 */
public static void closeConnection(FTPClient ftpClient) {
    try {
        ftpClient.logout();
    } catch (Exception exc) {
    }
    try {
        ftpClient.disconnect();
    } catch (Exception exc) {
    }
}

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  .ja va 2 s. c  o  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;
}