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

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

Introduction

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

Prototype

public String getReplyString() 

Source Link

Document

Returns the entire text of the last FTP server response exactly as it was received, including all end of line markers in NETASCII format.

Usage

From source file:org.jnode.protocol.ftp.FTPURLConnection.java

/**
 * @see java.net.URLConnection#getInputStream()
 *///from   w  w  w  .j  ava  2s .c  o  m
public InputStream getInputStream() throws IOException {
    FTPClient client = new FTPClient();
    client.connect(host);
    String replyString = client.getReplyString();
    int replyCode = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        client.disconnect();
        throw new IOException(replyString);
    }
    if (!client.login(username, password)) {
        replyString = client.getReplyString();
        client.logout();
        throw new IOException(replyString);
    }
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        client.retrieveFile(path, os);
        client.logout();
    } finally {
        client.disconnect();
    }
    return new ByteArrayInputStream(os.toByteArray());
}

From source file:org.moxie.ftp.FTP.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection/*from   ww w.j  av  a2s .  co m*/
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (verbose) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            log("Creating directory: " + dir + " in /");
        } else {
            log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (verbose) {
                    log("Directory already exists");
                }
            } else {
                if (verbose) {
                    log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:org.moxie.ftp.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.j  a  v  a2s.c  om
 * @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 {
        // XXX - 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 {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:org.moxie.ftp.FTPTaskMirrorImpl.java

/**
 * Retrieve a single file from the remote host. <code>filename</code> may
 * contain a relative path specification. <p>
 *
 * The file will then be retreived 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.</p>/*www .ja v  a2s  .co  m*/
 * @param ftp the ftp client
 * @param dir local base directory to which the file should go back
 * @param filename relative path of the file based upon the ftp remote directory
 *        and/or the local base directory (dir)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if skipFailedTransfers is false
 * and the file cannot be retrieved.
 */
protected void getFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    OutputStream outstream = null;
    try {
        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 " + filename + " to " + file.getAbsolutePath());
        }

        File pdir = file.getParentFile();

        if (!pdir.exists()) {
            pdir.mkdirs();
        }
        outstream = new BufferedOutputStream(new FileOutputStream(file));
        ftp.retrieveFile(resolveFile(filename), outstream);

        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            String s = "could not get file: " + ftp.getReplyString();

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

        } else {
            task.log("File " + file.getAbsolutePath() + " copied from " + task.getServer(),
                    Project.MSG_VERBOSE);
            transferred++;
            if (task.isPreserveLastModified()) {
                outstream.close();
                outstream = null;
                FTPFile[] remote = ftp.listFiles(resolveFile(filename));
                if (remote.length > 0) {
                    FILE_UTILS.setFileLastModified(file, remote[0].getTimestamp().getTime().getTime());
                }
            }
        }
    } finally {
        if (outstream != null) {
            try {
                outstream.close();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:org.moxie.ftp.FTPTaskMirrorImpl.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection/*from www . j  ava  2s.  c o m*/
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (task.isVerbose()) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            task.log("Creating directory: " + dir + " in /");
        } else {
            task.log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        task.log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(task.isIgnoreNoncriticalErrors()
                        && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (task.isVerbose()) {
                    task.log("Directory already exists");
                }
            } else {
                if (task.isVerbose()) {
                    task.log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:org.mule.transport.ftp.FtpConnector.java

/**
 * Well get the output stream (if any) for this type of transport. Typically this
 * will be called only when Streaming is being used on an outbound endpoint
 *
 * @param endpoint the endpoint that releates to this Dispatcher
 * @param event the current event being processed
 * @return the output stream to use for this request or null if the transport
 *         does not support streaming/*from   w w w  .  j av a  2 s  . co  m*/
 */
@Override
public OutputStream getOutputStream(OutboundEndpoint endpoint, MuleEvent event) throws MuleException {
    try {
        final EndpointURI uri = endpoint.getEndpointURI();
        String filename = getFilename(endpoint, event.getMessage());

        final FTPClient client;
        try {
            client = this.createFtpClient(endpoint);
        } catch (Exception e) {
            throw new ConnectException(e, this);
        }

        try {
            OutputStream out = client.storeFileStream(filename);
            if (out == null) {
                throw new IOException("FTP operation failed: " + client.getReplyString());
            }

            return new CallbackOutputStream(out, new CallbackOutputStream.Callback() {
                public void onClose() throws Exception {
                    try {
                        if (!client.completePendingCommand()) {
                            client.logout();
                            client.disconnect();
                            throw new IOException("FTP Stream failed to complete pending request");
                        }
                    } finally {
                        releaseFtp(uri, client);
                    }
                }
            });
        } catch (Exception e) {
            logger.debug("Error getting output stream: ", e);
            releaseFtp(uri, client);
            throw e;
        }
    } catch (ConnectException ce) {
        // Don't wrap a ConnectException, otherwise the retry policy will not go into effect.
        throw ce;
    } catch (Exception e) {
        throw new DispatchException(CoreMessages.streamingFailedNoStream(), event, endpoint, e);
    }
}

From source file:org.programmatori.domotica.own.plugin.remote.FTPUtility.java

/**
 * Funzione che consente la connessione ad un Server FTP
 * /*from w w  w  .j  a  v  a  2s.co  m*/
 * @param ftpServer Server FTP
 * @param username Nome utente per l'accesso
 * @param password Password per l'accesso
 * @return Un oggetto di tipo FTPClient contenente il Client per l'accesso
 */
public static FTPClient connect(String ftpServer, String username, String password) {

    FTPClient ftp = new FTPClient();
    String replyString;
    try {
        ftp.connect(ftpServer);
        ftp.login(username, password);
        log.info("Connesso a " + ftpServer + ".");

        replyString = ftp.getReplyString();
        log.debug(replyString);

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("Il Server FTP ha rifiutato la connessione.");
            log.error(replyString);
            return null;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ftp;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate).
 * Copying is done through a retrieve operation.
 * //from  w ww . java2s . co  m
 * @param ftpSource
 * @param localDestPat
 * @param filePattern
 * @return the number of files being copied
 * @throws IOException 
 */
public Integer syncPull(FTPClient ftpSource, String localDestPat, String filePattern) throws IOException {
    // check for new files since the last check which need to be copied

    Integer number = 0;
    SortedMap<FileNameDate, File> destMap = FileUtils.fileMapByNameAndDate(localDestPat, filePattern);
    SortedMap<FileNameDate, FTPFile> sourceMap = fileMapByNameAndDate(ftpSource, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (FTPFile file : sourceMap.values()) {
        logger.debug("Copying file " + file.getName() + ": " + file.getTimestamp());
        File copy = new File(localDestPat, file.getName());
        try {
            if (!copy.exists()) {
                // copy to tmp file first to avoid clashes during lengthy copy action
                File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile());
                FileOutputStream writeStream = new FileOutputStream(tmp);
                boolean rc = ftpSource.retrieveFile(file.getName(), writeStream);
                writeStream.close();
                if (rc) {
                    rc = tmp.renameTo(copy);
                    number++;
                }
                if (!rc) {
                    tmp.delete(); // cleanup if we fail
                }
            }
        } catch (IOException ex) {
            logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error  "
                    + ftpSource.getReplyString(), ex);
        }
    }
    return number;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate).
 * Copying is done from local directory into remote ftp destination directory.
 * /*from   ww  w. ja va  2s . c o m*/
 * @param destPath
 * @param localSourcePath
 * @param filePattern
 * @return the number of files being copied
 * @throws IOException 
 */
public Integer syncPush(String localSourcePath, FTPClient ftpDest, String filePattern) throws IOException {
    // check for new files since the last check which need to be copied

    Integer number = 0;
    SortedMap<FileNameDate, FTPFile> destMap = fileMapByNameAndDate(ftpDest, filePattern);
    SortedMap<FileNameDate, File> sourceMap = FileUtils.fileMapByNameAndDate(localSourcePath, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (File file : sourceMap.values()) {
        logger.debug(file.getName() + ": " + new Date(file.lastModified()));

        try {
            // only copy file that don't exist yet
            if (ftpDest.listNames(file.getName()).length == 0) {
                FileInputStream fin = new FileInputStream(file);
                String tmpName = "tempFile";
                boolean rc = ftpDest.storeFile(tmpName, fin);
                fin.close();
                if (rc) {
                    rc = ftpDest.rename(tmpName, file.getName());
                    number++;
                }
                if (!rc) {
                    ftpDest.deleteFile(tmpName);
                }
            }
        } catch (Exception ex) {
            logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error  "
                    + ftpDest.getReplyString());
        }
    }
    return number;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Creates the needed directories if necessary.
 * @param ftpClient A <code>FTPClient</code> being <b>connected</b>.
 * @param basePath The base path. This one <b>has to exist</b> on the ftp server!
 * @param path The path to be created./*from ww w.j  a v  a2  s  . co  m*/
 * @throws IOException IN case of an error.
 */
private boolean ensureFtpDirectory(FTPClient ftpClient, String basePath, String path) throws IOException {
    ftpClient.changeWorkingDirectory(basePath);
    StringTokenizer tokenizer = new StringTokenizer(path, "/");
    while (tokenizer.hasMoreTokens()) {
        String folder = tokenizer.nextToken();
        FTPFile[] ftpFile = ftpClient.listFiles(folder);
        if (ftpFile.length == 0) {
            // create the directoy
            if (!ftpClient.makeDirectory(folder)) {
                logger.error(
                        "Ftp Creating the destination directory did not succeed " + ftpClient.getReplyString());
                return false;
            }
        }
        ftpClient.changeWorkingDirectory(folder);
    }
    return true;
}