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

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

Introduction

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

Prototype

public int getReplyCode() 

Source Link

Document

Returns the integer value of the reply code of the last FTP reply.

Usage

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.FtpDownloadAdapter.java

/**
 * Establishes connection to the FTP server or throws exceptions if any problems occur.
 * //from   ww  w.j  a  v a 2 s  . c  o m
 * @param ftpClient
 *            client instance to operate on.
 * @throws DownloadAdapterException
 *             should any problems occur.
 */
private void connectToFtp(FTPClient ftpClient) throws DownloadAdapterException {
    try {
        ftpClient.connect(connectionInfo.getHost(), connectionInfo.getPort());
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            throw new DownloadAdapterException(
                    "Unable to establish connection to the server, server refused connection.");
        }
    } catch (IOException e) {
        throw new DownloadAdapterException("Exception while trying to establish connection to the server.", e);
    }
}

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.FtpDownloadAdapter.java

/**
 * Downloads resource from the FTP server or throws exceptions if any problesmw ith download occur.
 * //  www  .  j  a  v  a2s. c om
 * @param ftpClient
 *            client instance to operate on.
 * @param cachedFilePath
 *            path to the download destination in cache.
 * @param remotePath
 *            path to the resource on the server.
 * @throws DownloadAdapterException
 *             should any problems occur.
 */
private void downloadFromFtp(FTPClient ftpClient, String cachedFilePath, String remotePath)
        throws DownloadAdapterException {
    OutputStream output = null;
    try {
        output = new FileOutputStream(cachedFilePath);
        if (!ftpClient.retrieveFile(remotePath, output)) {
            throw new DownloadAdapterException(
                    "Unable to download file, ftp server returned response code: " + ftpClient.getReplyCode());
        }
    } catch (FileNotFoundException e) {
        throw new WrdzRuntimeException("Unable to create new file in cache.", e);
    } catch (IOException e) {
        throw new DownloadAdapterException("Exception while downloading the file - Unable to download ", e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                throw new WrdzRuntimeException("Unable to close open output stream.", e);
            }
        }
    }
}

From source file:rapture.ftp.common.FTPConnection.java

@Override
public boolean connectAndLogin() {
    if (isLocal()) {
        log.info("In local mode - not connecting");
        return true;
    }/*  w ww  .  j  a v  a 2s  . c  o  m*/
    return FTPService.runWithRetry("Could not login to " + config.getAddress() + " as " + config.getLoginId(),
            this, false, new FTPAction<Boolean>() {
                @Override
                public Boolean run(int attemptNum) throws IOException {
                    FTPClient ftpClient = getFtpClient();
                    log.debug(String.format("Connecting to %s. Attempt %s of %s", config.getAddress(),
                            1 + attemptNum, config.getRetryCount()));
                    try {
                        ftpClient.connect(config.getAddress());
                    } catch (UnknownHostException e) {
                        log.info(ExceptionToString.summary(e));
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Unknown host " + config.getAddress());
                    }
                    int reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        log.debug("Got non-positive reply of " + reply);
                        logoffAndDisconnect();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not connect to: " + config.getAddress());
                    }
                    log.debug("Logging in user: " + config.getLoginId());
                    if (!ftpClient.login(config.getLoginId(), config.getPassword())) {
                        log.info("Could not login to " + config.getAddress() + " as " + config.getLoginId());
                        ftpClient.logout();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not login to " + config.getAddress() + " as " + config.getLoginId());
                    }
                    isLoggedIn = true;
                    log.debug("Entering local passive mode");
                    ftpClient.enterLocalPassiveMode();
                    log.info("Connected and logged in to: " + config.getAddress());
                    ftpClient.setSoTimeout(1000 * config.getTimeout());
                    return true;
                }
            });
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public <X> X connect(URI remoteHostUri, String username, String password, String remoteHost, int remotePort,
        String options) throws Exception {
    long startTime = new Date().getTime();
    X abstractConnection = null;//from   w w w. j  a va2 s .  c o m
    FTPClient ftpConnection = new FTPClient();
    try {
        remotePort = (remotePort == -1) ? (int) 21 : remotePort;
        ftpConnection.setDefaultTimeout(60 * 1000);
        ftpConnection.setRemoteVerificationEnabled(false);
        // FTPconnection.setSoTimeout( 60 * 1000 );
        // FTPconnection.setDataTimeout( 60 * 1000 );
        ftpConnection.connect(remoteHost, remotePort);
        ftpConnection.login(username, password);
        ftpConnection.enterLocalPassiveMode();
        ftpConnection.setFileType(FTPClient.BINARY_FILE_TYPE);
        // FTPconnection.setControlKeepAliveTimeout(300);
        // Check reply code for success
        int reply = ftpConnection.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpConnection.disconnect();
            throw new Exception(ErrorMessages.err_FTC005);
        } else {
            abstractConnection = (X) ftpConnection;
        }
    } catch (IOException se) {
        if (ftpConnection.isConnected()) {
            try {
                ftpConnection.disconnect();
            } catch (IOException ioe) {
                throw new Exception(ErrorMessages.err_FTC005);
            }
        }
    }
    log.info("The FTP sub-module connected to '" + remoteHostUri + "' in " + (new Date().getTime() - startTime)
            + " ms.");
    return abstractConnection;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

private static List<Object> _checkResourcePath(FTPClient connection, String remoteResourcePath,
        String actionName, boolean isDirectory) throws Exception {
    FTPFile[] resources = null;/* ww  w.  java2 s.  co m*/
    List<Object> connectionObject = new LinkedList<Object>();

    boolean remoteDirectoryExists = connection.changeWorkingDirectory(remoteResourcePath);

    if (isDirectory) {
        int returnCode = connection.getReplyCode();

        // check if the remote directory exists
        if (returnCode == 550) {
            throw new Exception(ErrorMessages.err_FTC003);
        }
    }

    connectionObject.add(remoteDirectoryExists);

    // check if the user has rights as to the resource
    resources = connection.listFiles(remoteResourcePath);

    //      if (!actionName.equals("list-resources") && !remoteDirectoryExists) {
    //         // System.out.println("permissions; "
    //         // + resources[0].hasPermission(FTPFile.USER_ACCESS,
    //         // FTPFile.READ_PERMISSION));
    //      }

    // if (!remoteDirectoryExists) {
    // FTPconnection.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
    // is = FTPconnection.retrieveFileStream(remoteResourcePath);
    // if (is == null || resources.length == 0) {
    // throw new
    // Exception(ErrorMessages.err_FTC004);
    // }
    // }

    connectionObject.add(resources);

    return connectionObject;
}

From source file:se.sll.reimbursementadapter.mule.NonDeletingFtpMessageReceiver.java

@Override
protected void postProcess(FTPClient client, FTPFile file, MuleMessage message) throws Exception {
    if (connector.isStreaming()) {
        if (!client.completePendingCommand()) {
            throw new IOException(MessageFormat.format(
                    "Failed to complete a pending command. Retrieveing file {0}. Ftp error: {1}",
                    file.getName(), client.getReplyCode()));
        }/*from   w w  w.  ja  v a2  s.c  om*/
    }
}

From source file:se.vgregion.webbisar.helpers.FileHandler.java

private FTPClient connect() throws FTPException {
    try {// www.  ja va2s  .c  om
        FTPClient ftp = new FTPClient();
        ftp.connect(host, port);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        }
        ftp.login(userName, password);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        return ftp;
    } catch (SocketException e) {
        throw new FTPException("Failed to connect to server", e);
    } catch (IOException e) {
        throw new FTPException("Failed to connect to server", e);
    }
}

From source file:simplehttpdb.net.FTPHelper.java

/**
 * returns an FTP connection to the given server
 * if login fails null will be returned/*  w  w  w .j  ava 2  s .c o  m*/
 * @param ftpServer
 * @param ftpUser
 * @param ftpPass
 * @return
 * @throws SocketException
 * @throws IOException
 */
public FTPClient getFTPConnection(String ftpServer, String ftpUser, String ftpPass)
        throws SocketException, IOException {

    FTPClient ftp = new FTPClient();

    int reply;

    ftp.connect(ftpServer);
    Logger.getLogger(FTPHelper.class.getName()).log(Level.INFO,
            "Connected to " + ftpServer + " --> " + ftp.getReplyString());

    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.disconnect();
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "FTP server refused connection.");
        return null;
    }
    if (ftp.login(ftpUser, ftpPass)) {
        return ftp;
    } //else
    return null;
}

From source file:smilehouse.opensyncro.defaultcomponents.ftp.FTPDestination.java

public void take(String data, DestinationInfo info, MessageLogger logger)
        throws FailTransferException, AbortTransferException {

    FTPClient ftp = new FTPClient();

    try {//from  www .  j a  v a 2s.c  om
        // -----------------
        // Try to connect...
        // -----------------
        String host = this.data.getAttribute(HOST_ATTR);
        int port = -1;
        String portStr = this.data.getAttribute(PORT_ATTR);
        if (portStr != null && portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException nfe) {
                logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        }
        int reply;

        try {
            if (port != -1) {
                ftp.connect(host, port);
            } else {
                ftp.connect(host);
            }
        } catch (SocketException e) {
            logger.logMessage("SocketException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        } catch (IOException e) {
            logger.logMessage("IOException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                /**
                 * ftp.disconnect() is called only as additional clean-up here, so we choose to
                 * ignore possible exceptions
                 */
            }
            logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------
        // Then log in
        // -----------

        try {
            if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) {
                logger.logMessage("Could not log in, check your username and password settings.", this,
                        MessageLogger.ERROR);
                ftp.logout();

                PipeComponentUtils.failTransfer();
            }
        } catch (IOException e) {
            logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // Use passive mode
        ftp.enterLocalPassiveMode();

        // -----------------
        // ASCII or binary ?
        // -----------------
        boolean fileTypeSetOk = false;

        try {
            switch (getFileType()) {
            case FILE_TYPE_ASCII:
                fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE);
                break;
            case FILE_TYPE_BINARY:
                fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            }
            if (!fileTypeSetOk) {
                logger.logMessage("Could not set file type: " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
            }
        } catch (IOException e) {
            logger.logMessage("IOException while setting file transfer type parameter", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -------------
        // Send the data
        // -------------
        String fileName = getFileName();
        logger.logMessage("Storing file: " + fileName, this, MessageLogger.DEBUG);
        String charSet = this.data.getAttribute(CHARSET_ATTR);
        if (charSet == null || charSet.length() == 0)
            charSet = DEFAULT_CHARSET;
        InputStream dataStream = null;
        try {
            dataStream = new ByteArrayInputStream(data.getBytes(charSet));
        } catch (UnsupportedEncodingException e1) {

            logger.logMessage(charSet + " charset not supported", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
        try {
            if (!ftp.storeFile(fileName, dataStream)) {
                logger.logMessage("Could not store file '" + fileName + "': " + ftp.getReplyString(), this,
                        MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        } catch (IOException e) {
            logger.logMessage("IOException while uploading the file to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
}

From source file:smilehouse.opensyncro.defaultcomponents.ftp.FTPSource.java

public String[] give(SourceInfo info, MessageLogger logger)
        throws FailTransferException, AbortTransferException {

    // This component does not support iteration, so we output all our data
    // once (and only once)
    if (this.allDataOutput == true)
        return null;
    else/* w w w  .  ja v a 2 s .  c  om*/
        this.allDataOutput = true;

    String[] dataArray = new String[1];
    FTPClient ftp = new FTPClient();

    try {
        // -----------------
        // Try to connect...
        // -----------------
        String host = this.data.getAttribute(HOST_ATTR);
        int port = -1;
        String portStr = this.data.getAttribute(PORT_ATTR);
        if (portStr != null && portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException nfe) {
                logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        }
        int reply;

        try {

            if (port != -1) {
                ftp.connect(host, port);
            } else {
                ftp.connect(host);
            }

        } catch (SocketException e) {
            logger.logMessage("SocketException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        } catch (IOException e) {
            logger.logMessage("IOException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                /**
                 * ftp.disconnect() is called only as additional clean-up here, so we choose to
                 * ignore possible exceptions
                 */
            }
            logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------
        // Then log in
        // -----------
        try {
            if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) {
                logger.logMessage("Could not log in, check your username and password settings.", this,
                        MessageLogger.ERROR);
                ftp.logout();

                PipeComponentUtils.failTransfer();
            }

        } catch (IOException e) {
            logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // Use passive mode
        ftp.enterLocalPassiveMode();

        // -----------------
        // ASCII or binary ?
        // -----------------
        boolean fileTypeSetOk = false;
        try {
            switch (getFileType()) {
            case FILE_TYPE_ASCII:
                fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE);
                break;
            case FILE_TYPE_BINARY:
                fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            }
            if (!fileTypeSetOk) {
                logger.logMessage("Could not set file type: " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
            }
        } catch (IOException e) {
            logger.logMessage("IOException while setting file transfer type parameter", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------------
        // Retrieve the data
        // -----------------
        String fileName = getFileName(logger);
        logger.logMessage("Retrieving file: " + fileName, this, MessageLogger.DEBUG);
        OutputStream dataStream = new ByteArrayOutputStream();
        try {
            if (!ftp.retrieveFile(fileName, dataStream)) {
                logger.logMessage("Could not retrieve file '" + fileName + "': " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
                PipeComponentUtils.abortTransfer();
            }
            String charSet = this.data.getAttribute(CHARSET_ATTR);
            if (charSet == null || charSet.length() == 0)
                charSet = DEFAULT_CHARSET;
            dataArray[0] = ((ByteArrayOutputStream) dataStream).toString(charSet);
        } catch (IOException e) {
            logger.logMessage("IOException while downloading file from FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
    return dataArray;
}