Example usage for org.apache.commons.net.ftp FTPConnectionClosedException getMessage

List of usage examples for org.apache.commons.net.ftp FTPConnectionClosedException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.gdbocom.util.SendFileinFTP.java

/**
 * ,?FTP?BINASCII?/*from  ww w . ja  va 2 s  .  c  om*/
 * @param local ??(?,"/"?),??
 * @param remotePath ()
 * @param remote ??(??),??
 * @param filetype ?,BINASCII??
 * @param ftptype FTP?,??
 * @return ??
 */
public boolean putFile(String local, String remotePath, String remote, int filetype, int ftptype)
        throws IOException {

    //bin?,ASCII?
    if (filetype == SendFileinFTP.BINARY_FILE_TYPE) {
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        gzLog.Write("BIN?");
    } else if (filetype == SendFileinFTP.ASCII_FILE_TYPE) {
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        gzLog.Write("ASCII?");
    } else {
        gzLog.Write("");
        return false;
    }

    // FTP??,FTP?
    if (ftptype == SendFileinFTP.ActiveMode) {
        ftp.enterLocalActiveMode();
        gzLog.Write("FTP?");
    } else if (ftptype == SendFileinFTP.PassiveMode) {
        ftp.enterLocalPassiveMode();
        gzLog.Write("FTP?");
    } else {
        ftp.enterLocalPassiveMode();
        gzLog.Write("FTP?,FTP?");
        return false;
    }

    //?
    ftp.changeWorkingDirectory(remotePath);

    //FTP?
    try {
        InputStream input;
        input = new FileInputStream(local);

        if (ftp.storeFile(remote, input)) {
            gzLog.Write("" + remote + "?,?:/" + remotePath);
        } else {
            gzLog.Write("");
        }
        input.close();

    } catch (FTPConnectionClosedException e) {
        gzLog.Write("Server closed connection.");
        gzLog.Write(e.getMessage());
        return false;
    }
    return true;
}

From source file:com.isencia.message.ftp.FtpReceiverChannel.java

/**
 * @see ISenderChannel#close()// w  ww . ja v a2 s .com
 */
public void close() throws ChannelException {
    if (logger.isTraceEnabled())
        logger.trace("");

    if (isOpen()) {
        super.close();
    }

    //First logout, then disconnect (disconnect also closes the outputstream)
    try {
        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        throw new ChannelException("Server closed connection.");
    } catch (IOException e) {
        throw new ChannelException(e.getMessage());
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    if (logger.isTraceEnabled())
        logger.trace("exit");
}

From source file:ch.sdi.core.impl.ftp.FtpExecutor.java

/**
 * @throws SdiException//from www.ja v  a  2 s . c om
 */
public void logoutAndDisconnect() throws SdiException {
    if (myFtp == null) {
        myLog.debug("FTP not yet initilized. No logout");
        return;
    } // if myFtp == null

    if (!myFtp.isConnected()) {
        myLog.debug("FTP not connected. No logout");
        return;
    }

    try {
        myFtp.logout();
    } catch (FTPConnectionClosedException e) {
        myLog.warn("Problems FTP logout: " + e.getMessage());
    } catch (IOException e) {
        myLog.warn("Problems FTP logout: " + e.getMessage());
    } finally {

        if (myFtp.isConnected()) {
            try {
                myFtp.disconnect();
            } catch (IOException f) {
                myLog.warn("Problems FTP disconnect: " + f.getMessage());
            }
        }
    }
}

From source file:org.apache.nutch.protocol.ftp.Client.java

/**
 * retrieve list reply for path/*from   www .j a  v  a2s .c  o m*/
 * 
 * @param path
 * @param entries
 * @param limit
 * @param parser
 * @throws IOException
 * @throws FtpExceptionCanNotHaveDataConnection
 * @throws FtpExceptionUnknownForcedDataClose
 * @throws FtpExceptionControlClosedByForcedDataClose
 */
public void retrieveList(String path, List<FTPFile> entries, int limit, FTPFileEntryParser parser)
        throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose,
        FtpExceptionControlClosedByForcedDataClose {
    Socket socket = __openPassiveDataConnection(FTPCommand.LIST, path);

    if (socket == null)
        throw new FtpExceptionCanNotHaveDataConnection("LIST " + ((path == null) ? "" : path));

    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    // force-close data channel socket, when download limit is reached
    // boolean mandatory_close = false;

    // List entries = new LinkedList();
    int count = 0;
    String line = parser.readNextEntry(reader);
    while (line != null) {
        FTPFile ftpFile = parser.parseFTPEntry(line);
        // skip non-formatted lines
        if (ftpFile == null) {
            line = parser.readNextEntry(reader);
            continue;
        }
        entries.add(ftpFile);
        count += line.length();
        // impose download limit if limit >= 0, otherwise no limit
        // here, cut off is up to the line when total bytes is just over limit
        if (limit >= 0 && count > limit) {
            // mandatory_close = true;
            break;
        }
        line = parser.readNextEntry(reader);
    }

    // if (mandatory_close)
    // you always close here, no matter mandatory_close or not.
    // however different ftp servers respond differently, see below.
    socket.close();

    // scenarios:
    // (1) mandatory_close is false, download limit not reached
    // no special care here
    // (2) mandatory_close is true, download limit is reached
    // different servers have different reply codes:

    try {
        int reply = getReply();
        if (!_notBadReply(reply))
            throw new FtpExceptionUnknownForcedDataClose(getReplyString());
    } catch (FTPConnectionClosedException e) {
        // some ftp servers will close control channel if data channel socket
        // is closed by our end before all data has been read out. Check:
        // tux414.q-tam.hp.com FTP server (hp.com version whp02)
        // so must catch FTPConnectionClosedException thrown by getReply() above
        // disconnect();
        throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
    }

}

From source file:org.apache.nutch.protocol.ftp.Client.java

/**
 * retrieve file for path/*from ww  w  .  j a v a  2  s  .  c  om*/
 * 
 * @param path
 * @param os
 * @param limit
 * @throws IOException
 * @throws FtpExceptionCanNotHaveDataConnection
 * @throws FtpExceptionUnknownForcedDataClose
 * @throws FtpExceptionControlClosedByForcedDataClose
 */
public void retrieveFile(String path, OutputStream os, int limit)
        throws IOException, FtpExceptionCanNotHaveDataConnection, FtpExceptionUnknownForcedDataClose,
        FtpExceptionControlClosedByForcedDataClose {

    Socket socket = __openPassiveDataConnection(FTPCommand.RETR, path);

    if (socket == null)
        throw new FtpExceptionCanNotHaveDataConnection("RETR " + ((path == null) ? "" : path));

    InputStream input = socket.getInputStream();

    // 20040318, xing, treat everything as BINARY_FILE_TYPE for now
    // do we ever need ASCII_FILE_TYPE?
    // if (__fileType == ASCII_FILE_TYPE)
    // input = new FromNetASCIIInputStream(input);

    // fixme, should we instruct server here for binary file type?

    // force-close data channel socket
    // boolean mandatory_close = false;

    int len;
    int count = 0;
    byte[] buf = new byte[org.apache.commons.net.io.Util.DEFAULT_COPY_BUFFER_SIZE];
    while ((len = input.read(buf, 0, buf.length)) != -1) {
        count += len;
        // impose download limit if limit >= 0, otherwise no limit
        // here, cut off is exactly of limit bytes
        if (limit >= 0 && count > limit) {
            os.write(buf, 0, len - (count - limit));
            // mandatory_close = true;
            break;
        }
        os.write(buf, 0, len);
        os.flush();
    }

    // if (mandatory_close)
    // you always close here, no matter mandatory_close or not.
    // however different ftp servers respond differently, see below.
    socket.close();

    // scenarios:
    // (1) mandatory_close is false, download limit not reached
    // no special care here
    // (2) mandatory_close is true, download limit is reached
    // different servers have different reply codes:

    // do not need this
    // sendCommand("ABOR");

    try {
        int reply = getReply();
        if (!_notBadReply(reply))
            throw new FtpExceptionUnknownForcedDataClose(getReplyString());
    } catch (FTPConnectionClosedException e) {
        // some ftp servers will close control channel if data channel socket
        // is closed by our end before all data has been read out. Check:
        // tux414.q-tam.hp.com FTP server (hp.com version whp02)
        // so must catch FTPConnectionClosedException thrown by getReply() above
        // disconnect();
        throw new FtpExceptionControlClosedByForcedDataClose(e.getMessage());
    }

}

From source file:org.wso2.carbon.connector.FileFtpOverProxy.java

/**
 * Send file FTP over Proxy.//from w  ww.  j  a  va  2s.  c  o m
 *
 * @param proxyHost      Name of the proxy host.
 * @param proxyPort      Proxy port number.
 * @param proxyUsername  User name of the proxy.
 * @param proxyPassword  Password of the proxy.
 * @param ftpServer      FTP server.
 * @param ftpPort        Port number of FTP.
 * @param ftpUsername    User name of the FTP.
 * @param ftpPassword    Password of the FTP.
 * @param messageContext he message context that is generated for processing the ftpOverHttp method.
 * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server.
 */
public boolean ftpOverHttp(String proxyHost, String proxyPort, String proxyUsername, String proxyPassword,
        String ftpServer, String ftpPort, String ftpUsername, String ftpPassword,
        MessageContext messageContext) {
    String keepAliveTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.KEEP_ALIVE_TIMEOUT);
    String controlKeepAliveReplyTimeout = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT);
    String targetPath = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_PATH);
    String targetFile = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.TARGET_FILE);
    String binaryTransfer = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.BINARY_TRANSFER);
    String localActive = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.LOCAL_ACTIVE);
    boolean resultStatus = false;
    InputStream inputStream = null;

    final FTPClient ftp;
    if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)
            && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) {
        proxyHost = proxyHost.trim();
        proxyPort = proxyPort.trim();
        proxyUsername = proxyUsername.trim();
        proxyPassword = proxyPassword.trim();
        ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword);
    } else {
        ftp = new FTPClient();
    }
    //Set the time to wait between sending control connection keep alive messages when
    // processing file upload or download (Zero (or less) disables).
    keepAliveTimeout = keepAliveTimeout.trim();
    if (StringUtils.isNotEmpty(keepAliveTimeout)) {
        ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout.trim()));
    }
    //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.)
    if (StringUtils.isNotEmpty(controlKeepAliveReplyTimeout)) {
        ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout.trim()));
    }
    try {
        int reply;
        ftpPort = ftpPort.trim();
        int IntFtpPort = Integer.parseInt(ftpPort);
        if (IntFtpPort > 0) {
            ftp.connect(ftpServer, IntFtpPort);
        } else {
            ftpServer = ftpServer.trim();
            ftp.connect(ftpServer);
        }
        if (log.isDebugEnabled()) {
            log.debug(
                    " Connected to " + ftpServer + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort()));
        }
        // After connection attempt, should check the reply code to verify success.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP ftpServer refused connection.");
        }
        if (ftp.login(ftpUsername, ftpPassword)) {
            if (StringUtils.isNotEmpty(binaryTransfer)) {
                if (Boolean.valueOf(binaryTransfer.trim())) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                } else {
                    // in theory this should not be necessary as servers should default to ASCII
                    // but they don't all do so - see NET-500
                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                }
            } else {
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }
            // Use passive mode as default because most of us are behind firewalls these days.
            if (StringUtils.isNotEmpty(localActive)) {
                if (Boolean.valueOf(localActive.trim())) {
                    ftp.enterLocalActiveMode();
                } else {
                    ftp.enterLocalPassiveMode();
                }
            } else {
                ftp.enterLocalPassiveMode();
            }
            inputStream = new ByteArrayInputStream(
                    messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes());
            if (StringUtils.isNotEmpty(targetPath)) {
                ftp.changeWorkingDirectory(targetPath);
                ftp.storeFile(targetFile, inputStream);
                if (log.isDebugEnabled()) {
                    log.debug("Successfully FTP transfered the File");
                }
            }
            // check that control connection is working
            if (log.isDebugEnabled()) {
                log.debug("The code received from the server." + ftp.noop());
            }
            resultStatus = true;
        } else {
            ftp.logout();
            handleException("Error while login ftp server.", messageContext);
        }
    } catch (FTPConnectionClosedException e) {
        // log.error("Server closed connection " + e.getMessage(), e);
        handleException("Server closed connection: " + e.getMessage(), e, messageContext);
    } catch (IOException e) {
        //log.error("Error occurred while uploading:" + e.getMessage(), e);
        handleException("Could not connect to FTP ftpServer: " + e.getMessage(), e, messageContext);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
                ftp.logout();
            } catch (IOException f) {
                log.error("Error while disconnecting/logging out ftp server");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException f) {
                log.error("Error while closing inputStream");
            }
        }
    }
    return resultStatus;
}