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:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class);
    RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response);

    // prepare dynamic variables
    Part masterQualityPart = request.getPart("masterFile");
    String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf";

    // prepare static variables
    String host = "p4.eurixgroup.com";
    int port = 21;
    String username = "pprime";
    String password = "pprime09";

    FTPClient client = new FTPClient();
    try {//from ww w  .j  av  a 2 s.  c  o  m
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                // TODO add behavior if file name is already present in
                // remote ftp folder
                // now OVERWRITES
                if (client.storeFile(targetName, masterQualityPart.getInputStream())) {
                    logger.info("Stored file on remote FTP server " + host + ":" + port);

                    request.setAttribute("masterfileName", targetName);
                } else {
                    logger.error("Unable to store file on remote FTP server");
                }
            } else {
                logger.error("Unable to login on remote FTP server");
            }
        } else {
            logger.error("Unable to connect to remote FTP server");
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.fatal("General exception with FTPClient");
    }

    Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp");
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {//from  w  ww  .ja  va 2s . c  o m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private void deleteChallengeFiles() {
    FTPClient ftp = new FTPClient();
    try {//ww w  . j av  a 2s. c  o  m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.changeWorkingDirectory(".well-known");
        ftp.changeWorkingDirectory("acme-challenge");

        FTPFile[] subFiles = ftp.listFiles();

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    continue;
                } else {
                    ftp.deleteFile(currentFileName);
                }
            }
        }
        ftp.changeToParentDirectory();
        ftp.removeDirectory("acme-challenge");
        ftp.changeToParentDirectory();
        ftp.removeDirectory(".well-known");
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:lucee.runtime.exp.FTPException.java

public FTPException(String action, FTPClient client) {
    super("action [" + action + "] from tag ftp failed", client.getReplyString());
    //setAdditional("ReplyCode",Caster.toDouble(client.getReplyCode()));
    //setAdditional("ReplyMessage",client.getReplyString());
    code = client.getReplyCode();
    msg = client.getReplyString();/*ww  w  . j  a v a2  s .  c  o  m*/
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure.
 * /* w  w w .j  a  va2  s  . c  o  m*/
 * @param sourceDirectoryPath the directory to be uploaded
 * @param destDirName the path on ftp where directory will be uploaded
 * @param numberOfRetryCounter number of attempts to be made for uploading the directory
 * @throws FTPDataUploadException if an error occurs while uploading the file
 * @throws IOException if an error occurs while making the ftp connection
 * @throws SocketException if an error occurs while making the ftp connection
 */
public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData)
        throws FTPDataUploadException, SocketException, IOException {
    boolean isValid = true;
    if (ftpInformation.getSourceDirectoryPath() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DIR);
        throw new FTPDataUploadException(VAR_SOURCE_DIR);
    }
    if (ftpInformation.getDestDirName() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DES);
        throw new FTPDataUploadException(VAR_SOURCE_DES);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String destDirName = ftpInformation.getDestDirName();
        String destinationDirectory = ftpInformation.getUploadBaseDir();
        if (destDirName != null && !destDirName.isEmpty()) {
            String uploadBaseDir = ftpInformation.getUploadBaseDir();
            if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) {
                destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        destDirName);
            } else {
                destinationDirectory = destDirName;
            }

        }
        FileInputStream fis = null;
        try {
            createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(),
                    ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut());

            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Upload...");
            } else {
                LOGGER.info("Invalid Connection to FTP server. Disconnecting Client");
                client.disconnect();
                isValid = false;
                throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client");
            }
            if (isValid) {

                // code changed for keeping the control connection busy.
                client.setControlKeepAliveTimeout(300);
                client.setFileType(FTP.BINARY_FILE_TYPE);
                createFtpDirectoryTree(client, destinationDirectory);
                // client.makeDirectory(destinationDirectory);
                if (deleteExistingFTPData) {
                    deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData);
                }
                File file = new File(ftpInformation.getSourceDirectoryPath());
                if (file.isDirectory()) {
                    String[] fileList = file.list();
                    for (String fileName : fileList) {
                        String inputFile = EphesoftStringUtil
                                .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName);
                        File checkFile = new File(inputFile);
                        if (checkFile.isFile()) {
                            LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName));
                            fis = new FileInputStream(inputFile);
                            try {
                                client.storeFile(fileName, fis);
                            } catch (IOException e) {
                                int retryCounter = ftpInformation.getNumberOfRetryCounter();
                                LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-",
                                        (retryCounter + 1)));
                                if (retryCounter < ftpInformation.getNumberOfRetries()) {
                                    retryCounter = retryCounter + 1;
                                    uploadDirectory(ftpInformation, deleteExistingFTPData);
                                } else {
                                    LOGGER.error("Error in uploading the file to FTP server");
                                }
                            } finally {
                                try {
                                    if (fis != null) {
                                        fis.close();
                                    }
                                } catch (IOException e) {
                                    LOGGER.info(EphesoftStringUtil
                                            .concatenate("Could not close stream for file.", inputFile));
                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("File does not exist..");
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Disconnecting from FTP server....", e);
            }
        }
    }
}

From source file:com.zxy.commons.net.ftp.FtpUtils.java

/**
 * FTP handle/*from  w  ww  . ja va  2 s .  co  m*/
 * 
 * @param <T> return object type
 * @param ftpConfig ftp config
 * @param callback ftp callback
 * @return value
*/
public static <T> T ftpHandle(FtpConfig ftpConfig, FtpCallback<T> callback) {
    FTPClient client = null;
    if (ftpConfig.isFtps() && ftpConfig.getSslContext() != null) {
        client = new FTPSClient(ftpConfig.getSslContext());
    } else if (ftpConfig.isFtps()) {
        client = new FTPSClient();
    } else {
        client = new FTPClient();
    }

    client.configure(ftpConfig.getFtpClientConfig());
    try {
        //            client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        client.connect(ftpConfig.getHost(), ftpConfig.getPort());
        client.setConnectTimeout(ftpConfig.getConnectTimeoutMs());
        client.setControlKeepAliveTimeout(ftpConfig.getKeepAliveTimeoutSeconds());
        if (!Strings.isNullOrEmpty(ftpConfig.getUsername())) {
            client.login(ftpConfig.getUsername(), ftpConfig.getPassword());
        }
        LOGGER.trace("Connected to {}, reply: {}", ftpConfig.getHost(), client.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            throw new NetException("FTP server refused connection.");
        }
        return callback.process(client);
    } catch (Exception e) {
        throw new NetException(e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
            try {
                client.disconnect();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
        }
    }
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * /*from ww w .  java2  s  .c o m*/
 *
 * @param fileName   ??
 * @param path       ftp?
 * @param fileStream ?
 * @return true/false ?
 */
public boolean uploadFile(String fileName, String path, InputStream fileStream) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(path);
        ftpClient.storeFile(fileName, fileStream);
        fileStream.close();
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

From source file:eu.prestoprime.plugin.fprint.FPrintTasks.java

@WfService(name = "fprint_upload", version = "0.8.0")
public void upload(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    logger.debug("Called " + this.getClass().getName());

    // prepare dynamic variables
    String id = dParamsString.get("id");
    String targetName = id + ".webm";
    String fileLocation = null;//w w w . j  ava  2s  .  c  o m

    // prepare static variables
    String host = sParams.get("host");
    int port = Integer.parseInt(sParams.get("port"));
    String username = sParams.get("username");
    String password = sParams.get("password");
    String workdir = sParams.get("workdir");

    // retrieve AIP
    try {
        DIP dip = P4DataManager.getInstance().getDIPByID(id);
        List<String> fLocatList = dip.getAVMaterial("video/webm", "FILE");
        fileLocation = fLocatList.get(0);
    } catch (DataException | IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve the fileLocation of the Master Quality...");
    }

    logger.debug("Found video/webm location: " + fileLocation);

    // send to remote FTP folder
    FTPClient client = new FTPClient();
    try {
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                if (client.changeWorkingDirectory(workdir)) {
                    // TODO add behavior if file name is already present in
                    // remote ftp folder
                    // now OVERWRITES
                    File file = new File(fileLocation);
                    if (file.isFile()) {
                        if (client.storeFile(targetName, new FileInputStream(file))) {
                            logger.info("Stored file on server " + host + ":" + port + workdir);
                        } else {
                            throw new TaskExecutionFailedException("Cannot store file on server");
                        }
                    } else {
                        throw new TaskExecutionFailedException("Local file doesn't exist or is not acceptable");
                    }
                } else {
                    throw new TaskExecutionFailedException("Cannot browse directory " + workdir + " on server");
                }
            } else {
                throw new TaskExecutionFailedException("Username and Password not accepted by the server");
            }
        } else {
            throw new TaskExecutionFailedException(
                    "Cannot establish connection with server " + host + ":" + port);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("General exception with FTPClient");
    }

    logger.debug("Executed without errors " + this.getClass().getName());
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * /*from w w w . j  a  v a 2  s  .c  o m*/
 *
 * @param remotePath ftp
 * @param fileName   ???
 * @param localPath  ???
 * @return true/false ?
 */
public boolean downloadFile(String remotePath, String fileName, String localPath) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(remotePath);
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile file : files) {
            if (file.getName().equals(fileName)) {
                File localFile = new File(localPath + File.separator + file.getName());
                OutputStream outputStream = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), outputStream);
                outputStream.close();
            }
        }
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

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

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

    String fileName = filePath;/*from ww w .j  a  v 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;
}