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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:com.buzz.buzzdata.MongoBuzz.java

private InputStream getFTPInputStream(String ftp_location) {
    InputStream retval = null;//from   www.j  av  a 2s  .  c o  m

    String server = "162.219.245.61";
    int port = 21;
    String user = "jelastic-ftp";
    String pass = "HeZCHxeefB";
    FTPClient ftpClient = new FTPClient();

    try {
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        retval = ftpClient.retrieveFileStream(ftp_location);
    } catch (IOException ex) {
        Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return retval;
}

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 a2s  . 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:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream2(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    File downloadFile1 = null;//from w  ww .ja  v  a 2 s.c o m
    try {
        downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        //ftpClient.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) );
        //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD));
        //ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        boolean success;
        String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12";
        downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12");
        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
        success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12");
        FileInputStream fis = new FileInputStream(
                "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12");
        InputStream is = fis;
        if (success) {
            System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf");
        } else {
            System.out.println("File #1 has been downloaded successfully. 3333");
        }
        ;
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

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 {//  www  .j a  v  a 2 s.co 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.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {/*  w  ww.  ja v  a 2 s.  co  m*/
        // The executes in the IO thread!
        String sourceVar = getSourceVar(messageContext);
        InputStream src = null;
        boolean wantBase64Decode = getWantBase64Decode(messageContext);
        if (sourceVar == null) {
            src = messageContext.getMessage().getContentAsStream();
            // conditionally wrap a decoder around it
            if (wantBase64Decode) {
                src = new Base64InputStream(src);
            }
        } else {
            info.addMessage("Retrieving data from " + sourceVar);
            String sourceData = messageContext.getVariable(sourceVar);
            byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData)
                    : sourceData.getBytes(StandardCharsets.UTF_8);
            src = new ByteArrayInputStream(b);
        }
        String remoteName = getRemoteFileName(messageContext);
        remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-");

        String ftpServer = getFtpServer(messageContext);
        int ftpPort = getFtpPort(messageContext);
        String user = getFtpUser(messageContext);
        String password = getFtpPassword(messageContext);

        info.addMessage("connecting to server " + ftpServer);
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new FtpCommandListener(info));
        ftp.connect(ftpServer, ftpPort);
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("The FTP server refused the connection.");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }

        if (!ftp.login(user, password)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("Login failure");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }
        info.addMessage("logged in as " + user);

        String initialDirectory = getInitialDirectory(messageContext);
        if ((initialDirectory != null) && (!initialDirectory.equals(""))) {
            ftp.changeWorkingDirectory(initialDirectory);
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        OutputStream os = ftp.storeFileStream(remoteName);
        if (os == null) {
            // cannot open output stream
            info.addMessage("cannot open output stream to " + remoteName);
            info.setStatus("FAIL");
        } else {
            byte[] buf = new byte[2048];
            int n;
            while ((n = src.read(buf)) > 0) {
                os.write(buf, 0, n);
            }
            os.close();
            src.close();
            boolean completed = ftp.completePendingCommand();
            info.addMessage("transfer completed: " + completed);
            info.setStatus("OK");
        }

        ftp.disconnect();
        info.addMessage("All done.");
        messageContext.setVariable(varName("result"), info.toJsonString());
    } catch (java.lang.Exception exc1) {
        if (getDebug()) {
            System.out.println(ExceptionUtils.getStackTrace(exc1));
        }
        String error = exc1.toString();
        messageContext.setVariable(varName("exception"), error);
        info.setStatus("FAIL");
        info.addMessage(error);
        messageContext.setVariable(varName("result"), info.toJsonString());
        int ch = error.lastIndexOf(':');
        if (ch >= 0) {
            messageContext.setVariable(varName("error"), error.substring(ch + 2).trim());
        } else {
            messageContext.setVariable(varName("error"), error);
        }
        messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1));
        return ExecutionResult.ABORT;
    }

    return ExecutionResult.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  w  w . ja  v  a 2  s.  c om
        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.claim.support.FtpUtil.java

public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) {
    try {//from   ww w.j  a va  2 s  . 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:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *//*w  w w  .  j a va 2  s.c om*/
@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: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 {/*from  www.  j  a va 2s . 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:net.siegmar.japtproxy.fetcher.FetcherFtp.java

/**
 * {@inheritDoc}//from ww w  . java  2 s  .  co m
 */
@Override
public FetchedResourceFtp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final FTPClient ftpClient = new FTPClient();
    ftpClient.setSoTimeout(socketTimeout);
    ftpClient.setDataTimeout(dataTimeout);

    try {
        final String host = targetResource.getHost();
        final String resourceName = targetResource.getPath();

        LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName);

        ftpClient.connect(host);
        ftpClient.enterLocalPassiveMode();

        if (!ftpClient.login("anonymous", "japt-proxy")) {
            throw new IOException("Can't login to FTP server");
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        final FTPFile[] files = ftpClient.listFiles(resourceName);

        if (files.length == 0) {
            throw new ResourceUnavailableException("Resource '" + resourceName + "' not found");
        }

        if (files.length > 1) {
            throw new IOException("Multiple files found");
        }

        final FTPFile file = files[0];

        final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file);
        fetchedResourceFtp
                .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis());

        return fetchedResourceFtp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceFtp
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }

        throw e;
    }
}