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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

From source file:com.esri.gpt.control.webharvest.validator.WAFValidator.java

@Override
public boolean checkConnection(IMessageCollector mb) {
    if (url.toLowerCase().startsWith("ftp://")) {
        FTPClient client = null;
        try {//from  w  ww .  j  av  a2s .  c om
            URL u = new URL(url);
            String host = u.getHost();
            int port = u.getPort() >= 0 ? u.getPort() : 21;
            client = new FTPClient();
            client.connect(host, port);
            CredentialProvider cp = getCredentialProvider();
            if (cp == null) {
                client.login("anonymous", "anonymous");
            } else {
                client.login(cp.getUsername(), cp.getPassword());
            }
            return true;
        } catch (MalformedURLException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestInvalidUrl");
            return false;
        } catch (IOException ex) {
            mb.addErrorMessage("catalog.harvest.manage.test.err.HarvestConnectionException");
            return false;
        } finally {
            if (client != null) {
                try {
                    client.disconnect();
                } catch (IOException ex) {
                }
            }
        }
    } else {
        return super.checkConnection(mb);
    }
}

From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

private FTPClient connectMe() throws IOException {
    FTPClient ftpclient = new FTPClient();
    ftpclient.connect(configurator.host, configurator.port);

    if (ftpclient.login(configurator.username, configurator.password) == false) {
        ftpclient.logout();//from  w  w  w.  j  a v a2 s .c  o m
        throw new IOException("Can't login to server");
    }
    int reply = ftpclient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply) == false) {
        ftpclient.disconnect();
        throw new IOException("Can't login to server");
    }

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

    if (configurator.passive) {
        ftpclient.enterLocalPassiveMode();
    } else {
        ftpclient.enterLocalActiveMode();
    }
    ftpclient.changeWorkingDirectory("/" + path);
    if (ftpclient.printWorkingDirectory().equals("/" + path) == false) {
        throw new IOException("Can't change working dir : " + "/" + path);
    }

    return ftpclient;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * // w ww . j a  va2 s  .  c o  m
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/*from   w  w w . j  a  va  2s  . c  o m*/
            inputStream = new FileInputStream(file);
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from   ww  w.  ja  v a 2 s.co m
            inputStream = new FileInputStream(file);
            ftpClient.connect(ftpInfo.get("host"), 21);
            ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            path = ftpInfo.get("path") + path;
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.globalsight.smartbox.util.FtpHelper.java

private FTPClient initFtpClient() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(host, port);
    ftpClient.login(username, password);

    // Sets Binary File Type for ZIP File.
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    // Set Buffer Size to speed up download/upload file.
    ftpClient.setBufferSize(102400);// ww  w .ja  v  a2 s .co m

    return ftpClient;
}

From source file:com.jmeter.alfresco.utils.FtpUtils.java

/**
 * Upload directory or file.//from ww  w  . ja  v a2s.co  m
 *
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 * @param fromLocalDirOrFile the local dir
 * @param toRemoteDirOrFile the remote dir
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String uploadDirectoryOrFile(final String host, final int port, final String userName,
        final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile)
        throws IOException {

    final FTPClient ftpClient = new FTPClient();
    String responseMessage = Constants.EMPTY;
    try {
        // Connect and login to get the session
        ftpClient.connect(host, port);
        final int replyCode = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(replyCode)) {
            final boolean loginSuccess = ftpClient.login(userName, password);
            if (loginSuccess) {
                LOG.debug("Connected to remote host!");
                //Use local passive mode to pass fire-wall
                //In this mode a data connection is made by opening a port on the server for the client to connect 
                //and this is not blocked by fire-wall.
                ftpClient.enterLocalPassiveMode();
                final File localDirOrFileObj = new File(fromLocalDirOrFile);
                if (localDirOrFileObj.isFile()) {
                    LOG.debug("Uploading file: " + fromLocalDirOrFile);
                    uploadFile(ftpClient, fromLocalDirOrFile,
                            toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName());
                } else {
                    uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY);
                }
                responseMessage = "Upload completed successfully!";
            } else {
                responseMessage = "Could not login to the remote host!";
            }
            //Log out and disconnect from the server once FTP operation is completed.
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while logging out from remote host: ", ignored);
                }
                try {
                    ftpClient.disconnect();
                    LOG.debug("Disconnected from remote host!");
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored);
                }
            }
        } else {
            responseMessage = "Host connection failed!";
        }
        LOG.debug("ResponseMessage:=> " + responseMessage);
    } catch (IOException ioexcp) {
        LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp);
        throw ioexcp;
    }
    return responseMessage;
}

From source file:com.tobias.vocabulary_trainer.UpdateVocabularies.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_vocabularies_layout);
    prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text);
    serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text);
    serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text);
    serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text);
    serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text);
    localFileEditText = (EditText) findViewById(R.id.local_file_edit_text);

    vocabularies = new VocabularyData(this);
    System.out.println("before updateUIFromPreferences();");
    updateUIFromPreferences();/*from  w  ww .ja  va2 s . c om*/
    System.out.println("after updateUIFromPreferences();");

    final Button ServerOkButton = (Button) findViewById(R.id.server_ok);
    ServerOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("ServerOKButton pressed");
            savePreferences();
            InputStream in;
            String serverAdresse = serverAdresseEditText.getText().toString();
            String serverUsername = serverUsernameEditText.getText().toString();
            String serverPassword = serverPasswordEditText.getText().toString();
            int serverPort = Integer.parseInt(serverPortEditText.getText().toString());
            String serverFile = serverFileEditText.getText().toString();

            FTPClient ftp;
            ftp = new FTPClient();
            try {
                int reply;
                System.out.println("try to connect to ftp server");
                ftp.connect(serverAdresse, serverPort);
                System.out.print(ftp.getReplyString());
                // After connection attempt, you should check the reply code to verify
                // success.
                reply = ftp.getReplyCode();
                if (FTPReply.isPositiveCompletion(reply)) {
                    System.out.println("connected to ftp server");
                } else {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                }

                // transfer files
                System.out.println("try to login");
                ftp.login(serverUsername, serverPassword);
                System.out.println("current working directory: " + ftp.printWorkingDirectory());
                System.out.println("try to start downloading");
                in = ftp.retrieveFileStream(serverFile);
                // files transferred
                //write to database and textfile on sdcard
                vocabularies.readVocabularies(in, false);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        // do nothing
                    }
                }
            }
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok);
    LocalFileOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File f = new File(Environment.getExternalStorageDirectory(),
                    localFileEditText.getText().toString());
            savePreferences();
            vocabularies.readVocabularies(f, false);
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button CancelButton = (Button) findViewById(R.id.Cancel);
    CancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    vocabularies.close();
}

From source file:com.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {//from w w  w  .j a v  a  2s .c o  m
        // The executes in the IO thread!
        String sourceVar = getSourceVar(messageContext);
        InputStream src = null;
        boolean wantBase64Decode = getWantBase64Decode(messageContext);
        if (sourceVar == null) {
            src = messageContext.getMessage().getContentAsStream();
            // conditionally wrap a decoder around it
            if (wantBase64Decode) {
                src = new Base64InputStream(src);
            }
        } else {
            info.addMessage("Retrieving data from " + sourceVar);
            String sourceData = messageContext.getVariable(sourceVar);
            byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData)
                    : sourceData.getBytes(StandardCharsets.UTF_8);
            src = new ByteArrayInputStream(b);
        }
        String remoteName = getRemoteFileName(messageContext);
        remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-");

        String ftpServer = getFtpServer(messageContext);
        int ftpPort = getFtpPort(messageContext);
        String user = getFtpUser(messageContext);
        String password = getFtpPassword(messageContext);

        info.addMessage("connecting to server " + ftpServer);
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new FtpCommandListener(info));
        ftp.connect(ftpServer, ftpPort);
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("The FTP server refused the connection.");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }

        if (!ftp.login(user, password)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("Login failure");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }
        info.addMessage("logged in as " + user);

        String initialDirectory = getInitialDirectory(messageContext);
        if ((initialDirectory != null) && (!initialDirectory.equals(""))) {
            ftp.changeWorkingDirectory(initialDirectory);
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        OutputStream os = ftp.storeFileStream(remoteName);
        if (os == null) {
            // cannot open output stream
            info.addMessage("cannot open output stream to " + remoteName);
            info.setStatus("FAIL");
        } else {
            byte[] buf = new byte[2048];
            int n;
            while ((n = src.read(buf)) > 0) {
                os.write(buf, 0, n);
            }
            os.close();
            src.close();
            boolean completed = ftp.completePendingCommand();
            info.addMessage("transfer completed: " + completed);
            info.setStatus("OK");
        }

        ftp.disconnect();
        info.addMessage("All done.");
        messageContext.setVariable(varName("result"), info.toJsonString());
    } catch (java.lang.Exception exc1) {
        if (getDebug()) {
            System.out.println(ExceptionUtils.getStackTrace(exc1));
        }
        String error = exc1.toString();
        messageContext.setVariable(varName("exception"), error);
        info.setStatus("FAIL");
        info.addMessage(error);
        messageContext.setVariable(varName("result"), info.toJsonString());
        int ch = error.lastIndexOf(':');
        if (ch >= 0) {
            messageContext.setVariable(varName("error"), error.substring(ch + 2).trim());
        } else {
            messageContext.setVariable(varName("error"), error);
        }
        messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1));
        return ExecutionResult.ABORT;
    }

    return ExecutionResult.SUCCESS;
}

From source file:dk.netarkivet.common.distribute.IntegrityTestsFTP.java

public void testWrongChecksumThrowsError() throws Exception {
    Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.FTPRemoteFile");
    RemoteFile rf = RemoteFileFactory.getInstance(testFile2, true, false, true);
    // upload error to ftp server
    File temp = File.createTempFile("foo", "bar");
    FTPClient client = new FTPClient();
    client.connect(Settings.get(CommonSettings.FTP_SERVER_NAME),
            Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT)));
    client.login(Settings.get(CommonSettings.FTP_USER_NAME), Settings.get(CommonSettings.FTP_USER_PASSWORD));
    Field field = FTPRemoteFile.class.getDeclaredField("ftpFileName");
    field.setAccessible(true);/*from  www  .  j  a  v  a 2s . co  m*/
    String filename = (String) field.get(rf);
    client.storeFile(filename, new ByteArrayInputStream("foo".getBytes()));
    client.logout();
    try {
        rf.copyTo(temp);
        fail("Should throw exception on wrong checksum");
    } catch (IOFailure e) {
        // expected
    }
    assertFalse("Destination file should not exist", temp.exists());
}