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

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

Introduction

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

Prototype

public static boolean isPositivePreliminary(int reply) 

Source Link

Document

Determine if a reply code is a positive preliminary response.

Usage

From source file:com.consol.citrus.ftp.client.FtpClient.java

@Override
public void send(Message message, TestContext context) {
    FtpMessage ftpMessage;/*from  w w w. j  av a2s.com*/
    if (message instanceof FtpMessage) {
        ftpMessage = (FtpMessage) message;
    } else {
        ftpMessage = new FtpMessage(message);
    }

    String correlationKeyName = getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName());
    String correlationKey = getEndpointConfiguration().getCorrelator().getCorrelationKey(ftpMessage);
    correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);

    log.info(String.format("Sending FTP message to: ftp://'%s:%s'", getEndpointConfiguration().getHost(),
            getEndpointConfiguration().getPort()));

    if (log.isDebugEnabled()) {
        log.debug("Message to be sent:\n" + ftpMessage.getPayload(String.class));
    }

    try {
        connectAndLogin();

        int reply = ftpClient.sendCommand(ftpMessage.getCommand(), ftpMessage.getArguments());

        if (!FTPReply.isPositiveCompletion(reply) && !FTPReply.isPositivePreliminary(reply)) {
            throw new CitrusRuntimeException(String.format("Failed to send FTP command - reply is: %s:%s",
                    reply, ftpClient.getReplyString()));
        }

        log.info(String.format("FTP message was successfully sent to: '%s:%s'",
                getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()));

        correlationManager.store(correlationKey,
                new FtpMessage(ftpMessage.getCommand(), ftpMessage.getArguments()).replyCode(reply)
                        .replyString(ftpClient.getReplyString()));
    } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to execute ftp command", e);
    }

}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public InputStream getFile(final String filename) {
    return timeLogAndCatch("Get file stream " + filename, new Callable<InputStream>() {
        @Override/*from  w w w .  ja va  2s.  c o m*/
        public InputStream call() throws Exception {
            final InputStream is = preparedClient.retrieveFileStream(filename);
            int reply = preparedClient.getReplyCode();
            if (is == null
                    || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {
                throw new FtpException("Failed to open input stream: %s", preparedClient.getReplyString());
            }

            return new InputStream() {
                @Override
                public int read() throws IOException {
                    return is.read();
                }

                @Override
                public int read(byte[] b) throws IOException {
                    return is.read(b);
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    return is.read(b, off, len);
                }

                @Override
                public void close() throws IOException {
                    is.close();
                    preparedClient.completePendingCommand();
                }
            };
        }
    });
}

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

/**
 * Initiates control connections and gets initial reply.
 * Initializes {@link #_controlInput_} and {@link #_controlOutput_}.
 *//*from   w  w  w . jav a2  s  .  c o  m*/
@Override
protected void _connectAction_() throws IOException {
    super._connectAction_(); // sets up _input_ and _output_
    _controlInput_ = new CRLFLineReader(new InputStreamReader(_input_, getControlEncoding()));
    _controlOutput_ = new BufferedWriter(new OutputStreamWriter(_output_, getControlEncoding()));
    if (connectTimeout > 0) { // NET-385
        int original = _socket_.getSoTimeout();
        _socket_.setSoTimeout(connectTimeout);
        try {
            __getReply();
            // If we received code 120, we have to fetch completion reply.
            if (FTPReply.isPositivePreliminary(_replyCode)) {
                __getReply();
            }
        } catch (SocketTimeoutException e) {
            IOException ioe = new IOException("Timed out waiting for initial connect reply");
            ioe.initCause(e);
            throw ioe;
        } finally {
            _socket_.setSoTimeout(original);
        }
    } else {
        __getReply();
        // If we received code 120, we have to fetch completion reply.
        if (FTPReply.isPositivePreliminary(_replyCode)) {
            __getReply();
        }
    }
}

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

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>/*  w  ww.  jav  a  2 s . c o m*/
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 * @since 3.1
 */
protected Socket _openDataConnection_(String command, String arg) throws IOException {
    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
        return null;
    }

    final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;

    Socket socket;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        // if no activePortRange was set (correctly) -> getActivePort() = 0
        // -> new ServerSocket(0) -> bind to any free local port
        ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());

        try {
            // Try EPRT only if remote server is over IPv6, if not use PORT,
            // because EPRT has no advantage over PORT on IPv4.
            // It could even have the disadvantage,
            // that EPRT will make the data connection fail, because
            // today's intelligent NAT Firewalls are able to
            // substitute IP addresses in the PORT command,
            // but might not be able to recognize the EPRT command.
            if (isInet6Address) {
                if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            } else {
                if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            }

            if ((__restartOffset > 0) && !restart(__restartOffset)) {
                return null;
            }

            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
                return null;
            }

            // For now, let's just use the data timeout value for waiting for
            // the data connection.  It may be desirable to let this be a
            // separately configurable value.  In any case, we really want
            // to allow preventing the accept from blocking indefinitely.
            if (__dataTimeout >= 0) {
                server.setSoTimeout(__dataTimeout);
            }
            socket = server.accept();

            // Ensure the timeout is set before any commands are issued on the new socket
            if (__dataTimeout >= 0) {
                socket.setSoTimeout(__dataTimeout);
            }
            if (__receiveDataSocketBufferSize > 0) {
                socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
            }
            if (__sendDataSocketBufferSize > 0) {
                socket.setSendBufferSize(__sendDataSocketBufferSize);
            }
        } finally {
            server.close();
        }
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        // Try EPSV command first on IPv6 - and IPv4 if enabled.
        // When using IPv4 with NAT it has the advantage
        // to work with more rare configurations.
        // E.g. if FTP server has a static PASV address (external network)
        // and the client is coming from another internal network.
        // In that case the data connection after PASV command would fail,
        // while EPSV would make the client succeed by taking just the port.
        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
            _parseExtendedPassiveModeReply(_replyLines.get(0));
        } else {
            if (isInet6Address) {
                return null; // Must use EPSV for IPV6
            }
            // If EPSV failed on IPV4, revert to PASV
            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
                return null;
            }
            _parsePassiveModeReply(_replyLines.get(0));
        }

        socket = _socketFactory_.createSocket();
        if (__receiveDataSocketBufferSize > 0) {
            socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
        }
        if (__sendDataSocketBufferSize > 0) {
            socket.setSendBufferSize(__sendDataSocketBufferSize);
        }
        if (__passiveLocalHost != null) {
            socket.bind(new InetSocketAddress(__passiveLocalHost, 0));
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0) {
            socket.setSoTimeout(__dataTimeout);
        }

        socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();

        throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress()
                + " is not same as server " + getRemoteAddress().getHostAddress());
    }

    return socket;
}

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

/**
 * Reinitialize the FTP session.  Not all FTP servers support this
 * command, which issues the FTP REIN command.
 * <p>// w w  w  .  jav a 2s .c o m
 * @return True if successfully completed, false if not.
 * @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.
 */
boolean reinitialize() throws IOException {
    rein();

    if (FTPReply.isPositiveCompletion(_replyCode)
            || (FTPReply.isPositivePreliminary(_replyCode) && FTPReply.isPositiveCompletion(getReply()))) {

        __initDefaults();

        return true;
    }

    return false;
}

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

/**
 * Initiate a server to server file transfer.  This method tells the
 * server to which the client is connected to retrieve a given file from
 * the other server.//  ww  w. j a va2 s  .c om
 * <p>
 * @param filename  The name of the file to retrieve.
 * @return True if successfully completed, false if not.
 * @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 boolean remoteRetrieve(String filename) throws IOException {
    if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE
            || __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE) {
        return FTPReply.isPositivePreliminary(retr(filename));
    }
    return false;
}

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

/**
 * Initiate a server to server file transfer.  This method tells the
 * server to which the client is connected to store a file on
 * the other server using the given filename.  The other server must
 * have had a <code> remoteRetrieve </code> issued to it by another
 * FTPClient.//from   www. j  a  v a 2s. co m
 * <p>
 * @param filename  The name to call the file that is to be stored.
 * @return True if successfully completed, false if not.
 * @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 boolean remoteStore(String filename) throws IOException {
    if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE
            || __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE) {
        return FTPReply.isPositivePreliminary(stor(filename));
    }
    return false;
}

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

/**
 * Initiate a server to server file transfer.  This method tells the
 * server to which the client is connected to store a file on
 * the other server using a unique filename based on the given filename.
 * The other server must have had a <code> remoteRetrieve </code> issued
 * to it by another FTPClient.//from   w  w  w.  j ava 2s. co  m
 * <p>
 * @param filename  The name on which to base the filename of the file
 *                  that is to be stored.
 * @return True if successfully completed, false if not.
 * @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 boolean remoteStoreUnique(String filename) throws IOException {
    if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE
            || __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE) {
        return FTPReply.isPositivePreliminary(stou(filename));
    }
    return false;
}

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

/**
 * Initiate a server to server file transfer.  This method tells the
 * server to which the client is connected to store a file on
 * the other server using a unique filename.
 * The other server must have had a <code> remoteRetrieve </code> issued
 * to it by another FTPClient.  Many FTP servers require that a base
 * filename be given from which the unique filename can be derived.  For
 * those servers use the other version of <code> remoteStoreUnique</code>
 * <p>//from w ww. j a v a2  s .co m
 * @return True if successfully completed, false if not.
 * @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 boolean remoteStoreUnique() throws IOException {
    if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE
            || __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE) {
        return FTPReply.isPositivePreliminary(stou());
    }
    return false;
}

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

/**
 * Initiate a server to server file transfer.  This method tells the
 * server to which the client is connected to append to a given file on
 * the other server.  The other server must have had a
 * <code> remoteRetrieve </code> issued to it by another FTPClient.
 * <p>/*from   w ww  .j av  a 2 s  .  c om*/
 * @param filename  The name of the file to be appended to, or if the
 *        file does not exist, the name to call the file being stored.
 * <p>
 * @return True if successfully completed, false if not.
 * @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 boolean remoteAppend(String filename) throws IOException {
    if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE
            || __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE) {
        return FTPReply.isPositivePreliminary(appe(filename));
    }
    return false;
}