Example usage for org.apache.commons.net.ftp FTPReply isPositiveCompletion

List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion

Introduction

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

Prototype

public static boolean isPositiveCompletion(int reply) 

Source Link

Document

Determine if a reply code is a positive completion response.

Usage

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Issue the FTP STAT command to the server for a given pathname.  This
 * should produce a listing of the file or directory.
 * <p>/*from w  w w . j ava 2  s . c o m*/
 * @return The status information returned by the server.
 * @exception FTPConnectionClosedException
 *      If the FTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send FTP reply code 421.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 */
public String getStatus(String pathname) throws IOException {
    if (FTPReply.isPositiveCompletion(stat(pathname))) {
        return getReplyString();
    }
    return null;
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Issue the FTP MDTM command (not supported by all servers to retrieve the last
 * modification time of a file. The modification string should be in the
 * ISO 3077 form "YYYYMMDDhhmmss(.xxx)?". The timestamp represented should also be in
 * GMT, but not all FTP servers honour this.
 *
 * @param pathname The file path to query.
 * @return A string representing the last file modification time in <code>YYYYMMDDhhmmss</code> format.
 * @throws IOException if an I/O error occurs.
 * @since 2.0/*from www  .j  av  a2 s.  c om*/
 */
public String getModificationTime(String pathname) throws IOException {
    if (FTPReply.isPositiveCompletion(mdtm(pathname))) {
        return getReplyString();
    }
    return null;
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Issue the FTP MFMT command (not supported by all servers) which sets the last
 * modified time of a file./*from   ww w  .  j av  a  2 s  .co m*/
 *
 * The timestamp should be in the form <code>YYYYMMDDhhmmss</code>. It should also
 * be in GMT, but not all servers honour this.
 *
 * An FTP server would indicate its support of this feature by including "MFMT"
 * in its response to the FEAT command, which may be retrieved by FTPClient.features()
 *
 * @param pathname The file path for which last modified time is to be changed.
 * @param timeval The timestamp to set to, in <code>YYYYMMDDhhmmss</code> format.
 * @return true if successfully set, false if not
 * @throws IOException if an I/O error occurs.
 * @since 2.2
 * @see <a href="http://tools.ietf.org/html/draft-somers-ftp-mfxx-04">http://tools.ietf.org/html/draft-somers-ftp-mfxx-04</a>
 */
public boolean setModificationTime(String pathname, String timeval) throws IOException {
    return (FTPReply.isPositiveCompletion(mfmt(pathname, timeval)));
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * @deprecated use {@link #getSystemType()} instead
 *///from  w w  w.j  a v  a 2s  . co m
@Deprecated
public String getSystemName() throws IOException {
    if (__systemName == null && FTPReply.isPositiveCompletion(syst())) {
        __systemName = _replyLines.get(_replyLines.size() - 1).substring(4);
    }
    return __systemName;
}

From source file:net.yacy.grid.io.assets.FTPStorageFactory.java

public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread)
        throws IOException {
    this.server = server;
    this.username = username == null ? "" : username;
    this.password = password == null ? "" : password;
    this.port = port;
    this.deleteafterread = deleteafterread;

    this.ftpClient = new Storage<byte[]>() {

        @Override/*from  w w w  .ja  v a 2  s  . com*/
        public void checkConnection() throws IOException {
            return;
        }

        private FTPClient initConnection() throws IOException {
            FTPClient ftp = new FTPClient();
            ftp.setDataTimeout(3000);
            ftp.setConnectTimeout(20000);
            if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) {
                ftp.connect(FTPStorageFactory.this.server);
            } else {
                ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port);
            }
            ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("bad connection to ftp server: " + reply);
            }
            if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("login failure");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(8192);
            return ftp;
        }

        @Override
        public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException {
            long t0 = System.currentTimeMillis();
            FTPClient ftp = initConnection();
            try {
                long t1 = System.currentTimeMillis();
                String file = cdPath(ftp, path);
                long t2 = System.currentTimeMillis();
                ftp.enterLocalPassiveMode();
                boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset));
                long t3 = System.currentTimeMillis();
                if (!success)
                    throw new IOException("storage to path " + path + " was not successful (storeFile=false)");
                Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = "
                        + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2));
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return FTPStorageFactory.this;
        }

        @Override
        public Asset<byte[]> load(String path) throws IOException {
            FTPClient ftp = initConnection();
            ByteArrayOutputStream baos = null;
            byte[] b = null;
            try {
                String file = cdPath(ftp, path);
                baos = new ByteArrayOutputStream();
                ftp.retrieveFile(file, baos);
                b = baos.toByteArray();
                if (FTPStorageFactory.this.deleteafterread)
                    try {
                        boolean deleted = ftp.deleteFile(file);
                        FTPFile[] remaining = ftp.listFiles();
                        if (remaining.length == 0) {
                            ftp.cwd("/");
                            if (path.startsWith("/"))
                                path = path.substring(1);
                            int p = path.indexOf('/');
                            if (p > 0)
                                path = path.substring(0, p);
                            ftp.removeDirectory(path);
                        }
                    } catch (Throwable e) {
                        Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e);
                    }
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return new Asset<byte[]>(FTPStorageFactory.this, b);
        }

        @Override
        public void close() {
        }

        private String cdPath(FTPClient ftp, String path) throws IOException {
            int success_code = ftp.cwd("/");
            if (success_code >= 300)
                throw new IOException("cannot cd into " + path + ": " + success_code);
            if (path.length() == 0 || path.equals("/"))
                return "";
            if (path.charAt(0) == '/')
                path = path.substring(1); // we consider that all paths are absolute to / (home)
            int p;
            while ((p = path.indexOf('/')) > 0) {
                String dir = path.substring(0, p);
                int code = ftp.cwd(dir);
                if (code >= 300) {
                    // path may not exist, try to create the path
                    boolean success = ftp.makeDirectory(dir);
                    if (!success)
                        throw new IOException("unable to create directory " + dir + " for path " + path);
                    code = ftp.cwd(dir);
                    if (code >= 300)
                        throw new IOException("unable to cwd into directory " + dir + " for path " + path);
                }
                path = path.substring(p + 1);
            }
            return path;
        }
    };
}

From source file:network.FtpLogs.java

private void sendFiles() throws SocketException, IOException {
    ftpClient.connect(server, port);// ww w. ja  v a 2 s. c  om
    Log.println("Connected to " + server + ".");
    Log.print(ftpClient.getReplyString());
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        Log.println("FTP server refused connection.");
    } else {
        ftpClient.login(user, pass);
        Log.println("Logging in..");
        Log.print(ftpClient.getReplyString());

        ftpClient.enterLocalPassiveMode();
        ftpClient.setControlKeepAliveTimeout(300); // set timeout to 5 minutes.  Send NOOPs to keep control channel alive

        ftpClient.setFileType(FTP.ASCII_FILE_TYPE);

        /**
         * This is currently disabled because the payload store changed.  We probablly only want to send for one
         * satellite as this is only used for debugging
         * 
        sendFile(PayloadStore.RT_LOG);
        sendFile(PayloadStore.MAX_LOG);
        sendFile(PayloadStore.MIN_LOG);
        sendFile(PayloadStore.RAD_LOG);
        */
        ftpClient.disconnect();
    }
}

From source file:nl.nn.adapterframework.ftp.FTPsClient.java

protected void checkReply(String cmd) throws IOException {
    if (!FTPReply.isPositiveCompletion(getReplyCode())) {
        throw new IOException("Command [" + cmd + "] returned error [" + getReplyString() + "]");
    }/* www  .  jav a  2 s . c om*/
    log.debug("Command [" + cmd + "] returned " + getReplyString());
}

From source file:nl.nn.adapterframework.ftp.FTPsClient.java

public boolean completePendingCommand() throws IOException {
    if (FTPReply.isPositiveCompletion(getReplyCode())) {
        return true;
    }//w w w.j a  va2  s  .c o m
    return super.completePendingCommand();
}

From source file:nl.nn.adapterframework.ftp.FTPsClient.java

private Object _readReply(InputStream in, boolean concatenateLines) throws IOException {
    // obtain the result
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));

    int replyCode = 0;
    StringBuffer reply = new StringBuffer();
    List replyList = new ArrayList();
    String line = reader.readLine();

    if (line == null)
        throw new FTPConnectionClosedException("Connection closed without indication.");
    reply.append(line).append("\n");
    replyList.add(line);//  w ww.  jav  a2  s  .  c  o  m

    // In case we run into an anomaly we don't want fatal index exceptions
    // to be thrown.
    int length = line.length();
    if (length < 3)
        throw new MalformedServerReplyException("Truncated server reply: " + line);

    try {
        String code = line.substring(0, 3);
        replyCode = Integer.parseInt(code);
    } catch (NumberFormatException e) {
        MalformedServerReplyException mfre = new MalformedServerReplyException(
                "Could not parse response code.\nServer Reply [" + line + "]");
        mfre.initCause(e);
        throw mfre;
    }

    // Get extra lines if message continues.
    if (length > 3 && line.charAt(3) == '-') {
        do {
            line = reader.readLine();
            if (line == null)
                throw new FTPConnectionClosedException(
                        "Connection closed without indication after having read [" + reply.toString() + "]");

            reply.append(line).append("\n");
            replyList.add(line);
        } while (!(line.length() >= 4 && line.charAt(3) != '-' && Character.isDigit(line.charAt(0))));
    }

    if (replyCode == FTPReply.SERVICE_NOT_AVAILABLE)
        throw new FTPConnectionClosedException("FTP response 421 received. Server closed connection.");

    if (!FTPReply.isPositiveCompletion(replyCode))
        throw new IOException("Exception while sending command \n" + reply.toString());

    log.debug("_readReply [" + reply.toString() + "]");

    if (concatenateLines) {
        return reply.toString();
    }
    return (String[]) replyList.toArray(new String[0]);
}

From source file:nl.nn.adapterframework.ftp.FtpSession.java

protected void checkReply(String cmd) throws IOException {
    if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
        throw new IOException("Command [" + cmd + "] returned error [" + ftpClient.getReplyCode() + "]: "
                + ftpClient.getReplyString());
    }/*from  www.  j  av a2s  .  c om*/
    if (log.isDebugEnabled())
        log.debug("Command [" + cmd + "] returned " + ftpClient.getReplyString());
}