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:br.com.tiagods.util.FTPDownload.java

public boolean downloadFile(String arquivo) {
    FTPConfig cf = FTPConfig.getInstance();
    FTPClient ftp = new FTPClient();
    try {//from   w w w.j a  v  a 2  s .  c  om
        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:br.com.tiagods.util.FTPUpload.java

public boolean uploadFile(File arquivo, String novoNome) {
    FTPConfig cf = FTPConfig.getInstance();

    FTPClient ftp = new FTPClient();
    try {/*from  w w w.  j  a  v a  2 s .  c om*/
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        //ftp.connect(server,port);
        //ftp.login(user,pass);
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        boolean done;
        try (InputStream stream = new FileInputStream(arquivo)) {
            String remoteFile = novoNome;
            System.out.println("Start uploading first file");
            done = ftp.storeFile(cf.getValue("dirFTP") + "/" + remoteFile, stream);
            stream.close();
        }
        if (done) {
            JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            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: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   www.  j  av  a  2s. 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!!!");
        }
    }
}

From source file:heigit.ors.routing.traffic.providers.FtpDataSource.java

@Override
public String getMessage() throws IOException {
    String message = null;//  w  ww . ja v a  2  s.  c  om
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(server, port);
        ftpClient.login(user, password);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(2);

        String remoteFile1 = "/" + file;
        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
        message = StreamUtility.readStream(inputStream, "iso-8859-1");
        Boolean success = ftpClient.completePendingCommand();

        if (success) {
            System.out.println("File has been downloaded successfully.");
        }

        inputStream.close();
    } catch (IOException e) {
        /* SendMail mail = new SendMail();
           try
           {
             mail.postMail(this.properties.getProperty("mail"), "TMC-Fehler", 
        e.getStackTrace().toString(), "TMC@Fehlermeldung.de", this.properties
        .getProperty("smtpHost"), this.properties
        .getProperty("smtpUser"), this.properties
        .getProperty("smtpPort"));
           }
           catch (MessagingException e1)
           {
             e1.printStackTrace();
           }
           this.logger.debug("Error with FTP connection " + 
             e.getLocalizedMessage(), e);
           throw new DownloadException(
             "Error while downloading file from FTP " + 
             e.getLocalizedMessage(), e);
         */
    }

    return message;
}

From source file:model.ProfilModel.java

public void uploadFoto(String path) {
    String server = "localhost";
    int port = 21;
    String user = "user1";
    String pass = "itsme";

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

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

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File(path);

        String firstRemoteFile = this.user.getFoto();
        InputStream inputStream = new FileInputStream(firstLocalFile);

        System.out.println("Start uploading first file");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("The first file is uploaded successfully.");
        }
        inputStream.close();

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class);
    RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response);

    // prepare dynamic variables
    Part masterQualityPart = request.getPart("masterFile");
    String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf";

    // prepare static variables
    String host = "p4.eurixgroup.com";
    int port = 21;
    String username = "pprime";
    String password = "pprime09";

    FTPClient client = new FTPClient();
    try {//from  w w w  .java  2  s . c o  m
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                // TODO add behavior if file name is already present in
                // remote ftp folder
                // now OVERWRITES
                if (client.storeFile(targetName, masterQualityPart.getInputStream())) {
                    logger.info("Stored file on remote FTP server " + host + ":" + port);

                    request.setAttribute("masterfileName", targetName);
                } else {
                    logger.error("Unable to store file on remote FTP server");
                }
            } else {
                logger.error("Unable to login on remote FTP server");
            }
        } else {
            logger.error("Unable to connect to remote FTP server");
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.fatal("General exception with FTPClient");
    }

    Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp");
}

From source file:com.clican.pluto.cms.core.service.impl.SiteServiceImpl.java

public FTPClient getFTPClient(ISite site) throws IOException {
    String url = site.getUrl();// ww w.j  a v a2  s  . c o m
    if (url == null) {
        return null;
    }
    if (url.startsWith("ftp://")) {
        int port = 21;
        String hostname = null;
        try {
            url = url.substring(6);
            if (url.indexOf(":") != -1) {
                hostname = url.substring(0, url.indexOf(":"));
                if (url.endsWith("/")) {
                    port = Integer.parseInt(url.substring(url.indexOf(":") + 1, url.length() - 1));
                } else {
                    port = Integer.parseInt(url.substring(url.indexOf(":") + 1));
                }
            } else {
                if (url.endsWith("/")) {
                    hostname = url.substring(0, url.length() - 1);
                } else {
                    hostname = url;
                }
            }
        } catch (Exception e) {
            throw new UnknownHostException(url);
        }
        FTPClient client = new FTPClient();
        client.connect(hostname, port);
        if (log.isDebugEnabled()) {
            log.debug("Connected to " + url + ".");
            log.debug(client.getReplyString());
        }
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            log.warn("FTP server " + url + " refused connection.");
            return null;
        }
        if (StringUtils.isNotEmpty(site.getUsername())) {
            boolean login = client.login(site.getUsername(), site.getPassword());
            if (!login) {
                client.disconnect();
                return null;
            }
        }

        return client;
    }
    return null;
}

From source file:ca.nrc.cadc.web.ServerToServerFTPTransfer.java

private FTPClient connect() throws IOException {
    final FTPClient ftpClient = createFTPClient();
    ftpClient.connect(hostname, port);

    final int reply = ftpClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();//from   w  w  w .  j a  v a  2 s.c om
        throw new IOException(String.format("FTP Connection failed with error code %d.", reply));
    } else {
        return login(ftpClient);
    }
}

From source file:co.nubetech.hiho.mapreduce.lib.output.FTPTextOutputFormat.java

@Override
public RecordWriter<K, V> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {

    Configuration conf = job.getConfiguration();

    String ip = conf.get(HIHOConf.FTP_ADDRESS);
    String portno = conf.get(HIHOConf.FTP_PORT);
    String usr = conf.get(HIHOConf.FTP_USER);
    String pwd = conf.get(HIHOConf.FTP_PASSWORD);
    String dir = getOutputPath(job).toString();
    System.out.println("\n\ninside ftpoutputformat" + ip + " " + portno + " " + usr + " " + pwd + " " + dir);
    String keyValueSeparator = conf.get("mapred.textoutputformat.separator", "\t");
    FTPClient f = new FTPClient();
    f.connect(ip, Integer.parseInt(portno));
    f.login(usr, pwd);/*  w ww. j  av  a  2s  .co  m*/
    f.changeWorkingDirectory(dir);
    f.setFileType(FTP.BINARY_FILE_TYPE);

    boolean isCompressed = getCompressOutput(job);
    CompressionCodec codec = null;
    String extension = "";
    if (isCompressed) {
        Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, GzipCodec.class);
        codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf);
        extension = codec.getDefaultExtension();
    }
    Path file = getDefaultWorkFile(job, extension);
    FileSystem fs = file.getFileSystem(conf);
    String filename = file.getName();
    if (!isCompressed) {
        // FSDataOutputStream fileOut = fs.create(file, false);
        OutputStream os = f.appendFileStream(filename);
        DataOutputStream fileOut = new DataOutputStream(os);
        return new FTPLineRecordWriter<K, V>(fileOut, new String(keyValueSeparator), f);

    } else {
        // FSDataOutputStream fileOut = fs.create(file, false);
        OutputStream os = f.appendFileStream(filename);
        DataOutputStream fileOut = new DataOutputStream(os);
        return new FTPLineRecordWriter<K, V>(new DataOutputStream(codec.createOutputStream(fileOut)),
                keyValueSeparator, f);
    }
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * // ww w .  jav  a 2  s .  c  o m
 *
 * @param fileName   ??
 * @param path       ftp?
 * @param fileStream ?
 * @return true/false ?
 */
public boolean uploadFile(String fileName, String path, InputStream fileStream) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(path);
        ftpClient.storeFile(fileName, fileStream);
        fileStream.close();
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}