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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {//from w  w  w .ja v a 2s  .c om
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }
        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }
        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }/*from  ww w .j av a  2  s. c  om*/
    final FTPClient ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(30);
    ftp.setControlKeepAliveReplyTimeout(30);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        ftp.connect(ftpSubscription.getFtpHost());
        _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (final IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }
    boolean error = false;
    __main: try {
        if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) {
            ftp.logout();
            error = true;
            break __main;
        }
        _log.info("Remote system is " + ftp.getSystemType());
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        //ftp.enterLocalActiveMode();
        ftp.enterLocalPassiveMode();
        //final FTPClientConfig config = new FTPClientConfig();
        ////config.setLenientFutureDates(true);
        //ftp.configure(config);
        if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) {
            ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder());
        }
        final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile());
        if (is == null) {
            _log.error("FIle not found: " + ftp.getSystemType());
        } else {
            unzip(ftpSubscription, is);
            is.close();
        }
        ftp.completePendingCommand();
    } catch (final FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (final IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException e) {
                _log.error(e);
            }
        }
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates a connection to a target host and then executes an FTP
 * request to send or receive a file to or from the target. This is fully
 * key-based, as a result, a keyfile is required for the connection to
 * successfully authenticate./*from www . j  a v  a 2 s .  co m*/
 * 
 * @param sourceFile - The full path to the source file to transfer
 * @param targetFile - The full path (including file name) of the desired target file
 * @param targetHost - The target server to perform the transfer to
 * @param isUpload - <code>true</code> is the transfer is an upload, <code>false</code> if it
 *            is a download 
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeFtpConnection(final String sourceFile, final String targetFile,
        final String targetHost, final boolean isUpload) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", sourceFile);
        DEBUGGER.debug("Value: {}", targetFile);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", isUpload);
    }

    final FTPClient client = new FTPClient();
    final FTPConfig ftpConfig = appBean.getConfigData().getFtpConfig();

    if (DEBUG) {
        DEBUGGER.debug("FTPClient: {}", client);
        DEBUGGER.debug("FTPConfig: {}", ftpConfig);
    }

    try {
        client.connect(targetHost);

        if (DEBUG) {
            DEBUGGER.debug("FTPClient: {}", client);
        }

        if (!(client.isConnected())) {
            throw new IOException("Failed to authenticate to remote host with the provided information");
        }

        boolean isAuthenticated = false;

        if (StringUtils.isNotBlank(ftpConfig.getFtpAccount())) {
            isAuthenticated = client.login(
                    (StringUtils.isNotEmpty(ftpConfig.getFtpAccount())) ? ftpConfig.getFtpAccount()
                            : System.getProperty("user.name"),
                    PasswordUtils.decryptText(ftpConfig.getFtpPassword(), ftpConfig.getFtpSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        } else {
            isAuthenticated = client.login(ftpConfig.getFtpAccount(), null);
        }

        if (DEBUG) {
            DEBUGGER.debug("isAuthenticated: {}", isAuthenticated);
        }

        if (!(isAuthenticated)) {
            throw new IOException("Failed to connect to FTP server: " + targetHost);
        }

        client.enterLocalPassiveMode();

        if (!(FileUtils.getFile(sourceFile).exists())) {
            throw new IOException("File " + sourceFile + " does not exist. Skipping");
        }

        if (isUpload) {
            client.storeFile(targetFile, new FileInputStream(FileUtils.getFile(sourceFile)));
        } else {
            client.retrieveFile(sourceFile, new FileOutputStream(targetFile));
        }

        if (DEBUG) {
            DEBUGGER.debug("Reply: {}", client.getReplyCode());
            DEBUGGER.debug("Reply: {}", client.getReplyString());
        }
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if (client.isConnected()) {
                client.completePendingCommand();
                client.disconnect();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();//from   w ww. j  a v a  2s.c  o  m
            return client;
        } else {
            // this flowFile is going to a different destination, reset
            // session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).evaluateAttributeExpressions(flowFile)
            .getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

private static ArrayList<String> listFiles(final BackgroundTaskStatusProviderSupportingExternalCall status,
        String downloadURL, String server, String remotePath, final FTPClient ftp) {
    String username;/*from w  ww.  jav  a  2 s .co  m*/
    String password;
    username = "anonymous@" + server;
    password = "anonymous";

    final ObjectRef myoutputstream = new ObjectRef();

    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText1("Command: " + arg0.getMessage());
        }

        public void protocolReplyReceived(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText2("Message: " + arg0.getMessage());
            if (myoutputstream.getObject() != null) {
                String msg = arg0.getMessage();
                if (msg.indexOf("Opening BINARY mode") >= 0) {
                    if (msg.indexOf("(") > 0) {
                        msg = msg.substring(msg.indexOf("(") + "(".length());
                        if (msg.indexOf(" ") > 0) {
                            msg = msg.substring(0, msg.indexOf(" "));
                            try {
                                long max = Long.parseLong(msg);
                                MyOutputStream os = (MyOutputStream) myoutputstream.getObject();
                                os.setMaxBytes(max);
                            } catch (Exception e) {
                                System.out.println(
                                        "Could not determine file length for detailed progress information");
                            }
                        }
                    }
                }
            }
        }
    });

    System.out.println("FTP LIST DIRECTORY: " + downloadURL);

    try {
        if (ftp.isConnected()) {
            status.setCurrentStatusText2("Using open FTP connection");
            System.out.println("Reusing open FTP connection");
        } else {
            ftp.connect(server);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                status.setCurrentStatusText1("Can't connect to FTP server");
                status.setCurrentStatusText2("ERROR");
                return new ArrayList<String>();
            }
            if (!ftp.login("anonymous", "anonymous")) {
                if (!ftp.login(username, password)) {
                    ftp.disconnect();
                    status.setCurrentStatusText1("Can't login to FTP server");
                    status.setCurrentStatusText2("ERROR");
                    return new ArrayList<String>();
                }
            }
            status.setCurrentStatusText1("Set Binary Transfer Mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            status.setCurrentStatusText2("Activate Passive Transfer Mode");
            ftp.enterLocalPassiveMode();
        }
        status.setCurrentStatusText1("Start download...");
        status.setCurrentStatusText2("Please Wait.");

        ftp.setRemoteVerificationEnabled(false);

        FTPFile[] res = ftp.listFiles(remotePath);

        ArrayList<String> result = new ArrayList<String>();

        for (FTPFile r : res) {
            result.add(r.getName());
        }

        return result;
    } catch (Exception err) {
        ErrorMsg.addErrorMessage(err);
        if (ftp != null && ftp.isConnected()) {
            try {
                System.out.println("Disconnect FTP connection (following error condition)");
                ftp.disconnect();
            } catch (Exception err2) {
                ErrorMsg.addErrorMessage(err2);
            }
        }
        return new ArrayList<String>();
    }
}

From source file:com.droid.app.fotobot.FotoBot.java

public boolean files_to_ftp(List<String> FTP_files) {
    String server;/*w  w w  .  jav a 2  s .  c o  m*/
    int port;
    String user;
    String pass;

    String FTP_folder = "";

    if (FTP_server.contains("/")) {

        FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1));
        FTP_folder = FTP_folder.substring(1);

        server = FTP_server.substring(0, FTP_server.indexOf("/", 1));
    } else {
        server = FTP_server;
    }

    port = Integer.parseInt(FTP_port);
    user = FTP_username;
    pass = FTP_password;

    SendMessage("FTP user: " + "<br>" + user, MSG_PASS);
    SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS);
    SendMessage("FTP server: " + "<br>" + server, MSG_PASS);

    FTPClient ftpClient = new FTPClient();

    try {
        int reply;

        ftpClient.connect(server, port);
        System.out.println("Connected to " + server + ".");
        System.out.print(ftpClient.getReplyString());
        reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");
            SendMessage("FTP   ?", MSG_FAIL);
            return false;
        }
    } catch (Exception e) {
    }

    try {
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(
                    " ?   FTP ?,      FTP  ?.",
                    MSG_FAIL);
            return false;
        }
    } catch (Exception e) {

    }

    // chdir

    if (FTP_folder.length() > 1) {
        try {
            ftpClient.changeWorkingDirectory(FTP_folder);

            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("FTP chdir error");
                SendMessage(
                        "FTP  ?    <br>" + FTP_folder,
                        MSG_FAIL);
                return false;
            }

            SendMessage("FTP   <br>" + FTP_folder, MSG_PASS);
            System.out.println("Successfully changed working directory.");
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            SendMessage("FTP  ?    <br>" + FTP_folder,
                    MSG_FAIL);
            System.out.println("Failed to change working directory.");
            return false;
        }
    }

    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (Exception e) {
        SendMessage("FTP   BINARY_FILE_TYPE", MSG_FAIL);
        System.out.println("Failed to change to BINARY_FILE_TYPE.");
        return false;
    }

    // APPROACH #1: uploads first file using an InputStream

    for (String str : FTP_files) {
        File firstLocalFile = new File(str);

        String firstRemoteFile = firstLocalFile.getName();

        try {
            InputStream inputStream = new FileInputStream(firstLocalFile);

            SendMessage("? ", MSG_PASS);
            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
            inputStream.close();

            if (done) {
                SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS);
            }
        } catch (IOException ex) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(" ?  " + "<br>" + str + "<br>"
                    + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage()
                    + "<br>"
                    + "     FTP  ?.",
                    MSG_FAIL);
            ex.printStackTrace();
        }

    }

    try {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
            SendMessage("FTP ???? ", MSG_PASS);
            fbpause(h, 3);
            return true;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        SendMessage("FTP ???? ", MSG_FAIL);
    }

    return false;

}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

private static boolean processDownload(final BackgroundTaskStatusProviderSupportingExternalCallImpl status,
        String downloadURL, String targetFileName, ObjectRef lastStatus, final int thisRun, String server,
        String remote, final FTPClient ftp) {
    String username;//from   w  w w. ja v a  2  s . c o  m
    String password;
    String local;
    username = "anonymous@" + server;
    password = "anonymous";
    local = targetFileName;

    final ObjectRef myoutputstream = new ObjectRef();

    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent arg0) {
            // System.out.print("out: " + arg0.getMessage());
            status.setCurrentStatusText1("Command: " + arg0.getMessage());
        }

        public void protocolReplyReceived(ProtocolCommandEvent arg0) {
            // System.out.print("in : " + arg0.getMessage());
            status.setCurrentStatusText2("Message: " + arg0.getMessage());
            if (myoutputstream.getObject() != null) {
                String msg = arg0.getMessage();
                if (msg.indexOf("Opening BINARY mode") >= 0) {
                    if (msg.indexOf("(") > 0) {
                        msg = msg.substring(msg.indexOf("(") + "(".length());
                        if (msg.indexOf(" ") > 0) {
                            msg = msg.substring(0, msg.indexOf(" "));
                            try {
                                long max = Long.parseLong(msg);
                                MyOutputStream os = (MyOutputStream) myoutputstream.getObject();
                                os.setMaxBytes(max);
                            } catch (Exception e) {
                                System.out.println(
                                        "Could not determine file length for detailed progress information");
                            }
                        }
                    }
                }
            }
        }
    });

    System.out.println("FTP DOWNLOAD: " + downloadURL);

    try {
        if (ftp.isConnected()) {
            status.setCurrentStatusText2("Using open FTP connection");
            System.out.println("Reusing open FTP connection");
        } else {
            ftp.connect(server);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                status.setCurrentStatusText1("Can't connect to FTP server");
                status.setCurrentStatusText2("ERROR");
                return false;
            }
            if (!ftp.login("anonymous", "anonymous")) {
                if (!ftp.login(username, password)) {
                    ftp.disconnect();
                    status.setCurrentStatusText1("Can't login to FTP server");
                    status.setCurrentStatusText2("ERROR");
                    return false;
                }
            }
            status.setCurrentStatusText1("Set Binary Transfer Mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            status.setCurrentStatusText2("Activate Passive Transfer Mode");
            ftp.enterLocalPassiveMode();
        }
        status.setCurrentStatusText1("Start download...");
        status.setCurrentStatusText2("Please Wait.");

        // ftp.listFiles(pathname);

        OutputStream output = new MyOutputStream(lastStatus, status, new FileOutputStream(local));
        myoutputstream.setObject(output);
        ftp.setRemoteVerificationEnabled(false);
        long tA = System.currentTimeMillis();
        boolean result = ftp.retrieveFile(remote, output);
        output.close();
        long tB = System.currentTimeMillis();
        if (!result) {
            new File(local).delete();
            MainFrame.showMessage("Can't download " + downloadURL + ". File not available.", MessageType.INFO);
        } else {
            File f = new File(local);
            System.out.println("Download completed (" + f.getAbsolutePath() + ", " + (f.length() / 1024)
                    + " KB, " + (int) ((f.length() / 1024d / (tB - tA) * 1000d)) + " KB/s).");
        }
        BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() {
            public void run() {
                try {
                    synchronized (GUIhelper.class) {
                        if (runIdx == thisRun) {
                            System.out.println("Disconnect FTP connection");
                            ftp.disconnect();
                        }
                    }
                } catch (Exception err) {
                    ErrorMsg.addErrorMessage(err);
                }
            }
        });
        return result;
    } catch (Exception err) {
        System.out.println("ERROR: FTP DOWNLOAD ERROR: " + err.getMessage());
        if (ftp != null && ftp.isConnected()) {
            try {
                System.out.println("Disconnect FTP connection (following error condition)");
                ftp.disconnect();
            } catch (Exception err2) {
                ErrorMsg.addErrorMessage(err2);
            }
        }
        return false;
    }
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();// ww w. j  a  v a2s . c  om
            return client;
        } else {
            // this flowFile is going to a different destination, reset session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    // additional  
    FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    final String ftpClientConfig = ctx.getProperty(FTP_CLIENT_CONFIG_SYST).getValue();
    if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_UNIX)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    } else if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_NT)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'FTPTargetFile' function will get the FTP details and send off the generated file
 *
 * @param batchId The id of the batch to FTP the file for
 *//*from   w  w  w  .j av  a 2s  .c om*/
private void FTPTargetFile(int batchId, configurationTransport transportDetails) throws Exception {

    try {

        /* Update the status of the batch to locked */
        transactionOutDAO.updateBatchStatus(batchId, 22);

        List<transactionTarget> targets = transactionOutDAO.getTransactionsByBatchDLId(batchId);

        if (!targets.isEmpty()) {

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 22, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 37);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 37);

            }

        }

        /* get the batch details */
        batchDownloads batchFTPFileInfo = transactionOutDAO.getBatchDetails(batchId);

        /* Get the FTP Details */
        configurationFTPFields ftpDetails = configurationTransportManager
                .getTransportFTPDetailsPush(transportDetails.getId());

        if ("SFTP".equals(ftpDetails.getprotocol())) {

            JSch jsch = new JSch();
            Session session = null;
            ChannelSftp channel = null;
            FileInputStream localFileStream = null;

            String user = ftpDetails.getusername();
            int port = ftpDetails.getport();
            String host = ftpDetails.getip();

            Organization orgDetails = organizationManager.getOrganizationById(
                    configurationManager.getConfigurationById(transportDetails.getconfigId()).getorgId());

            if (ftpDetails.getcertification() != null && !"".equals(ftpDetails.getcertification())) {

                File newFile = null;

                fileSystem dir = new fileSystem();
                dir.setDir(orgDetails.getcleanURL(), "certificates");

                jsch.addIdentity(new File(dir.getDir() + ftpDetails.getcertification()).getAbsolutePath());
                session = jsch.getSession(user, host, port);
            } else if (ftpDetails.getpassword() != null && !"".equals(ftpDetails.getpassword())) {
                session = jsch.getSession(user, host, port);
                session.setPassword(ftpDetails.getpassword());
            }

            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(2000);

            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");

            channel.connect();

            if (ftpDetails.getdirectory() != null && !"".equals(ftpDetails.getdirectory())) {
                channel.cd(ftpDetails.getdirectory());

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                if (file.exists()) {
                    FileInputStream fileInput = new FileInputStream(file);

                    channel.put(fileInput, fileName);
                }

            }

            channel.disconnect();
            session.disconnect();

        } else {
            FTPClient ftp;

            if ("FTP".equals(ftpDetails.getprotocol())) {
                ftp = new FTPClient();
            } else {
                FTPSClient ftps;
                ftps = new FTPSClient(true);

                ftp = ftps;
                ftps.setTrustManager(null);
            }

            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            ftp.setDefaultTimeout(3000);
            ftp.setConnectTimeout(3000);

            if (ftpDetails.getport() > 0) {
                ftp.connect(ftpDetails.getip(), ftpDetails.getport());
            } else {
                ftp.connect(ftpDetails.getip());
            }

            int reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
            } else {
                ftp.login(ftpDetails.getusername(), ftpDetails.getpassword());

                ftp.enterLocalPassiveMode();

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                FileInputStream fileInput = new FileInputStream(file);

                ftp.changeWorkingDirectory(ftpDetails.getdirectory());
                ftp.storeFile(fileName, fileInput);
                ftp.logout();
                ftp.disconnect();

            }
        }

        // we should delete file now that we ftp'ed the file
        try {
            fileSystem dir = new fileSystem();
            String filelocation = transportDetails.getfileLocation();
            filelocation = filelocation.replace("/bowlink/", "");
            dir.setDirByName(filelocation);

            File sourceFile = new File(dir.getDir() + batchFTPFileInfo.getoutputFIleName());
            if (sourceFile.exists()) {
                sourceFile.delete();
            }

            transactionOutDAO.updateBatchStatus(batchId, 23);

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 23, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 20);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 20);

            }

        } catch (Exception e) {
            throw new Exception(
                    "Error occurred during FTP - delete file and update statuses. batchId: " + batchId, e);

        }
    } catch (Exception e) {
        throw new Exception("Error occurred trying to FTP a batch target. batchId: " + batchId, e);
    }

}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@Override
public void publishWebArchiveArtifact(@NotNull String subscriptionId, @NotNull String webSpaceName,
        @NotNull String webSiteName, @NotNull String artifactPath, @NotNull boolean isDeployRoot,
        @NotNull String artifactName) throws AzureCmdException {
    WebSitePublishSettings webSitePublishSettings = getWebSitePublishSettings(subscriptionId, webSpaceName,
            webSiteName);//from   ww  w.ja  v a2s.  c  o m
    WebSitePublishSettings.FTPPublishProfile publishProfile = null;
    for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
        if (pp instanceof FTPPublishProfile) {
            publishProfile = (FTPPublishProfile) pp;
            break;
        }
    }

    if (publishProfile == null) {
        throw new AzureCmdException("Unable to retrieve FTP credentials to publish web site");
    }

    URI uri;

    try {
        uri = new URI(publishProfile.getPublishUrl());
    } catch (URISyntaxException e) {
        throw new AzureCmdException("Unable to parse FTP Publish Url information", e);
    }

    final FTPClient ftp = new FTPClient();

    try {
        ftp.connect(uri.getHost());
        final int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new AzureCmdException("Unable to connect to FTP server");
        }

        if (!ftp.login(publishProfile.getUserName(), publishProfile.getPassword())) {
            ftp.logout();
            throw new AzureCmdException("Unable to login to FTP server");
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (publishProfile.isFtpPassiveMode()) {
            ftp.enterLocalPassiveMode();
        }

        String targetDir = getAbsolutePath(uri.getPath());
        targetDir += "/webapps";

        InputStream input = new FileInputStream(artifactPath);
        if (isDeployRoot) {
            ftp.storeFile(targetDir + "/ROOT.war", input);
        } else {
            ftp.storeFile(targetDir + "/" + artifactName + ".war", input);
        }
        input.close();
        ftp.logout();
    } catch (IOException e) {
        throw new AzureCmdException("Unable to connect to the FTP server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
    }
}