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

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

Introduction

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

Prototype

public boolean completePendingCommand() throws IOException 

Source Link

Document

There are a few FTPClient methods that do not complete the entire sequence of FTP commands to complete a transaction.

Usage

From source file:conf.FTPConf.java

public String subirArchivo(File archivo) {

    FTPClient ftpClient = new FTPClient();
    try {/*from  ww  w.j a  v  a  2s.  c  o m*/

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #2: uploads second file using an OutputStream
        String serverFile = dir + archivo.getName();
        InputStream inputStream = new FileInputStream(archivo);

        OutputStream outputStream = ftpClient.storeFileStream(serverFile);
        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) {
            String link = "ftp://" + user + "@" + server + "/" + serverFile;
            return link;
        }

    } 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();
        }
    }
    return null;
}

From source file:net.audumla.climate.bom.BOMDataLoader.java

private boolean storeFTPFile(String host, String location, OutputStream os) {
    FTPClient ftp = getFTPClient(host);
    try {//  ww w  .  j a  va  2 s .co  m
        if (getFTPFile(host, location) != null) {
            synchronized (ftp) {
                IOUtils.copy(ftp.retrieveFileStream(location), os);
            }
        } else {
            return false;
        }
    } catch (IOException ex) {
        LOG.warn("Unable to load file " + location + " FTP Reply -> " + ftp.getReplyCode(), ex);
        return false;
    } finally {
        try {
            os.close();
        } catch (Exception ex) {
            LOG.error("Unknown error encountered storing file " + location, ex);
        }
    }
    LOG.info("Retrieved remote FTP content - " + "ftp://" + host + location);
    try {
        if (!ftp.completePendingCommand()) {
            ftp.logout();
            ftp.disconnect();
        }
    } catch (Exception ex) {
        LOG.error("Unknown error encountered storing file " + location, ex);
    }
    return true;
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public void getFile(String remoteFile, File localFile) throws Exception {

    FTPClient ftpClient = new FTPClient();
    OutputStream outputStream = null;
    try {// w ww.j  a v a2 s .  c o  m
        ftpClient.connect(ftpHost, ftpPort);
        ftpClient.enterLocalPassiveMode();
        if (ftpUser != null && ftpUser.length() > 0)
            ftpClient.login(ftpUser, ftpPassword);
        else
            ftpClient.login("anonymous", "");
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        boolean commandOK = ftpClient.completePendingCommand();
        //boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        //if (!success) {
        //   throw new Exception("Error retrieving remote file: " + remoteFile);
        //}   
    } finally {
        outputStream.close();
        ftpClient.disconnect();
    }
}

From source file:ddf.test.itests.catalog.TestFtp.java

private void ftpPutStreaming(FTPClient client, String data, String fileName) throws IOException {
    LOGGER.info("Start data upload via FTP PUT...");

    try (InputStream is = new ByteArrayInputStream(data.getBytes());
            OutputStream os = client.storeFileStream(fileName)) {
        byte[] bytesIn = new byte[4096];
        int read = 0;

        while ((read = is.read(bytesIn)) != -1) {
            os.write(bytesIn, 0, read);/*from  w w w.  j  a v a  2s  .c o  m*/
        }
    }

    showServerReply(client);

    // finalize the file transfer
    boolean done = client.completePendingCommand();
    if (done) {
        LOGGER.debug("File uploaded successfully.");
    } else {
        LOGGER.error("Failed to upload file.");
    }
}

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

public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) {
    FTPClient ftpClient = new FTPClient();
    InputStream inputStream = null;
    try {/*from   ww  w  .  jav  a  2  s.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:com.zurich.sds.sino.utils.UploadZurichFTP.java

public void controller(FTPClient ftpClient, String preaperUpDirPath, String remoteDirPath_dir)
        throws FileNotFoundException, IOException {

    //FTPClient ftpClient = new FTPClient();
    try {/* ww  w.j  ava  2  s.  com*/

        // APPROACH #2: uploads second file using an OutputStream
        File secondLocalFile = new File(preaperUpDirPath + this.LocalFile);
        //System.out.println("..........LocalFile..prepare up load loc:"+secondLocalFile);
        String secondRemoteFile = remoteDirPath_dir + "/" + this.LocalFile;
        InputStream inputStream = new FileInputStream(secondLocalFile);

        System.out.println("..........iUPLOADj the file from " + secondLocalFile + " to " + secondRemoteFile);
        logger.info("..........iUPLOADj the file from " + secondLocalFile + " to " + secondRemoteFile);
        OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);

        //ftpClient.deleteFile(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  file is uploaded successfully.");
            logger.info("The  file is uploaded successfully.");
            setCompleted(completed);
        }

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        logger.info("Error: " + ex.getMessage());
        ex.printStackTrace();
    }

}

From source file:GridFDock.DataDistribute.java

public Status uploadFile(String remoteFile, File localFile, FTPClient ftpClient, long remoteSize)
        throws IOException {

    long step = localFile.length() / 100;
    long process = 0;
    long localreadbytes = 0L;
    boolean tmp2 = true;
    Status result = null;/*from  ww w  .j a v a 2  s.co  m*/
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

    while (tmp2) {
        RandomAccessFile raf = new RandomAccessFile(localFile, "r");
        OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(CODING_1), CODING_2));

        if (remoteSize > 0) {
            ftpClient.setRestartOffset(remoteSize);
            process = remoteSize / step;
            raf.seek(remoteSize);
            localreadbytes = remoteSize;
        }
        byte[] bytes = new byte[1024];
        int c;
        while ((c = raf.read(bytes)) != -1) {
            out.write(bytes, 0, c);
            localreadbytes += c;
            if (localreadbytes / step != process) {
                process = localreadbytes / step;
                // System.out.println("Upload Progress" + process);

            }
        }
        out.flush();
        raf.close();
        out.close();
        boolean judge = ftpClient.completePendingCommand();

        if (judge) {
            result = Status.Upload_From_Break_Success;
            tmp2 = false;
        } else {
            result = Status.Upload_New_File_Failed;
        }
    }
    return result;
}

From source file:com.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {/* w  w  w.j  a  v a 2 s .c  o 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.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException {
    String server = properties.getValue(propServer);
    String path = properties.getValue(propPath);
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);
    String fileNamePattern = properties.getValue(propFileNamePattern);
    boolean deleteAfterLoad = Boolean.TRUE.toString().equals(properties.getValue(propDeleteAfterLoad));
    boolean truncateWhenFilesFound = Boolean.TRUE.toString()
            .equals(properties.getValue(propTruncateIndexWhenFilesFound));
    Pattern pattern = null;// www. j a  v a  2s.com
    if (fileNamePattern != null && fileNamePattern.length() > 0)
        pattern = Pattern.compile(fileNamePattern);

    String p = properties.getValue(propBuffersize);
    String xsl = properties.getValue(propXsl);
    File xmlTempResult = null;
    int bufferSize = 50;
    if (p != null && p.length() > 0)
        bufferSize = Integer.parseInt(p);
    HttpDownloader httpDownloader = client.getWebCrawlMaster().getNewHttpDownloader(true);
    FTPClient ftp = null;
    InputStream inputStream = null;
    try {
        // FTP Connection
        ftp = new FTPClient();
        checkConnect(ftp, server, login, password);
        FTPFile[] files = ftp.listFiles(path, new FtpFileInstance.FtpInstanceFileFilter(true, false, null));
        if (files == null)
            return;
        // Sort by ascendant filename
        String[] fileNames = new String[files.length];
        int i = 0;
        for (FTPFile file : files)
            fileNames[i++] = file.getName();
        Arrays.sort(fileNames);
        int ignored = 0;
        int loaded = 0;
        boolean bAlreadyTruncated = false;
        for (String fileName : fileNames) {
            String filePathName = FilenameUtils.concat(path, fileName);
            if (pattern != null)
                if (!pattern.matcher(fileName).find()) {
                    ignored++;
                    continue;
                }
            if (truncateWhenFilesFound && !bAlreadyTruncated) {
                client.deleteAll();
                bAlreadyTruncated = true;
            }
            taskLog.setInfo("Working on: " + filePathName);
            inputStream = ftp.retrieveFileStream(filePathName);
            Node xmlDoc = null;
            if (xsl != null && xsl.length() > 0) {
                xmlTempResult = File.createTempFile("ossftpfeed", ".xml");
                DomUtils.xslt(new StreamSource(inputStream), xsl, xmlTempResult);
                xmlDoc = DomUtils.readXml(new StreamSource(xmlTempResult), false);
            } else
                xmlDoc = DomUtils.readXml(new StreamSource(inputStream), false);
            client.updateXmlDocuments(xmlDoc, bufferSize, null, httpDownloader, taskLog);
            client.deleteXmlDocuments(xmlDoc, bufferSize, taskLog);
            inputStream.close();
            inputStream = null;
            if (!ftp.completePendingCommand())
                throw new SearchLibException("FTP Error");
            if (xmlTempResult != null) {
                xmlTempResult.delete();
                xmlTempResult = null;
            }
            checkConnect(ftp, server, login, password);
            if (deleteAfterLoad)
                ftp.deleteFile(filePathName);
            loaded++;
        }
        taskLog.setInfo(loaded + " file(s) loaded - " + ignored + " file(s) ignored");
    } catch (XPathExpressionException e) {
        throw new SearchLibException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SearchLibException(e);
    } catch (ParserConfigurationException e) {
        throw new SearchLibException(e);
    } catch (SAXException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    } catch (InstantiationException e) {
        throw new SearchLibException(e);
    } catch (IllegalAccessException e) {
        throw new SearchLibException(e);
    } catch (ClassNotFoundException e) {
        throw new SearchLibException(e);
    } catch (TransformerException e) {
        throw new SearchLibException(e);
    } finally {
        if (xmlTempResult != null)
            xmlTempResult.delete();
        IOUtils.close(inputStream);
        try {
            if (ftp != null)
                if (ftp.isConnected())
                    ftp.disconnect();
        } catch (IOException e) {
            Logging.warn(e);
        }
        if (httpDownloader != null)
            httpDownloader.release();
    }
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);//  w  ww.  jav  a 2  s.c  om
        //               System.out.println( "Connected.");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

        //               System.out.println( "Logging in ...");

        if (!client.login(username, password)) {
            //                  System.out.println( "Could not log in.");
            // TODO bring up login dialog?
            client.disconnect();

            throw new IOException("Could not login to FTP Server \"" + host + "\".");
        }

        //               System.out.println( "Logged in.");

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}