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

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

Introduction

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

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

From source file:edu.stanford.epad.common.util.FTPUtil.java

public boolean sendFile(String filePath, boolean delete) throws Exception {

    String fileName = filePath;/*  ww  w  .ja va2 s  .  c o  m*/
    int slash = fileName.lastIndexOf("/");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    slash = fileName.lastIndexOf("\\");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    boolean success = true;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(ftpHost, ftpPort);
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(ftpUser, ftpPassword)) {
                if (ftpFolder != null && ftpFolder.trim().length() > 0) {
                    ftp.cwd(ftpFolder);
                    System.out.print("ftp cd: " + ftp.getReplyString());
                }
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
                FileInputStream in = new FileInputStream(filePath);
                success = ftp.storeFile(fileName, in);
                in.close();
                if (delete) {
                    File file = new File(filePath);
                    file.delete();
                }
            } else
                success = false;
        }
    } finally {
        ftp.disconnect();
    }

    return success;
}

From source file:com.claim.support.FtpUtil.java

public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) {
    FTPClient ftpClient = new FTPClient();
    InputStream inputStream = null;
    try {/* w ww  .j a  va  2s  .  com*/
        FtpProperties properties = new ResourcesProperties().loadFTPProperties();
        ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
        ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        File secondLocalFile = new File(direcPath);
        String secondRemoteFile = "WorkshopDay2.docx";
        inputStream = new FileInputStream(secondLocalFile);
        System.out.println("Start uploading second file");
        OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
        byte[] bytesIn = new byte[4096];
        int read = 0;
        while ((read = inputStream.read(bytesIn)) != -1) {
            outputStream.write(bytesIn, 0, read);
        }
        inputStream.close();
        outputStream.close();
        boolean completed = ftpClient.completePendingCommand();
        if (completed) {
            System.out.println("The second file is uploaded successfully.");
        }
    } 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:com.globalsight.smartbox.util.FtpHelper.java

private FTPClient initFtpClient() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(host, port);/*from   w  w w.  jav  a  2 s .c  o m*/
    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);

    return ftpClient;
}

From source file:de.cismet.cids.custom.utils.formsolutions.FormSolutionFtpClient.java

/**
 * DOCUMENT ME!//from   w  w w .  j av  a  2  s. c o  m
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
private FTPClient getConnectedFTPClient() throws Exception {
    final FTPClient ftpClient = new FTPClient();
    ftpClient.connect(FormSolutionsProperties.getInstance().getFtpHost());

    final int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
    }
    ftpClient.login(FormSolutionsProperties.getInstance().getFtpLogin(),
            FormSolutionsProperties.getInstance().getFtpPass());
    return ftpClient;
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private Boolean downloadFile(String server, int portNumber, String user, String password, String filename,
        File localFile) throws IOException {
    FTPClient ftp = null;

    try {//from   w w w  . ja v a  2s  . c  o m
        ftp = new FTPClient();
        ftp.setBufferSize(1024 * 1024);
        ftp.connect(server, portNumber);
        Log.d(NAME, "Connected. Reply: " + ftp.getReplyString());
        if (!ftp.login(user, password)) {
            return false;
        }
        Log.d(NAME, "Logged in");
        if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
            return false;
        }
        Log.d(NAME, "Downloading");
        ftp.enterLocalPassiveMode();

        OutputStream outputStream = null;
        boolean success = false;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
            success = ftp.retrieveFile(filename, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }

        return success;
    } finally {
        if (ftp != null) {
            ftp.logout();
            ftp.disconnect();
        }
    }
}

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. j  av a2s .  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:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *//*ww w .  j av a 2 s .com*/
@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:edu.stanford.epad.common.util.FTPUtil.java

public void getFile(String remoteFile, File localFile) throws Exception {

    FTPClient ftpClient = new FTPClient();
    OutputStream outputStream = null;
    try {/*from w ww .java  2 s . c om*/
        ftpClient.connect(ftpHost, ftpPort);
        ftpClient.enterLocalPassiveMode();
        if (ftpUser != null && ftpUser.length() > 0)
            ftpClient.login(ftpUser, ftpPassword);
        else
            ftpClient.login("anonymous", "");
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        boolean commandOK = ftpClient.completePendingCommand();
        //boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        //if (!success) {
        //   throw new Exception("Error retrieving remote file: " + remoteFile);
        //}   
    } finally {
        outputStream.close();
        ftpClient.disconnect();
    }
}

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 w  w  .ja v  a  2s. co m*/
            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:be.thomasmore.controller.FileController.java

public String uploadFile() throws IOException {
    String server = "logic.sinners.be";
    int port = 21;
    String user = "logic_java";
    String pass = "scoretracker";

    FTPClient ftpClient = new FTPClient();
    try {/*from   www. j a  v a2 s. c  o  m*/
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        String firstRemoteFile = getFileName(part);
        InputStream inputStream = part.getInputStream();

        System.out.println("Bestand uploaden");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("Het bestand is succesvol upgeload.");
            statusMessage = "De gegevens werden succesvol ingeladen.";
        }

    } catch (IOException ex) {
        System.out.println("Fout: " + ex.getMessage());
        statusMessage = "Er is een fout opgetreden: " + ex.getMessage();
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
     //De bestandsnaam uit het bestand (part) halen
     String fileName = getFileName(part);
     System.out.println("***** fileName: " + fileName);
            
     String basePath = "C:" + File.separator + "data" + File.separator;
            
     File outputFilePath = new File(basePath + fileName);
            
     //Streams aanmaken om het upgeloade bestand naar de destination te kopiren
     InputStream inputStream = null;
     OutputStream outputStream = null;
     try {
     inputStream = part.getInputStream();
     outputStream = new FileOutputStream(outputFilePath);
            
     int read = 0;
     final byte[] bytes = new byte[1024];
     while ((read = inputStream.read(bytes)) != -1) {
     outputStream.write(bytes, 0, read);
     }
     statusMessage = "De gegevens werden succesvol ingeladen.";
     } catch (IOException e) {
     e.printStackTrace();
     statusMessage = "Er is een fout opgetreden.";
     } finally {
     if (outputStream != null) {
     outputStream.close();
     }
     if (inputStream != null) {
     inputStream.close();
     }
     }*/
    leesExcel();

    return null;
}