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:com.claim.support.FtpUtil.java

public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) {
    try {/*from   www . j a  v  a 2s  .  c o m*/
        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        FTPClient ftp = new FTPClient();
        ftp.connect(properties.getFtp_server());
        if (!ftp.login(properties.getFtp_username(), properties.getFtp_password())) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        ftp.enterLocalPassiveMode();
        System.out.println("Remote system is " + ftp.getSystemName());
        ftp.changeWorkingDirectory(targetDirectory);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        FTPFile[] ftpFiles = ftp.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());
                OutputStream output;
                output = new FileOutputStream(
                        properties.getFtp_remote_directory() + File.separator + file.getName());
                ftp.retrieveFile(file.getName(), output);
                output.close();
            }
        }
        ftp.logout();
        ftp.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

/**
 * /*www.  j  av a  2  s.  co 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;
}

From source file:ftp_server.FileUpload.java

public void uploading() {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;/*from www.j  av  a2 s.c  o  m*/
    try {
        client.connect("shamalmahesh.net78.net");
        client.login("a9959679", "9P3IckDo");
        client.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = client.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        //            String filename = "DownloadedLook1.txt";
        String path = "D:\\jpg\\";
        //            String filename = "1.jpg";
        String filename = "appearance.jpg";
        System.out.println(path + filename);
        fis = new FileInputStream(path + filename);
        System.out.println(fis.toString());
        boolean status = client.storeFile("/public_html/testing/" + filename, fis);
        System.out.println("Status : " + status);
        System.out.println("Done!");
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * /*from  w  w w.j a  v a 2  s  . c om*/
 *
 * @param remotePath ftp
 * @param fileName   ???
 * @param localPath  ???
 * @return true/false ?
 */
public boolean downloadFile(String remotePath, String fileName, String localPath) {
    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(remotePath);
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile file : files) {
            if (file.getName().equals(fileName)) {
                File localFile = new File(localPath + File.separator + file.getName());
                OutputStream outputStream = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), outputStream);
                outputStream.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;
}

From source file:com.starr.smartbuilds.service.FileService.java

public String getFile(Build build, ServletContext sc)
        throws FileNotFoundException, IOException, ParseException {

    /*if (fileName == null || fileName.equals("") || fileText == null || fileText.equals("")) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     } else {//  ww  w.  ja  v a2 s. c  o  m
     try {*/
    String path = sc.getRealPath("/");
    System.out.println(path);
    File dir = new File(path + "/builds");
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();
    }

    String fileName = path + "/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
    File fileBuild = new File(fileName);
    if (!fileBuild.exists() || fileBuild.isDirectory()) {
        String file_data = buildService.buildData(build, buildService.parseBlocks(build.getBlocks()));
        fileBuild.createNewFile();
        FileOutputStream fos = new FileOutputStream(fileBuild, false);
        fos.write(file_data.getBytes());
        fos.close();
    }

    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    try {
        client.connect("itelit.ftp.ukraine.com.ua");
        client.login("itelit_dor", "154896");

        // Create an InputStream of the file to be uploaded
        fis = new FileInputStream(fileBuild.getAbsolutePath());

        // Store file to server
        client.storeFile("builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json", fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*} catch (IOException ex) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     }
     }*/
    return "http://dor.it-elit.org/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException {

    FTPClient ftp = new FTPClient();

    System.out.println("\t\t" + pp.ftpUrl());
    System.out.println("\t\t" + pp.ftpUsername());
    System.out.println("\t\t" + pp.ftpPassword());

    URI uri = URI.create("ftp://" + pp.ftpUrl());
    ftp.connect(uri.getHost(), 21);//www .j  a  v  a 2s . co  m
    final int replyCode = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        ftp.disconnect();
        throw new ConnectException("Unable to connect to FTP server");
    }

    if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) {
        throw new ConnectException("Unable to login to FTP server");
    }

    ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.enterLocalPassiveMode();//Switch to passive mode

    return ftp;
}

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 {/*w w  w.  ja  v  a2 s  . co  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:autonomouspathplanner.ftp.FTP.java

/**
 * Attempts to connect to server to check if it is possible
 * @return true if the client can connect to the server and false otherwise.
 *//* w ww .  jav a 2  s .  c  om*/
public boolean canConnect() {
    try {
        FTPClient c = new FTPClient();
        c.connect(IP, port);

        c.login(user, pass);
        if (c.isConnected()) {
            c.logout();
            c.disconnect();
            return true;
        } else
            return false;
    } catch (UnknownHostException x) {
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }

}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {// w  w  w .  j  av  a 2 s  .  c o  m
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}

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;/*from   w  w  w.  jav  a2  s .com*/
    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;
}