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:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

private FTPClient connect() {
    final FTPClient connection = new FTPClient();
    try {//from  w w w.j a va 2  s.co m
        connection.setAutodetectUTF8(true);
        connection.connect(url.getHost(), port);
        connection.enterLocalActiveMode();
        if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) {
            throw new SourceException(
                    String.format("Cannot login as anonymous user, reason %s", connection.getReplyString()));
        }
        if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        connection.enterLocalPassiveMode();
        connection.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (final IOException e) {
        disconnect(connection);
        throw new SourceException(e);
    }
    return connection;
}

From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java

/**
 * /*from www .j  a v a2s  .c  o  m*/
 */
private String retrieveFTP(String aURL) {
    debug("retrieveFTP (" + aURL + ")");

    URL urlObject = null;

    try {
        urlObject = new URL(aURL);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/");
    HoopLink.fManager.createDirectory(downloadPath);

    File translator = new File(urlObject.getFile());

    String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName();

    OutputStream fileStream = null;

    if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    fileStream = HoopLink.fManager.getOutputStreamBinary();

    if (fileStream == null) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    debug("Starting FTP client ...");

    FTPClient ftp = new FTPClient();

    try {
        int reply;

        debug("Connecting ...");

        ftp.connect(urlObject.getHost());

        debug("Connected to " + urlObject.getHost() + ".");
        debug(ftp.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            debug("FTP server refused connection.");
            return (null);
        } else {
            ftp.login("anonymous", "hoop-dev@gmail.com");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                debug("Unable to login to FTP server");
                return (null);
            }

            debug("Logged in");

            boolean rep = true;

            String pathFixed = translator.getParent().replace("\\", "/");

            rep = ftp.changeWorkingDirectory(pathFixed);
            if (rep == false) {
                debug("Unable to change working directory to: " + pathFixed);
                return (null);
            } else {
                debug("Current working directory: " + pathFixed);

                debug("Retrieving file " + urlObject.getFile() + " ...");

                try {
                    rep = ftp.retrieveFile(urlObject.getFile(), fileStream);
                } catch (FTPConnectionClosedException connEx) {
                    debug("Caught: FTPConnectionClosedException");
                    connEx.printStackTrace();
                    return (null);
                } catch (CopyStreamException strEx) {
                    debug("Caught: CopyStreamException");
                    strEx.printStackTrace();
                    return (null);
                } catch (IOException ioEx) {
                    debug("Caught: IOException");
                    ioEx.printStackTrace();
                    return (null);
                }

                debug("File retrieved");
            }

            ftp.logout();
        }
    } catch (IOException e) {
        debug("Error retrieving FTP file");
        e.printStackTrace();
        return (null);
    } finally {
        if (ftp.isConnected()) {
            debug("Closing ftp connection ...");

            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                debug("Exception closing ftp connection");
            }
        }
    }

    debug("Closing local file stream ...");

    try {
        fileStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName));

    return (result);
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public boolean sendFile(String filePath, boolean delete) throws Exception {

    String fileName = filePath;//from   w w  w  .  j av a 2 s . c o m
    int slash = fileName.lastIndexOf("/");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    slash = fileName.lastIndexOf("\\");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    boolean success = true;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(ftpHost, ftpPort);
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(ftpUser, ftpPassword)) {
                if (ftpFolder != null && ftpFolder.trim().length() > 0) {
                    ftp.cwd(ftpFolder);
                    System.out.print("ftp cd: " + ftp.getReplyString());
                }
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
                FileInputStream in = new FileInputStream(filePath);
                success = ftp.storeFile(fileName, in);
                in.close();
                if (delete) {
                    File file = new File(filePath);
                    file.delete();
                }
            } else
                success = false;
        }
    } finally {
        ftp.disconnect();
    }

    return success;
}

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that throws a SocketException
 * on connect().//from  w  ww  .j  a va 2  s. c om
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient socketExMockFtpClient() throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(true);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(true);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(true);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    doThrow(SocketException.class).when(client).connect("ftp.host.com", 21); //$NON-NLS-1$
    return client;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * /*from   w w  w.j  a v a 2s.co m*/
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java

/**
 * FTP????????//from   www .ja  v a 2s  .co m
 * 
 * @param addressText
 * @return FTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        FTPClient client = new FTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (FTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(FTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that does not need an FTP server.
 * /*from   www.j a v  a 2  s .  com*/
 * @param succeedOnLogin 
 *        Specifies if this FTP client mocks its login method by
 *        imitating a successful or a failed login.
 * @param succedOnUploadDownload
 *        Specifies if this FTP client mocks the upload and download
 *        operations by imitating successful or failed operations.   
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient mockFtpClient(boolean succeedOnLogin, boolean succedOnUploadDownload) throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(succeedOnLogin);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    return client;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public InputStream getInputStream(final String remoteFileName, final FlowFile flowFile) throws IOException {
    final FTPClient client = getClient(null);
    InputStream in = client.retrieveFileStream(remoteFileName);
    if (in == null) {
        throw new IOException(client.getReplyString());
    }/*w  w w . j a  v a  2s.c o  m*/
    return in;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public void deleteFile(final String path, final String remoteFileName) throws IOException {
    final FTPClient client = getClient(null);
    if (path != null) {
        setWorkingDirectory(path);//w w  w  .  ja  v a2  s. c om
    }
    if (!client.deleteFile(remoteFileName)) {
        throw new IOException("Failed to remove file " + remoteFileName + " due to " + client.getReplyString());
    }
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public void deleteDirectory(final String remoteDirectoryName) throws IOException {
    final FTPClient client = getClient(null);
    final boolean success = client.removeDirectory(remoteDirectoryName);
    if (!success) {
        throw new IOException(
                "Failed to remove directory " + remoteDirectoryName + " due to " + client.getReplyString());
    }/*from  w ww .  j  a  v a2s. c o m*/
}