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

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

Introduction

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

Prototype

public boolean retrieveFile(String remote, OutputStream local) throws IOException 

Source Link

Document

Retrieves a named file from the server and writes it to the given OutputStream.

Usage

From source file:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

public String getContent() {
    final FTPClient connection = connect();
    String content = null;/*from   w ww . j a  v  a 2  s  .  co m*/
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        if (!connection.retrieveFile(url.getPath(), outputStream)) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        content = outputStream.toString(encoding);
    } catch (final IOException e) {
        throw new SourceException(e);
    } finally {
        disconnect(connection);
        IOUtils.closeQuietly(outputStream);
    }
    lastModificationDate = getModificationDate(getFile());
    return content;
}

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

public void start() throws IOException {

    FTPClient client = new FTPClient();
    OutputStream outStream = null;

    try {//from  w  w w  .  j a v  a2s  .c  om
        client.connect("ftp.ibiblio.org");
        client.login("anonymous", "");

        String remoteFile = "/pub/micro/commodore/schematics/computers/c64/c64bus.gif";
        outStream = new FileOutputStream("c64bus.gif");

        client.retrieveFile(remoteFile, outStream);
    } catch (IOException ioe) {
        System.out.println("Error communicating with FTP server.");
    } finally {
        IOUtils.closeQuietly(outStream);
        try {
            client.disconnect();
        } catch (IOException e) {
            System.out.println("Problem disconnecting from FTP server");
        }
    }

    secondExample();

}

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

public static void setInitialLocationType(RepositoryLocation location) {

    FTPClient client = RepositoryClientUtil.connect(location, false);

    if (client != null) {

        String tempDir = "";

        try {/*from   ww  w .  j  a  v a2 s . c  o  m*/
            String eclipseInstallationDirectory = Platform.getInstallLocation().getURL().getPath();
            tempDir = RepositoryClientUtil.createFolder(eclipseInstallationDirectory + "tmp", 0);

            FTPFile[] files = client.listFiles();

            if (files.length > 0) {
                String fileName = files[0].getName();
                String destination = tempDir + "/" + fileName;
                FileOutputStream fos = new FileOutputStream(destination);
                client.retrieveFile(fileName, fos);
                fos.close();

                extractZipFile(tempDir, fileName);

                Document doc = getDocument(tempDir + "/rasset.xml");
                if (doc != null) {
                    Node ntype = doc.getElementsByTagName("type").item(0);
                    String type = ntype.getAttributes().getNamedItem("value").getNodeValue();
                    if (type != null) {
                        if (isTechnicalFragment(type)) {
                            location.setType("Technical");
                        } else {
                            location.setType("Conceptual");
                        }
                    }
                }
            } else {
                location.setType("Empty");
            }
        } catch (Exception e) {

        } finally {
            RepositoryClientUtil.disconnect(client);
            if (location.getType().equals("")) {
                location.setType("Empty");
            }
            if (!tempDir.equals("")) {
                RepositoryClientUtil.removeFolder(new File(tempDir));
            }
        }
    }
}

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

/**
 * Downloads file from FTP to Locale.//from   w  w w . j ava2  s.c o m
 * 
 * @param p_remoteFileName
 *            File Name in FTP Server
 * @param p_localFileName
 *            File Name in Locale
 */
public void ftpDownloadFile(String p_remoteFileName, String p_localFileName) {
    FTPClient ftpClient = getFtpClient();
    if (ftpClient != null && ftpClient.isConnected()) {
        try {
            FileOutputStream local = new FileOutputStream(new File(p_localFileName));
            ftpClient.retrieveFile(p_remoteFileName, local);
            local.close();
        } catch (IOException e) {
            String message = "Failed to download file from InBox(in FTP), fileName: " + p_remoteFileName + ".";
            LogUtil.FAILEDLOG.error(message);
        } finally {
            closeFtpClient(ftpClient);
        }
    }
}

From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

/**
 * ? ???/*from  w w w.j av  a  2s.c o m*/
 *
 * @param remoteAbsoluteFile
 * @param output
 * @param autoClose
 * @return
 * @throws Exception
 */
public boolean get(String remoteAbsoluteFile, OutputStream output, boolean autoClose) throws Exception {
    try {
        FTPClient ftpClient = getFTPClient();
        // ?
        return ftpClient.retrieveFile(remoteAbsoluteFile, output);
    } catch (IOException e) {
        throw new Exception("Couldn't get file from server.", e);
    } finally {
        if (autoClose) {
            disconnect(); //
        }
    }
}

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that throws a SocketException
 * on connect()./*from   ww w.j  a  v a 2s. c o m*/
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient socketExMockFtpClient() throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(true);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(true);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(true);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    doThrow(SocketException.class).when(client).connect("ftp.host.com", 21); //$NON-NLS-1$
    return client;
}

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that does not need an FTP server.
 * //from   w w w  . j a va2  s.  c o  m
 * @param succeedOnLogin 
 *        Specifies if this FTP client mocks its login method by
 *        imitating a successful or a failed login.
 * @param succedOnUploadDownload
 *        Specifies if this FTP client mocks the upload and download
 *        operations by imitating successful or failed operations.   
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient mockFtpClient(boolean succeedOnLogin, boolean succedOnUploadDownload) throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(succeedOnLogin);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    return client;
}

From source file:br.com.tiagods.util.FTPDownload.java

public boolean downloadFile(String arquivo) {
    FTPConfig cf = FTPConfig.getInstance();
    FTPClient ftp = new FTPClient();
    try {/*from   ww  w  .j a  v  a2 s  . c o  m*/
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        String remoteFile1 = cf.getValue("dirFTP") + "/" + arquivo;
        novoArquivo = new File(System.getProperty("java.io.tmpdir") + "/" + arquivo);
        try (OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(novoArquivo))) {
            boolean success = ftp.retrieveFile(remoteFile1, outputStream1);
            if (success) {
                return true;
            }
        }
        return false;
    } catch (IOException e) {
        System.out.println("Erro = " + e.getMessage());
        return false;
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream2(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    File downloadFile1 = null;//from   w ww .j av a 2  s. co  m
    try {
        downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        //ftpClient.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) );
        //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD));
        //ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        boolean success;
        String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12";
        downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12");
        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
        success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12");
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12");
        InputStream is = fis;
        if (success) {
            System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf");
        } else {
            System.out.println("File #1 has been downloaded successfully. 3333");
        }
        ;
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:boosta.artem.services.FTPResultReader.java

public void readResult() {
    String server = "62.210.82.210";
    int port = 55021;
    String user = "misha_p";
    String pass = "GfhjkM1983";

    FTPClient ftpClient = new FTPClient();
    try {/*from w w w  .  ja  va2 s .c  o  m*/

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.ASCII_FILE_TYPE);

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String remoteFile = Main.remote_out_path;
        System.out.println(remoteFile);
        //String remoteFile = "/results/ttgenerate.txt";
        String downlFile = Main.file_name;
        System.out.println(downlFile);
        File downloadFile = new File(downlFile);
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));

        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        outputStream.close();

        if (success) {
            System.out.println(" ?   FTP!!!");
        } else {
            System.out.println("  ?   TFP!!!");
        }

    } catch (IOException ex) {
        System.out.println("   ? FTP  !!!");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println(" ? ?? ? FTP!!!");
        }
    }
}