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.nostra13.universalimageloader.core.download.BaseImageDownloader.java

protected InputStream getStreamFromFTPNetwork(String imageUri, Object extra) throws IOException {
    int indexUrl = imageUri.indexOf("//") + 1;
    int indexUrlFinal = imageUri.lastIndexOf(":");
    int slash = imageUri.lastIndexOf("/");
    String ip = imageUri.substring(indexUrl + 1, indexUrlFinal);
    FTPClient client = new FTPClient();
    client.connect(ip, 20000);//from   w w w .  java  2s  .c o m
    client.login("anonymous", "");
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    InputStream imageStream = null;
    FTPFile[] directories = client.listFiles();
    long fileLength = (int) getFile(directories, imageUri.substring(slash + 1)).getSize();
    try {
        imageStream = client.retrieveFileStream(imageUri.substring(slash + 1));
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(imageStream);
        throw e;
    }
    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), fileLength);
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {/* w w w .j  a v  a  2  s. c  o m*/
        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();
        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.shigeodayo.ardrone.utils.ARDroneInfo.java

private boolean connectToDroneThroughFtp() {
    FTPClient client = new FTPClient();
    BufferedOutputStream bos = null;

    try {//w w  w .  j  av a 2  s  .  c o m
        client.connect(ARDroneConstants.IP_ADDRESS, ARDroneConstants.FTP_PORT);

        if (!client.login("anonymous", "")) {
            ARDrone.error("Login failed", this);
            return false;
        }

        client.setFileType(FTP.BINARY_FILE_TYPE);

        bos = new BufferedOutputStream(new OutputStream() {

            @Override
            public void write(int arg0) throws IOException {
                //System.out.println("aa:" + (char)arg0);
                switch (count) {
                case 0:
                    major = arg0 - '0';
                    break;
                case 2:
                    minor = arg0 - '0';
                    break;
                case 4:
                    revision = arg0 - '0';
                    break;
                default:
                    break;
                }
                count++;
            }
        });

        if (!client.retrieveFile("/" + VERSION_FILE_NAME, bos)) {
            ARDrone.error("Cannot find \"" + VERSION_FILE_NAME + "\"", this);
            return false;
        }

        bos.flush();

        //System.out.print("major:" + major);
        //System.out.print(" minor:" + minor);
        //System.out.println(" revision:" + revision);

        //System.out.println("done");
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}

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

/**
 * API for creating connection to ftp server.
 * //from   ww w.  j a  va  2  s.c o 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 {//ww w .ja  v  a 2s  .  c  o m
        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:eu.prestoprime.plugin.fprint.FPrintTasks.java

@WfService(name = "fprint_upload", version = "0.8.0")
public void upload(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    logger.debug("Called " + this.getClass().getName());

    // prepare dynamic variables
    String id = dParamsString.get("id");
    String targetName = id + ".webm";
    String fileLocation = null;//from w  w  w.  java 2  s .c om

    // prepare static variables
    String host = sParams.get("host");
    int port = Integer.parseInt(sParams.get("port"));
    String username = sParams.get("username");
    String password = sParams.get("password");
    String workdir = sParams.get("workdir");

    // retrieve AIP
    try {
        DIP dip = P4DataManager.getInstance().getDIPByID(id);
        List<String> fLocatList = dip.getAVMaterial("video/webm", "FILE");
        fileLocation = fLocatList.get(0);
    } catch (DataException | IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve the fileLocation of the Master Quality...");
    }

    logger.debug("Found video/webm location: " + fileLocation);

    // send to remote FTP folder
    FTPClient client = new FTPClient();
    try {
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                if (client.changeWorkingDirectory(workdir)) {
                    // TODO add behavior if file name is already present in
                    // remote ftp folder
                    // now OVERWRITES
                    File file = new File(fileLocation);
                    if (file.isFile()) {
                        if (client.storeFile(targetName, new FileInputStream(file))) {
                            logger.info("Stored file on server " + host + ":" + port + workdir);
                        } else {
                            throw new TaskExecutionFailedException("Cannot store file on server");
                        }
                    } else {
                        throw new TaskExecutionFailedException("Local file doesn't exist or is not acceptable");
                    }
                } else {
                    throw new TaskExecutionFailedException("Cannot browse directory " + workdir + " on server");
                }
            } else {
                throw new TaskExecutionFailedException("Username and Password not accepted by the server");
            }
        } else {
            throw new TaskExecutionFailedException(
                    "Cannot establish connection with server " + host + ":" + port);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("General exception with FTPClient");
    }

    logger.debug("Executed without errors " + this.getClass().getName());
}

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

private FTPClient connect() {
    final FTPClient connection = new FTPClient();
    try {/* w  w w  . j a v a2  s  .com*/
        connection.setAutodetectUTF8(true);
        connection.connect(url.getHost(), port);
        connection.enterLocalActiveMode();
        if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) {
            throw new SourceException(
                    String.format("Cannot login as anonymous user, reason %s", connection.getReplyString()));
        }
        if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        connection.enterLocalPassiveMode();
        connection.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (final IOException e) {
        disconnect(connection);
        throw new SourceException(e);
    }
    return connection;
}

From source file:beans.BL.java

/**
 * Upload FTP Server/*from   w  w w.j  a  v  a  2  s  .  com*/
 *
 * @param filename
 * @throws IOException
 */
public void upload(String filename) throws IOException {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    client.connect("ftp.sunlime.at", 990);
    client.login("admin", "secret");

    fis = new FileInputStream(filename);
    client.storeFile(filename, fis);
    client.logout();
    fis.close();
}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * ?FTP?./*from   w  w  w .  j a  v a  2s  .  c om*/
 * 
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public boolean ftpUploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("UTF-8");
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(path);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        // 
        ftp.storeFile(filename, input);
        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {//from   w  w  w  . j  a v  a  2s.c o m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}