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.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public FTPClient getFtpClient(HashMap<String, String> params) {
    String urlServer = params.get("urlServer");
    String usuario = params.get("user");
    String pass = params.get("pass");
    //        String workingDir = params.get("workingDir");

    FTPClient ret = null;/* w w w  . ja  va2 s . c  om*/
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(InetAddress.getByName(urlServer));
        ftpClient.login(usuario, pass);
        //Verificar conexin con el servidor.
        int reply = ftpClient.getReplyCode();
        System.out.println("Estatus de conexion FTP:" + reply);
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Conectado exitosamente");
        } else {
            System.out.println("No se pudo conectar con el servidor");
        }
        //directorio de trabajo
        //            ftpClient.changeWorkingDirectory(workingDir);
        System.out.println("Establecer carpeta de trabajo");
        //Activar que se envie cualquier tipo de archivo
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ret = ftpClient;
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile)
        throws IOException, Exception {
    FTPClient ftp = new FTPClient();
    try {/*from  w  w  w.  j  av a2s. c  o  m*/
        int reply = 0;
        boolean replyB = false;
        ftp.connect(theServer);
        System.out.print(ftp.getReplyString());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        } else {
            ftp.login("anonymous", "anonymous");
            replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to login to " + theServer);
            }
            OutputStream output = new FileOutputStream(theLocalFile);
            replyB = ftp.retrieveFile(theServerFile, output);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to retrieve " + theServerFile);
            }
        }
        ftp.logout();
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage());
        throw rethrownExp;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignore) {
                // do nothing
            }
        }
    }
}

From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java

/**
 * API for creating connection to ftp server.
 * /*  w w  w .  j av  a2 s .  co m*/
 * @param client {@link FTPClient} the ftp client instance
 * @throws SocketException if any error occur while making the connection.
 * @throws IOException generate if any error occur while making the connection
 */
private void createConnection(FTPClient client) throws SocketException, IOException {
    client.connect(ftpServerURL);
    client.login(ftpUsername, ftpPassword);
    try {
        int ftpDataTimeOutLocal = Integer.parseInt(ftpDataTimeOut);
        client.setDataTimeout(ftpDataTimeOutLocal);
    } catch (NumberFormatException e) {
        LOGGER.error("Error occuring in converting ftpDataTimeOut :" + e.getMessage(), e);
    }
}

From source file:EscribirCorreo.java

private void SubirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubirActionPerformed
    //Codigo para subir archivo         
    String localfile = subir1Field.getText();
    String server = "51.254.137.26";
    String username = "proyecto";
    String password = "proyecto";
    String destinationfile = nombre;
    try {//from  www .j  a  v  a  2  s . c  om
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        InputStream in = new FileInputStream(localfile);
        ftp.setFileType(ftp.BINARY_FILE_TYPE);
        ftp.storeFile(destinationfile, in);
        JOptionPane.showMessageDialog(null, "Archivo subido correctamente", "Subido!",
                JOptionPane.INFORMATION_MESSAGE);
        if (archivos == null) {
            archivos = "http://51.254.137.26/proyecto/" + destinationfile;
        } else {
            archivos = archivos + "#http://51.254.137.26/proyecto/" + destinationfile;
        }
        in.close();
        ftp.logout();
        ftp.disconnect();

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

}

From source file:FTP.Uploader.java

public void uploadFile(String filename) throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;//w  w w .j  a v  a 2 s. c  o m
    boolean result;
    String ftpServerAddress = "shamalmahesh.net78.net";
    String userName = "a9959679";
    String password = "9P3IckDo";

    try {
        ftpclient.connect(ftpServerAddress);
        result = ftpclient.login(userName, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.enterLocalPassiveMode();
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/public_html/testing");

        //            File file = new File("D:/jpg/wq.jpg");
        File file = new File(filename);
        String testName = file.getName();
        fis = new FileInputStream(file);
        System.out.println(ftpclient.getBufferSize());
        // Upload file to the ftp server
        result = ftpclient.storeFile(testName, fis);
        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

From source file:com.cisco.dvbu.ps.utils.net.FtpFile.java

public void ftpFile(String fileName) throws CustomProcedureException, SQLException {

    // new ftp client
    FTPClient ftp = new FTPClient();
    OutputStream output = null;//from   w  w  w .j a v a 2s  .co m

    success = false;
    try {
        //try to connect
        ftp.connect(hostIp);

        //login to server
        if (!ftp.login(userId, userPass)) {
            ftp.logout();
            qenv.log(LOG_ERROR, "Ftp server refused connection user/password incorrect.");
        }
        int reply = ftp.getReplyCode();

        //FTPReply stores a set of constants for FTP Reply codes
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            qenv.log(LOG_ERROR, "Ftp server refused connection.");
        }

        //enter passive mode
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();

        //get system name
        //System.out.println("Remote system is " + ftp.getSystemType());

        //change current directory
        ftp.changeWorkingDirectory(ftpDirName);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        System.out.println("File is " + fileName);

        output = new FileOutputStream(dirName + "/" + fileName);

        //get the file from the remote system
        success = ftp.retrieveFile(fileName, output);

        //close output stream
        output.close();

    } catch (IOException ex) {
        throw new CustomProcedureException("Error in CJP " + getName() + ": " + ex.toString());
    }
}

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./*  w w  w. ja  va2 s .  c o  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:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 */// w w  w .  java  2s.c o  m
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);
        //               System.out.println( "Connected.");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();//from   w ww  . ja va  2  s.  co m
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

        //               System.out.println( "Logging in ...");

        if (!client.login(username, password)) {
            //                  System.out.println( "Could not log in.");
            // TODO bring up login dialog?
            client.disconnect();

            throw new IOException("Could not login to FTP Server \"" + host + "\".");
        }

        //               System.out.println( "Logged in.");

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

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}

From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java

/**
 * //ww  w .jav a  2s .c o  m
 */
private String retrieveFTP(String aURL) {
    debug("retrieveFTP (" + aURL + ")");

    URL urlObject = null;

    try {
        urlObject = new URL(aURL);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/");
    HoopLink.fManager.createDirectory(downloadPath);

    File translator = new File(urlObject.getFile());

    String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName();

    OutputStream fileStream = null;

    if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    fileStream = HoopLink.fManager.getOutputStreamBinary();

    if (fileStream == null) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    debug("Starting FTP client ...");

    FTPClient ftp = new FTPClient();

    try {
        int reply;

        debug("Connecting ...");

        ftp.connect(urlObject.getHost());

        debug("Connected to " + urlObject.getHost() + ".");
        debug(ftp.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            debug("FTP server refused connection.");
            return (null);
        } else {
            ftp.login("anonymous", "hoop-dev@gmail.com");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                debug("Unable to login to FTP server");
                return (null);
            }

            debug("Logged in");

            boolean rep = true;

            String pathFixed = translator.getParent().replace("\\", "/");

            rep = ftp.changeWorkingDirectory(pathFixed);
            if (rep == false) {
                debug("Unable to change working directory to: " + pathFixed);
                return (null);
            } else {
                debug("Current working directory: " + pathFixed);

                debug("Retrieving file " + urlObject.getFile() + " ...");

                try {
                    rep = ftp.retrieveFile(urlObject.getFile(), fileStream);
                } catch (FTPConnectionClosedException connEx) {
                    debug("Caught: FTPConnectionClosedException");
                    connEx.printStackTrace();
                    return (null);
                } catch (CopyStreamException strEx) {
                    debug("Caught: CopyStreamException");
                    strEx.printStackTrace();
                    return (null);
                } catch (IOException ioEx) {
                    debug("Caught: IOException");
                    ioEx.printStackTrace();
                    return (null);
                }

                debug("File retrieved");
            }

            ftp.logout();
        }
    } catch (IOException e) {
        debug("Error retrieving FTP file");
        e.printStackTrace();
        return (null);
    } finally {
        if (ftp.isConnected()) {
            debug("Closing ftp connection ...");

            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                debug("Exception closing ftp connection");
            }
        }
    }

    debug("Closing local file stream ...");

    try {
        fileStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName));

    return (result);
}