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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

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

/**
 * //  www  .ja v  a  2s. com
 * @param destFile
 * @param generator Flushes messages through the channel
 * (channel close => destFile closed, the generator can only write while channel open)
 */
public FtpSenderChannel(String destFile, String server, String username, String password,
        boolean isBinaryTransfer, boolean isPassiveMode, IMessageGenerator generator) {
    super(generator);
    this.remote = destFile; //Remote file to read/write
    this.server = server;
    this.username = username;
    this.password = password;
    this.binaryTransfer = isBinaryTransfer;
    this.passiveMode = isPassiveMode;
    ftp = new FTPClient();
}

From source file:gr.interamerican.bo2.utils.ftp.FtpSession.java

/**
 * Creates a new FTPClient.
 * 
 * @return Returns a new FTPClient.
 */
FTPClient newFtpClient() {
    return new FTPClient();
}

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

public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) {
    FTPClient ftpClient = new FTPClient();
    InputStream inputStream = null;
    try {//from www. java  2s. c  o  m
        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:helma.scripting.rhino.extensions.FtpObject.java

/**
 * Login to the FTP server//ww w  .  jav  a 2  s.  c  o  m
 *
 * @param   username the user name
 * @param   password the user's password
 * @return  true if successful, false otherwise
 */
public boolean login(String username, String password) {
    if (server == null) {
        return false;
    }

    try {
        ftpclient = new FTPClient();
        ftpclient.connect(server);

        return ftpclient.login(username, password);
    } catch (Exception x) {
        return false;
    } catch (NoClassDefFoundError x) {
        return false;
    }
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public LinkedList<AZoFTPFile> checkConnection(boolean includeDirs) {

    if (!"".equals(getLastWorkingConnection())) {
        LinkedList<String> t = new LinkedList<>();
        t.add(getLastWorkingConnection());
        for (String s : possibleConnections) {
            if (!s.equals(lastWorkingConnection)) {
                t.add(s);/*from  w  w  w. j  a v a2  s  .  c  om*/
            }
        }
        possibleConnections = t.toArray(new String[0]);
    }
    for (String ip : possibleConnections) {
        notify(FTPConnectionStatus.TRYING, ip, -1);
        if (ftpclient != null) {
            close();
        }
        ftpclient = new FTPClient();

        try {
            ftpclient.setDefaultTimeout(TIMEOUT);
            ftpclient.connect(ip);
            if (ftpclient.isAvailable()) {
                LinkedList<AZoFTPFile> retval = discoverRemoteFiles("/", includeDirs);

                lastWorkingConnection = ip;

                close();

                notify(FTPConnectionStatus.CONNECTED, ip, -1);

                return retval;
            } else {
                close();
            }
        } catch (IOException ex) {
            close();
            notify(FTPConnectionStatus.NOCONNECTION, "", -1);
            Logger.getLogger(FTPConnection.class.getName()).log(Level.INFO, null, ex);
        }

    }
    setLooksFullySynced(false);
    notify(FTPConnectionStatus.NOCONNECTION, "", -1);
    return null;
}

From source file:lucee.runtime.net.ftp.FTPWrap.java

/**
 * connects the client/*from w w w.  j av  a 2  s. c  o m*/
 * @throws IOException
 */
private void connect() throws IOException {

    client = new FTPClient();

    setConnectionSettings(client, conn);

    // transfer mode
    if (conn.getTransferMode() == FTPConstant.TRANSFER_MODE_ASCCI)
        getClient().setFileType(FTP.ASCII_FILE_TYPE);
    else if (conn.getTransferMode() == FTPConstant.TRANSFER_MODE_BINARY)
        getClient().setFileType(FTP.BINARY_FILE_TYPE);

    // Connect
    try {
        Proxy.start(conn.getProxyServer(), conn.getProxyPort(), conn.getProxyUser(), conn.getProxyPassword());
        client.connect(address, conn.getPort());
        client.login(conn.getUsername(), conn.getPassword());
    } finally {
        Proxy.end();
    }
}

From source file:de.thischwa.pmcms.tool.connection.ftp.FtpConnectionManager.java

@Override
public void start() {
    ftpClient = new FTPClient();
    try {/*from   ww w .  j  a  v a 2s. co m*/
        // 1. set the port
        ftpClient.setDefaultPort(port);

        // 2. set the encoding, FTPClient() default is ISO-8859-1, which isn't well
        //    this step has to be done before login !!
        ftpClient.setControlEncoding(DEFAULT_ENCODING);

        // 3. connect to the server
        ftpClient.connect(host);
        checkReply(); // throws exception, if server replied an error
        logger.debug("[FTP] Connected to " + host + ":" + port);

        // 4. login
        ftpClient.login(loginName, loginPassword);
        checkReply();
        logger.debug("[FTP] Remote system is " + ftpClient.getSystemType());

        // 5. set the passive mode because most clients are behind a firewall
        ftpClient.enterLocalPassiveMode();

        // 6. set the default file TYPE
        ftpClient.setFileType(DEFAULT_FILE_TYPE);

        // 7. change to the remote start directory
        if (StringUtils.isNotBlank(remoteStartDir)) {
            ftpClient.changeWorkingDirectory(remoteStartDir);
            checkReply();
            logger.debug("[FTP] Start directory set: " + ftpClient.getReplyString());
        }

        // 8. save the root dir
        serverRootDir = ftpClient.printWorkingDirectory();
        if (!serverRootDir.endsWith("/"))
            serverRootDir = serverRootDir.concat("/");

        logger.debug("[FTP] Login procedere completely successfull!");
    } catch (IOException e) {
        close();
        throw new ConnectionRunningException("While login procedere: " + e.getMessage(), e);
    }
}

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  ww w.  j  a  v  a 2 s  .com*/
        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.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 w w w  .j ava  2  s. c o  m*/
    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:Controlador.ControlResultadosActividades.java

public ControlResultadosActividades() {

    ftpClient = new FTPClient();
    infoUsuarioConectado = "Informacin Usuario Conectado";
    permisoIngresar = false;//from w  ww  .j a  v a  2 s. c  om
    permisoReservar = true;
    permisoPrestamo = true;
    permisoDocPracticas = true;
    permisoLaboratorio = true;
    permisoEstadisticas = true;
    permisoGuias = true;
    permisoUsuario = true;
    permisoMateria = true;
    permisoCerrarSesion = true;

    listResultadosActividades = null;
    permitirIndex = true;
    guardado = true;
    tamano = 270;
    nuevaResultadosActividades = new ResultadosActividades();
}