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

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

Introduction

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

Prototype

public void setDefaultPort(int port) 

Source Link

Document

Sets the default port the SocketClient should connect to when a port is not specified.

Usage

From source file:ch.cyberduck.core.ftp.FTPSession.java

protected void configure(final FTPClient client) throws IOException {
    client.setProtocol(host.getProtocol());
    client.setSocketFactory(socketFactory);
    client.setControlEncoding(host.getEncoding());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);// ww w .j a va 2s. c  o m
    client.setDefaultTimeout(timeout);
    client.setDataTimeout(timeout);
    client.setDefaultPort(host.getProtocol().getDefaultPort());
    client.setParserFactory(new FTPParserFactory());
    client.setRemoteVerificationEnabled(preferences.getBoolean("ftp.datachannel.verify"));
    final int buffer = preferences.getInteger("ftp.socket.buffer");
    client.setBufferSize(buffer);

    if (preferences.getInteger("connection.buffer.receive") > 0) {
        client.setReceiveBufferSize(preferences.getInteger("connection.buffer.receive"));
    }
    if (preferences.getInteger("connection.buffer.send") > 0) {
        client.setSendBufferSize(preferences.getInteger("connection.buffer.send"));
    }
    if (preferences.getInteger("connection.buffer.receive") > 0) {
        client.setReceieveDataSocketBufferSize(preferences.getInteger("connection.buffer.receive"));
    }
    if (preferences.getInteger("connection.buffer.send") > 0) {
        client.setSendDataSocketBufferSize(preferences.getInteger("connection.buffer.send"));
    }
    client.setStrictMultilineParsing(preferences.getBoolean("ftp.parser.multiline.strict"));
    client.setStrictReplyParsing(preferences.getBoolean("ftp.parser.reply.strict"));
}

From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }/*from w  w w.  j  av a 2  s .  co m*/
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}

From source file:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/*from  w  w w.java 2  s.co  m*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.glassfish.common.util.admin.MapInjectionResolver.java

private void FormatUriToFile() throws IOException {
    List<String> value = parameters.get("DEFAULT");
    String uri = value.get(0);//from   w  w  w  . ja  va  2s . c  om
    URL url = new URL(uri);
    File file = null;

    if (uri.startsWith("file:/")) {
        file = new File(url.getFile());
    } else if (uri.startsWith("http://")) {
        InputStream inStream = url.openStream();
        BufferedInputStream bufIn = new BufferedInputStream(inStream);

        file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
        if (file.exists()) {
            file.delete();
        }
        OutputStream out = new FileOutputStream(file);
        BufferedOutputStream bufOut = new BufferedOutputStream(out);
        byte buffer[] = new byte[204800];
        while (true) {
            int nRead = bufIn.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            bufOut.write(buffer, 0, nRead);
        }
        bufOut.flush();
        out.close();
        inStream.close();
    } else if (uri.startsWith("ftp://")) {
        String pattern = "^ftp://(.+?)(:.+?)?@(\\S+):(\\d+)(\\S+)$";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(uri);
        if (m.matches()) {
            String username = m.group(1);
            String password = "";
            if (m.group(2) != null) {
                password = m.group(2).replace(":", "");
            }
            String ipAddress = m.group(3);
            String port = m.group(4);
            String path = m.group(5);
            FTPClient ftp = new FTPClient();
            ftp.connect(ipAddress);
            ftp.setDefaultPort(Integer.parseInt(port));
            boolean isLogin = ftp.login(username, password);
            if (isLogin) {
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                byte[] buf = new byte[204800];
                int bufsize = 0;

                file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
                if (file.exists()) {
                    file.delete();
                }
                OutputStream ftpOut = new FileOutputStream(file);
                InputStream ftpIn = ftp.retrieveFileStream(path);
                System.out.println(ftpIn);
                while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
                    ftpOut.write(buf, 0, bufsize);
                }
                ftpOut.flush();
                ftpOut.close();
                ftpIn.close();
            } else {
                ftp.logout();
                ftp.disconnect();
            }
        } else {
            localStrings.getLocalString("IncorrectFtpAddress",
                    "The ftp address is not correct, please change another one.");
        }
    }
    if (file != null)
        parameters.set("DEFAULT", file.getAbsolutePath());
}