Example usage for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

Introduction

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

Prototype

int BINARY_FILE_TYPE

To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.

Click Source Link

Document

A constant used to indicate the file(s) being transfered should be treated as a binary image, i.e., no translations should be performed.

Usage

From source file:com.isencia.message.ftp.FtpReceiverChannel.java

/**
 * @see ISenderChannel#open()/*from  w  ww.  ja  v a 2  s .  co m*/
 */
public void open() throws ChannelException {
    if (logger.isTraceEnabled())
        logger.trace("");

    if (server == null)
        throw new ChannelException("Server is not specified");
    if (username == null)
        throw new ChannelException("Username is not specified");
    if (password == null)
        throw new ChannelException("Password is not specified");
    if (remote == null)
        throw new ChannelException("File is not specified");

    // CONNECT TO SERVER
    try {
        int reply;
        ftp.connect(server, port);
        logger.debug("Connected to " + server + ".");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            logger.error("FTP server refused connection");
            throw new ChannelException("FTP server refused connection");
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        logger.error("Could not connect to server");
        throw new ChannelException("Could not connect to server");
    }

    try {
        // LOGIN TO THE SERVER
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new ChannelException(
                    "Can't login with username " + this.username + " and password " + this.password);
        }

        logger.debug("Remote system is " + ftp.getSystemName());

        // ADJUST SETTINGS
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        if (passiveMode) {
            // Use passive mode as default because most of us are
            // behind firewalls these days.
            ftp.enterLocalPassiveMode(); //Remark: after the login!
        }
    } catch (ChannelException e1) {
        throw new ChannelException(e1.getMessage());
    } catch (IOException e1) {
        //TODO: need to think about this...
        throw new ChannelException(e1.getMessage() + " (IOException)");
    }

    try {
        InputStream remoteFileStream = ftp.retrieveFileStream(remote);
        if (remoteFileStream == null) {
            int reply = ftp.getReplyCode();
            throw new ChannelException("Error opening source file " + remote + " (file not found). Reply code: "
                    + Integer.toString(reply));
        }
        setReader(new InputStreamReader(remoteFileStream, "UTF-8"));
    } catch (IOException e) {
        throw new ChannelException("Error opening source file " + remote + " : " + e.getMessage());
    }

    super.open();

    if (logger.isTraceEnabled())
        logger.trace("exit");
}

From source file:com.recomdata.transmart.data.export.util.FTPUtil.java

/**
 * Uploads a given file to the connected FTP Server
 * /*from w  ww  .  ja v  a2 s  .  c o m*/
 * @param binaryTransfer
 * @param localFile
 * @return remote FTP location of the file
 */
public static String uploadFile(boolean binaryTransfer, File localFile) {
    String remote = null;
    boolean uploadComplete = false;
    try {
        connect();
        login();

        if (binaryTransfer)
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();
        ftp.setUseEPSVwithIPv4(false);

        InputStream input = new FileInputStream(localFile);

        remote = FTP_SERVER_REMOTE_PATH + localFile.getName();
        uploadComplete = ftp.storeFile(remote, input);

        input.close();
    } catch (InvalidFTPParamsException e) {
        log.error("Invalid FTP Params to connect");
    } catch (FTPAuthenticationException e) {
        log.error(e.getMessage());
    } catch (FileNotFoundException e) {
        log.error("Not able to load/read the localFile");
    } catch (IOException e) {
        log.error("IOException during FTP upload process");
    } finally {
        if (!uploadComplete)
            remote = null;
    }

    return remote;
}

From source file:com.isencia.message.ftp.FtpSenderChannel.java

/**
 * @see ISenderChannel#open()//  w w w.  jav a 2s  .  c  o m
 */
public void open() throws ChannelException {
    if (logger.isTraceEnabled())
        logger.trace("");

    if (server == null)
        throw new ChannelException("Server is not specified");
    if (username == null)
        throw new ChannelException("Username is not specified");
    if (password == null)
        throw new ChannelException("Password is not specified");
    if (remote == null)
        throw new ChannelException("File is not specified");

    // CONNECT TO SERVER
    try {
        int reply;
        ftp.connect(server, port);
        logger.debug("Connected to " + server + ".");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            logger.error("FTP server refused connection");
            throw new ChannelException("FTP server refused connection");
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        logger.error("Could not connect to server");
        throw new ChannelException("Could not connect to server");
    }

    try {
        // LOGIN TO THE SERVER
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new ChannelException(
                    "Can't login with username " + this.username + " and password " + this.password);
        }

        logger.debug("Remote system is " + ftp.getSystemName());

        // ADJUST SETTINGS
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        if (passiveMode) {
            // Use passive mode as default because most of us are
            // behind firewalls these days.
            ftp.enterLocalPassiveMode(); //Remark: after the login!
        }
    } catch (ChannelException e1) {
        throw new ChannelException(e1.getMessage());
    } catch (IOException e1) {
        //TODO: need to think about this...
        throw new ChannelException(e1.getMessage() + " (IOException)");
    }

    try {
        setWriter(new OutputStreamWriter(ftp.storeFileStream(remote), "UTF-8"));
    } catch (Exception e) {
        logger.error("Error opening destination file " + remote, e);
        throw new ChannelException("Error opening destination file " + remote + " : " + e.getMessage());
    }

    super.open();

    if (logger.isTraceEnabled())
        logger.trace("exit");
}

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
        boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
        String args[]) {/*from ww w . jav a  2  s .  c om*/
    System.out.println("jarName=" + jarName);
    for (String arg : args) {
        if (arg.toLowerCase().trim().equals("-noautoupdate")) {
            return;
        }
    }
    JavaAutoUpdater.basePath = basePath;
    JavaAutoUpdater.softwareName = softwareName;
    JavaAutoUpdater.args = args;

    if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
        if (isDebug) {
            jarName = "test.jar";
        } else {
            return;
        }
    }
    JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.progressBar.setString("Updating");
    //      d.addCancelEventListener(this);
    Thread longRunningThread = new Thread() {
        public void run() {
            d.progressBar.setString("checking latest version");
            System.out.println("checking latest version");

            FTPClient ftp = new FTPClient();
            try {
                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                ftp.connect(ftpHost, ftpPort);
                int reply = ftp.getReplyCode();
                System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                d.progressBar.setString("connected to ftp");
                System.out.println("connected to ftp");
                boolean success = ftp.login(ftpUsername, ftpPassword);
                if (!success) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (isLocalPassiveMode) {
                    ftp.enterLocalPassiveMode();
                }
                if (isRemotePassiveMode) {
                    ftp.enterRemotePassiveMode();
                }
                FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                    @Override
                    public boolean accept(FTPFile file) {
                        if (file.getName().startsWith(softwareName)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
                if (ftpFiles.length > 0) {
                    FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                    System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                            + "!=" + new File(jarName).length());
                    if (!targetFile.getName().equals(jarName)
                            || targetFile.getSize() != new File(jarName).length()) {
                        int r = JOptionPane.showConfirmDialog(null,
                                "Confirm to update to " + targetFile.getName(), "Question",
                                JOptionPane.YES_NO_OPTION);
                        if (r == JOptionPane.YES_OPTION) {
                            //ftp.enterRemotePassiveMode();
                            d.progressBar.setString("downloading " + targetFile.getName());
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                            d.progressBar.setIndeterminate(false);
                            d.progressBar.setMaximum(100);
                            CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                @Override
                                public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                        long streamSize) {
                                    int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                    d.progressBar.setValue(percent);
                                }
                            };
                            ftp.setCopyStreamListener(streamListener);
                            try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            d.progressBar.setString("restarting " + targetFile.getName());
                            restartApplication(targetFile.getName());
                        }
                    }

                }
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    d.thread = longRunningThread;
    d.setVisible(true);
}

From source file:edu.monash.merc.system.remote.FTPFileGetter.java

/**
 * Use Binary mode for file transfers/*from w  ww  .  j av  a 2s .c  om*/
 *
 * @return a boolean value that indicates the setting for binary mode is successful or not.
 */
public boolean binary() {
    boolean setOk = false;
    try {
        setOk = setFileType(FTP.BINARY_FILE_TYPE);
    } catch (Exception ex) {
        throw new DMFTPException(ex);
    }
    return setOk;
}

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {/*from  ww w .  j av  a  2s. c  o m*/
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:fr.chaffottem.bonita.connector.ftp.FTPClientConnector.java

private void configureClient() throws IOException {
    final String transferType = (String) getInputParameter(TRANSFER_TYPE, "binary");
    if ("ascii".equalsIgnoreCase(transferType)) {
        ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
    } else {//from ww w. j av  a 2 s.  c om
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    }
    final String transferMode = (String) getInputParameter(TRANSFER_MODE, "passive");
    if ("active".equalsIgnoreCase(transferMode)) {
        ftpClient.enterLocalActiveMode();
    } else {
        ftpClient.enterLocalPassiveMode();
    }
}

From source file:fr.lille1.car.burihabwa.rest.utils.FTPAdapterImpl.java

public void stor(String path, InputStream received) throws IOException {
    if (path == null) {
        throw new IllegalArgumentException("path argument cannot be null!");
    }//from w  w  w.  j  a v a2  s  .  c om
    if (received == null) {
        throw new IllegalArgumentException("received argument cannot be null!");
    }
    if (!this.client.isConnected()) {
        authenticate();
    }
    String parentDirectory = getParentDirectory(path);
    String file = getFile(path);
    this.client.changeWorkingDirectory(parentDirectory);
    this.client.setBufferSize(4096);
    this.client.setFileType(FTP.BINARY_FILE_TYPE);
    this.client.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
    boolean storeFile = this.client.storeFile(file, received);
    if (!storeFile) {
        Logger.getLogger(FTPAdapterImpl.class.getName()).log(Level.WARNING, this.client.getReplyString());
        throw new IOException(this.client.getReplyString());
    }
    received.close();
    close();
}

From source file:helma.scripting.rhino.extensions.FtpObject.java

public boolean binary() {
    if (ftpclient != null) {
        try {//from  ww  w  . j  av a 2s . c o m
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

            return true;
        } catch (IOException ignore) {
        }
    }

    return false;
}

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. jav  a  2 s  .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
            }
        }
    }
}