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) throws SocketException, IOException 

Source Link

Document

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

Usage

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

@Nullable
private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite,
        @NonNls final String directory, final ProgressIndicator indicator) {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(30 * 1000);/*ww  w  .  j a  v  a  2  s  . c o m*/
    try {
        indicator.setText("Connecting to server...");
        ftp.connect(ftpSite);
        indicator.setText("Connected to server");

        if (!ftp.login("anonymous", "anonymous@jetbrains.com")) {
            return "Failed to login";
        }
        indicator.setText("Logged in");

        // After connection attempt, you should check the reply code to verify
        // success.
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "FTP server refused connection: " + reply;
        }
        if (!ftp.changeWorkingDirectory(directory)) {
            return "Failed to change directory";
        }

        // else won't work behind FW
        ftp.enterLocalPassiveMode();

        if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) {
            return "Failed to switch to binary mode";
        }

        indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")");
        FileInputStream readStream = new FileInputStream(reportPath);
        try {
            if (!ftp.storeFile(reportPath.getName(), readStream)) {
                return "Failed to upload file";
            }
        } catch (IOException e) {
            return "Error during transfer: " + e.getMessage();
        } finally {
            readStream.close();
        }
        ftp.logout();
        return null;
    } catch (IOException e) {
        return "Failed to upload: " + e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:joshuatee.wx.UtilityFTP.java

public static String[] GetNidsArr(Context c, String url, String path, String frame_cnt_str) {

    int frame_cnt = Integer.parseInt(frame_cnt_str);
    String[] nids_arr = new String[frame_cnt];

    try {/*w w w  . j a v  a 2s  . c  o m*/
        FTPClient ftp = new FTPClient();

        //String user = "ftp";
        //String pass = "anonymous";

        ftp.connect(url);

        if (!ftp.login("ftp", "anonymous")) {
            ftp.logout();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(path);
        //reply = ftp.getReplyCode();

        FTPFile[] ftpFiles = ftp.listFiles();

        //get newest .xml file name from ftp server
        java.util.Date lastMod = ftpFiles[0].getTimestamp().getTime();
        FTPFile choice = ftpFiles[0];

        for (FTPFile file : ftpFiles) {
            if (file.getTimestamp().getTime().after(lastMod) && !file.getName().equals("sn.last")) {
                choice = file;
                lastMod = file.getTimestamp().getTime();
            }
        }

        int seq = Integer.parseInt(choice.getName().replace("sn.", "")); // was ALl
        int j = 0;
        int k = seq - frame_cnt + 1;
        for (j = 0; j < frame_cnt; j++) {
            // files range from 0000 to 0250, if num is negative add 251
            int tmp_k = k;

            if (tmp_k < 0)
                tmp_k = tmp_k + 251;

            nids_arr[j] = "sn." + String.format("%4s", Integer.toString(tmp_k)).replace(' ', '0');
            k++;
        }

        FileOutputStream fos;
        for (j = 0; j < frame_cnt; j++) {
            fos = c.openFileOutput(nids_arr[j], Context.MODE_PRIVATE);
            ftp.retrieveFile(nids_arr[j], fos);
            fos.close();
        }

        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return nids_arr;

}

From source file:com.microsoft.azure.management.appservice.samples.ManageWebAppSourceControl.java

private static void uploadFileToFtp(PublishingProfile profile, String fileName, InputStream file)
        throws Exception {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot/webapps";
    ftpClient.connect(server);
    ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.changeWorkingDirectory(path);
    ftpClient.storeFile(fileName, file);
    ftpClient.disconnect();/*from  ww w.ja  v  a  2s .com*/
}

From source file:joshuatee.wx.UtilityFTP.java

public static void GetNids(Context c, String url, String path) {

    try {/*w w w .ja v a 2s . com*/
        FTPClient ftp = new FTPClient();

        //String url = "tgftp.nws.noaa.gov";
        //String user = "ftp";
        //String pass = "anonymous";

        ftp.connect(url);

        if (!ftp.login("ftp", "anonymous")) {
            ftp.logout();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(path);
        //reply = ftp.getReplyCode();
        //String fn = "sn.last";

        FileOutputStream fos = c.openFileOutput("nids", Context.MODE_PRIVATE);
        ftp.retrieveFile("sn.last", fos);
        //reply = ftp.getReplyCode();
        fos.close();

        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:AIR.Common.Web.FileFtpHandler.java

/**
 * Makes FTP call to the provided URI and retrieves contents
 *  //from   w w  w .java  2 s  .c  o m
 * @param uri
 * @return ByteArrayInputStream
 * @throws FtpResourceException
 */
public static byte[] getBytes(URI uri) throws FtpResourceException {
    try {
        FTPClient ftp = new FTPClient();
        String[] credentialsAndHost = uri.getAuthority().split("@");
        String host = credentialsAndHost[1];
        String[] credentials = credentialsAndHost[0].split(":");

        ftp.connect(host);
        ftp.enterLocalPassiveMode();
        if (!ftp.login(credentials[0], credentials[1])) {
            ftp.logout();
            ftp.disconnect();
            throw new RuntimeException("FTP Authentication Failure");
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.logout();
            ftp.disconnect();
            throw new RuntimeException("FTP No reponse from server");
        }
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(uri.getPath(), output);
        output.close();
        ftp.logout();
        ftp.disconnect();
        return output.toByteArray();

    } catch (IOException ex) {
        throw new FtpResourceException(ex);
    }
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for creating connection to ftp server.
 * //ww w.  ja va 2  s. c o m
 * @param client {@link FTPClient} the ftp client instance
 * @throws SocketException generate if any error occurs while making the connection.
 * @throws IOException generate if any error occur while making the connection.
 */
public static void createConnection(final FTPClient client, final String ftpServerURL, final String ftpUsername,
        final String ftpPassword, final String ftpDataTimeOut) throws SocketException, IOException {
    client.connect(ftpServerURL);
    client.login(ftpUsername, ftpPassword);
    try {
        int ftpDataTimeOutLocal = Integer.parseInt(ftpDataTimeOut);
        client.setDataTimeout(ftpDataTimeOutLocal);
    } catch (NumberFormatException e) {
        LOGGER.error(EphesoftStringUtil.concatenate("Error occuring in converting ftpDataTimeOut :",
                e.getMessage(), e));
    }
}

From source file:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java

/**
 * Retrieve a file to a temporary path. This temporary path will be returned. Valid protocol
 * types: ftp, http, package or local file If a file has already be downloaded (the file is
 * existing in tmp directory) it will not be redownloaded again. Simply the path to this file
 * will be returned./*from w  w w  . j  a  v a2s .c o m*/
 * 
 * @param url
 *            URL to retrieve
 * @param checkAlreadyRetrieved
 *            if false, always download the file and ignore, if it is already existing
 * @return NULL on error. On success the path to the file is returned.
 */
public static File retrieve(String url, boolean checkAlreadyRetrieved) {
    if (url.indexOf("://") <= 0) {
        // Is local file
        return new File(url);
    }
    int start = url.indexOf('/') + 2;
    int end = url.indexOf('/', start);
    String serverName = url.substring(start, end);
    if (url.startsWith("package://")) {
        String filePath = url.substring(end + 1);
        String pkgPath = findPackage(serverName);
        if (pkgPath == null)
            return null;
        return new File(pkgPath, filePath);
    } else if (url.startsWith("http://")) {

        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            return tmpPath;
        }

        try {
            // Get the URL
            URL urlClass = new URL(url);
            // Open an output stream to the destination file on our local filesystem
            out = new BufferedOutputStream(new FileOutputStream(tmpPath));
            conn = urlClass.openConnection();
            in = conn.getInputStream();

            // Get the data
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
            // Done! Just clean up and get out
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                // Ignore if stream not possible to close
            }
        }
        return tmpPath;
    } else if (url.startsWith("ftp://")) {
        FTPClient client = new FTPClient();
        OutputStream outStream = null;
        String filename = url.substring(url.lastIndexOf('/') + 1);

        File tmpPath = getTmpName(url, filename);

        if (checkAlreadyRetrieved && tmpPath.exists()) {
            System.out.println("Already retrieved: " + url + " to " + tmpPath.getAbsolutePath());
            return tmpPath;
        }

        try {
            // Connect to the FTP server as anonymous
            client.connect(serverName);
            client.login("anonymous", "knowrob@example.com");
            String remoteFile = url.substring(end);
            // Write the contents of the remote file to a FileOutputStream
            outStream = new FileOutputStream(tmpPath);
            client.retrieveFile(remoteFile, outStream);

        } catch (IOException ioe) {
            System.out.println("ResourceRetriever: Error communicating with FTP server: " + serverName + "\n"
                    + ioe.getMessage());
        } finally {
            try {
                outStream.close();
            } catch (IOException e1) {
                // Ignore if stream not possible to close
            }
            try {
                client.disconnect();
            } catch (IOException e) {
                System.out.println("ResourceRetriever: Problem disconnecting from FTP server: " + serverName
                        + "\n" + e.getMessage());
            }
        }
        return tmpPath;
    }
    return null;
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static FTPClient connect(RepositoryLocation location, boolean showErrors) {

    FTPClient client = new FTPClient();
    String errorMessage = "";

    try {/*from  w  w w.j  av a 2  s .  co m*/
        client.connect(location.getHost());
        boolean ok = client.login(location.getUser(), location.getPassword());
        if (ok) {
            boolean ok2 = client.changeWorkingDirectory(location.getRepositoryPath());
            if (!ok2) {
                client = null;
                errorMessage = "Incorrect repository path";
            }
        } else {
            client = null;
            errorMessage = "Incorrect user name and password";
        }
    } catch (Exception e) {
        client = null;
        errorMessage = "Unknown host";
    }

    if (!errorMessage.equals("") && showErrors) {
        MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                "Connection failed", errorMessage);
    }

    return client;
}

From source file:com.discursive.jccook.net.FTPExample.java

private void secondExample() throws SocketException, IOException {
    FTPClient client = new FTPClient();
    client.connect("ftp.ibiblio.org");
    client.login("anonymous", "");

    String remoteDir = "/pub/mirrors/apache/jakarta/ecs/binaries";

    FTPFile[] remoteFiles = client.listFiles(remoteDir);

    System.out.println("Files in " + remoteDir);

    for (int i = 0; i < remoteFiles.length; i++) {
        String name = remoteFiles[i].getName();
        long length = remoteFiles[i].getSize();
        String readableLength = FileUtils.byteCountToDisplaySize(length);

        System.out.println(name + ":\t\t" + readableLength);
    }//from w w w  .  j av a 2  s . com

    client.disconnect();
}

From source file:br.com.atmatech.painel.util.EnviaLogs.java

public void enviarBD(File file, String enderecoFTP, String login, String senha) throws IOException {
    String nomeArquivo = null;//w ww. j  a v a2 s  .  c  o m
    FTPClient ftp = new FTPClient();
    ftp.connect(enderecoFTP);
    //verifica se conectou com sucesso! 

    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.login(login, senha);
    } else {
        //erro ao se conectar  
        ftp.disconnect();
    }
    ftp.changeWorkingDirectory("/atmatech.com.br/ErroLogsPainelFX/");
    //abre um stream com o arquivo a ser enviado              
    InputStream is = new FileInputStream(file);
    //pega apenas o nome do arquivo             
    int idx = file.getName().lastIndexOf(File.separator);
    if (idx < 0)
        idx = 0;
    else
        idx++;
    nomeArquivo = file.getName().substring(idx, file.getName().length());
    //ajusta o tipo do arquivo a ser enviado  
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    //faz o envio do arquivo  
    ftp.storeFile(nomeArquivo, is);
    ftp.disconnect();

}