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

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

Introduction

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

Prototype

public boolean storeFile(String remote, InputStream local) throws IOException 

Source Link

Document

Stores a file on the server using the given name and taking input from the given InputStream.

Usage

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logInfo("[putFile] starting...", module);
    InputStream localFile = null;
    try {/*  w ww .  j  a  v  a2 s .co m*/
        localFile = new FileInputStream((String) context.get("localFilename"));
    } catch (IOException ioe) {
        Debug.logError(ioe, "[putFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            Debug.logInfo("[putFile] Server refused connection", module);
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
            if (!ftp.login(username, password)) {
                Debug.logInfo("[putFile] login failed", module);
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"),
                        module);
                if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
                    Debug.logInfo("[putFile] store was unsuccessful", module);
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                } else {
                    Debug.logInfo("[putFile] store was successful", module);
                    List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
                    if (siteCommands != null) {
                        for (String command : siteCommands) {
                            Debug.logInfo("[putFile] sending SITE command: " + command, module);
                            if (!ftp.sendSiteCommand(command)) {
                                errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed",
                                        UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()),
                                        locale));
                            }
                        }
                    }
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    Debug.logInfo("[putFile] finished successfully", module);
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client/*w w w .  j a v  a  2  s . com*/
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occurring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(this);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, getLocation());
    }
    return returnValue;
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Sends a single file to the remote host. <code>filename</code> may
 * contain a relative path specification. When this is the case, <code>sendFile</code>
 * will attempt to create any necessary parent directories before sending
 * the file. The file will then be sent using the entire relative path
 * spec - no attempt is made to change directories. It is anticipated that
 * this may eventually cause problems with some FTP servers, but it
 * simplifies the coding.//from  w  w  w .  ja  v a 2  s.c o m
 * @param ftp ftp client
 * @param dir base directory of the file to be sent (local)
 * @param filename relative path of the file to be send
 *        locally relative to dir
 *        remotely relative to the remotedir attribute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    InputStream instream = null;

    try {
        // TODO - why not simply new File(dir, filename)?
        File file = getProject().resolveFile(new File(dir, filename).getPath());

        if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
            return;
        }

        if (verbose) {
            log("transferring " + file.getAbsolutePath());
        }

        instream = new BufferedInputStream(new FileInputStream(file));

        createParents(ftp, filename);

        ftp.storeFile(resolveFile(filename), instream);

        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());

        if (!success) {
            String s = "could not put file: " + ftp.getReplyString();

            if (skipFailedTransfers) {
                log(s, Project.MSG_WARN);
                skipped++;
            } else {
                throw new BuildException(s);
            }

        } else {
            // see if we should issue a chmod command
            if (chmod != null) {
                doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename));
            }
            log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE);
            transferred++;
        }
    } finally {
        FileUtils.close(instream);
    }
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client//from   w  w  w  .  j  av a2 s  .  co  m
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occurring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(task);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, task.getLocation());
    }
    return returnValue;
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 * Sends a single file to the remote host. <code>filename</code> may
 * contain a relative path specification. When this is the case, <code>sendFile</code>
 * will attempt to create any necessary parent directories before sending
 * the file. The file will then be sent using the entire relative path
 * spec - no attempt is made to change directories. It is anticipated that
 * this may eventually cause problems with some FTP servers, but it
 * simplifies the coding./*from w  w  w.  ja  va  2s  . c  o  m*/
 * @param ftp ftp client
 * @param dir base directory of the file to be sent (local)
 * @param filename relative path of the file to be send
 *        locally relative to dir
 *        remotely relative to the remotedir attribute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    InputStream instream = null;

    try {
        // TODO - why not simply new File(dir, filename)?
        File file = task.getProject().resolveFile(new File(dir, filename).getPath());

        if (task.isNewer() && isUpToDate(ftp, file, resolveFile(filename))) {
            return;
        }

        if (task.isVerbose()) {
            task.log("transferring " + file.getAbsolutePath());
        }

        instream = new BufferedInputStream(new FileInputStream(file));

        createParents(ftp, filename);

        ftp.storeFile(resolveFile(filename), instream);

        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());

        if (!success) {
            String s = "could not put file: " + ftp.getReplyString();

            if (task.isSkipFailedTransfers()) {
                task.log(s, Project.MSG_WARN);
                skipped++;
            } else {
                throw new BuildException(s);
            }

        } else {
            // see if we should issue a chmod command
            if (task.getChmod() != null) {
                doSiteCommand(ftp, "chmod " + task.getChmod() + " " + resolveFile(filename));
            }
            task.log("File " + file.getAbsolutePath() + " copied to " + task.getServer(), Project.MSG_VERBOSE);
            transferred++;
        }
    } finally {
        FileUtils.close(instream);
    }
}

From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java

/**
 * Sends a single file to the remote host. <code>filename</code> may
 * contain a relative path specification. When this is the case, <code>sendFile</code>
 * will attempt to create any necessary parent directories before sending
 * the file. The file will then be sent using the entire relative path
 * spec - no attempt is made to change directories. It is anticipated that
 * this may eventually cause problems with some FTP servers, but it
 * simplifies the coding.//from   w w  w.jav  a 2 s  .co  m
 * @param ftp ftp client
 * @param dir base directory of the file to be sent (local)
 * @param filename relative path of the file to be send
 *        locally relative to dir
 *        remotely relative to the remotedir attribute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    InputStream instream = null;

    try {
        // TODO - why not simply new File(dir, filename)?
        File file = getProject().resolveFile(new File(dir, filename).getPath());

        if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
            if (verbose)
                log("No need to transfer " + filename + " (" + file.getAbsolutePath() + " is up-to-date)");
            return;
        }

        if (verbose) {

            // Fix for an obvious bug in ANT 1.8.4:
            //              log("transferring " + filename + " to " + file.getAbsolutePath());
            log("transferring " + file.getAbsolutePath() + " to " + filename);
        }

        instream = new BufferedInputStream(new FileInputStream(file));

        createParents(ftp, filename);

        ftp.storeFile(resolveFile(filename), instream);

        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());

        if (!success) {
            String s = "could not put file: " + ftp.getReplyString();

            if (skipFailedTransfers) {
                log(s, Project.MSG_WARN);
                skipped++;
            } else {
                throw new BuildException(s);
            }

        } else {
            // see if we should issue a chmod command
            if (chmod != null) {
                doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename));
            }
            log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE);
            transferred++;
        }
    } finally {
        FileUtils.close(instream);
    }
}

From source file:org.compiere.model.MMediaServer.java

/**
 *    (Re-)Deploy all media//from  w  w  w  .  ja  va  2s . c  o m
 *    @param media array of media to deploy
 *    @return true if deployed
 */
public boolean deploy(MMedia[] media) {
    // Check whether the host is our example localhost, we will not deploy locally, but this is no error
    if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
        log.warning("You have not defined your own server, we will not really deploy to localhost!");
        return true;
    }

    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getIP_Address());
        if (ftp.login(getUserName(), getPassword()))
            log.info("Connected to " + getIP_Address() + " as " + getUserName());
        else {
            log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
        return false;
    }

    boolean success = true;
    String cmd = null;
    //   List the files in the directory
    try {
        cmd = "cwd";
        ftp.changeWorkingDirectory(getFolder());
        //
        cmd = "list";
        String[] fileNames = ftp.listNames();
        log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);

        /*
        FTPFile[] files = ftp.listFiles();
        log.config("Number of files in " + getFolder() + ": " + files.length);
        for (int i = 0; i < files.length; i++)
           log.fine(files[i].getTimestamp() + " \t" + files[i].getName());*/
        //
        cmd = "bin";
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //
        for (int i = 0; i < media.length; i++) {
            if (!media[i].isSummary()) {
                log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                MImage thisImage = media[i].getImage();

                // Open the file and output streams
                byte[] buffer = thisImage.getData();
                ByteArrayInputStream is = new ByteArrayInputStream(buffer);

                String fileName = media[i].get_ID() + media[i].getExtension();
                cmd = "put " + fileName;
                ftp.storeFile(fileName, is);
                is.close();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
        success = false;
    }
    //   Logout from the FTP Server and disconnect
    try {
        cmd = "logout";
        ftp.logout();
        cmd = "disconnect";
        ftp.disconnect();
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
    }
    ftp = null;
    return success;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*from  w  ww.j a v  a2  s .c  o m*/
 * 
 * @author covito
 * @param is
 * @param fileName
 * @param meta
 * @return
 */
@Override
public String upload(InputStream is, String fileName, Map<String, String> meta) {
    init();
    if (null == meta) {
        meta = new HashMap<String, String>();
    }
    if (fileName == null || fileName.length() == 0) {
        fileName = "Unkown";
    }

    meta.put(FileMeta.KEY_FILENAME, fileName);
    String path = generatePath(fileName);

    FTPClient client = getConnect();

    try {
        if (!dealDocPath(client, path, true)) {
            throw new FileServiceException(client.getReplyString());
        }
        boolean sucess = client.storeFile(getFilePath(path), is);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Map<String, Object> m = new HashMap<String, Object>();
    m.putAll(meta);
    JSONObject josn = new JSONObject(m);

    ByteArrayInputStream bis = new ByteArrayInputStream(josn.toString().getBytes());
    try {
        boolean sucess = client.storeFile(getMetaPath(path), bis);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*from   www.ja va 2  s .co m*/
 * 
 * @author covito
 * @param path
 * @param meta
 */
@Override
public void updataMeta(String path, Map<String, String> meta) {
    init();
    FTPClient client = getConnect();
    if (!dealDocPath(client, path, false)) {
        throw new FileServiceException("path not exist!");
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        boolean sucess = client.retrieveFile(getMetaPath(path), bos);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new FileServiceException("path not exist!");
    }
    JSONObject json = JSON.parseObject(bos.toString());
    json.putAll(meta);
    ByteArrayInputStream bis = new ByteArrayInputStream(json.toString().getBytes());
    try {
        boolean sucess = client.storeFile(getMetaPath(path), bis);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {//from  www  .j ava 2  s.c om
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}