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:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/*from w w  w  .  ja  v a  2  s .  c o m*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*  w  w w  .j a v a  2 s  . com*/
 * 
 * @author covito
 * @param path
 * @return
 */
@Override
public int deleteFile(String path) {
    init();
    try {
        FTPClient client = getConnect();
        if (!dealDocPath(client, path, false)) {
            return 0;
        }
        boolean sucess = client.deleteFile(getFilePath(path));
        if (!sucess) {
            log.warn(client.getReplyString());
        }
        sucess = client.deleteFile(getMetaPath(path));
        if (!sucess) {
            log.warn(client.getReplyString());
        }
        return 0;
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new FileServiceException(e);
    }
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}//www  .  j av a  2  s.  co  m
 * 
 * @author covito
 * @param path
 * @return
 */
@Override
public FileMeta getFileInfo(String path) {
    init();
    if (path == null || path.length() == 0) {
        return null;
    }
    FileMeta file = new FileMeta();
    FTPClient client = getConnect();
    if (!dealDocPath(client, path, false)) {
        throw new FileServiceException("path not exist!");
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        boolean sucess = client.retrieveFile(getMetaPath(path), bos);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException("path is not exist!");
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new FileServiceException("path is not exist!");
    }
    JSONObject json = JSON.parseObject(bos.toString());

    Map<String, String> meta = JSON.parseObject(json.toString(), Map.class);
    file.setMeta(meta);
    file.setFileName(meta.get(FileMeta.KEY_FILENAME));

    try {
        FTPFile ftpfile = client.mlistFile(rootWorkingDirectory + "/" + path);
        file.setCreateTime(new Date(ftpfile.getTimestamp().getTimeInMillis()));
        file.setFileSize(ftpfile.getSize());
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return file;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}//from   w  ww . j a va  2  s.c  o  m
 * 
 * @author covito
 * @param path
 * @param os
 */
@Override
public void outputFile(String path, OutputStream os) {
    init();
    if (os == null) {
        throw new FileServiceException("OutputStream is null");
    }
    FTPClient client = getConnect();
    try {
        if (!dealDocPath(client, path, false)) {
            throw new FileServiceException("path not exist!");
        }
        boolean sucess = client.retrieveFile(getFilePath(path), os);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*w ww .  j  ava2 s .c om*/
 * 
 * @author covito
 * @param is
 * @param fileName
 * @param meta
 * @return
 */
@Override
public String upload(InputStream is, String fileName, Map<String, String> meta) {
    init();
    if (null == meta) {
        meta = new HashMap<String, String>();
    }
    if (fileName == null || fileName.length() == 0) {
        fileName = "Unkown";
    }

    meta.put(FileMeta.KEY_FILENAME, fileName);
    String path = generatePath(fileName);

    FTPClient client = getConnect();

    try {
        if (!dealDocPath(client, path, true)) {
            throw new FileServiceException(client.getReplyString());
        }
        boolean sucess = client.storeFile(getFilePath(path), is);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Map<String, Object> m = new HashMap<String, Object>();
    m.putAll(meta);
    JSONObject josn = new JSONObject(m);

    ByteArrayInputStream bis = new ByteArrayInputStream(josn.toString().getBytes());
    try {
        boolean sucess = client.storeFile(getMetaPath(path), bis);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*  w  w w  . ja  va  2  s.c  om*/
 * 
 * @author covito
 * @param path
 * @param is
 */
@Override
public void append(String path, InputStream is) {
    init();
    if (is == null) {
        throw new FileServiceException("InputStream is null");
    }
    FTPClient client = getConnect();
    try {
        if (!dealDocPath(client, path, false)) {
            throw new FileServiceException("path not exist!");
        }
        boolean sucess = client.appendFile(getFilePath(path), is);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w.  j  a v a  2 s  . c o m*/
 * 
 * @author covito
 * @param path
 * @param meta
 */
@Override
public void updataMeta(String path, Map<String, String> meta) {
    init();
    FTPClient client = getConnect();
    if (!dealDocPath(client, path, false)) {
        throw new FileServiceException("path not exist!");
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        boolean sucess = client.retrieveFile(getMetaPath(path), bos);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new FileServiceException("path not exist!");
    }
    JSONObject json = JSON.parseObject(bos.toString());
    json.putAll(meta);
    ByteArrayInputStream bis = new ByteArrayInputStream(json.toString().getBytes());
    try {
        boolean sucess = client.storeFile(getMetaPath(path), bis);
        if (!sucess) {
            log.error(client.getReplyString());
            throw new FileServiceException(client.getReplyString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {/*from w w w.j  a v a  2 s .co  m*/
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}

From source file:org.gogpsproject.parser.rinex.RinexNavigation.java

private RinexNavigationParser getFromFTP(String url) throws IOException {
    RinexNavigationParser rnp = null;/*from  www  . ja  va 2s  .  c  o  m*/

    String origurl = url;
    if (negativeChache.containsKey(url)) {
        if (System.currentTimeMillis() - negativeChache.get(url).getTime() < 60 * 60 * 1000) {
            throw new FileNotFoundException("cached answer");
        } else {
            negativeChache.remove(url);
        }
    }

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File rnf = new File(RNP_CACHE, filename);

    if (!rnf.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                return null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                negativeChache.put(origurl, new Date());
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            rnp = new RinexNavigationParser(uis, rnf);
            rnp.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + rnf);
        rnp = new RinexNavigationParser(rnf);
        rnp.init();
    }
    return rnp;
}

From source file:org.gogpsproject.parser.sp3.SP3Navigation.java

private SP3Parser getFromFTP(String url) throws IOException {
    SP3Parser sp3p = null;//  www . j a v  a 2s  .c o m

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File sp3f = new File(SP3_CACHE, filename);

    if (!sp3f.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                return null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            sp3p = new SP3Parser(uis, sp3f);
            sp3p.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + sp3f);
        sp3p = new SP3Parser(sp3f);
        sp3p.init();
    }
    return sp3p;
}