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

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

Introduction

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

Prototype

public boolean sendSiteCommand(String arguments) throws IOException 

Source Link

Document

Send a site specific command.

Usage

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Sends a site command to the ftp server
 * @param ftp ftp client/*from w w w.  j  a  v  a2s  . c  om*/
 * @param theCMD command to execute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void doSiteCommand(FTPClient ftp, String theCMD) throws IOException, BuildException {
    boolean rc;
    String[] myReply = null;

    log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE);

    rc = ftp.sendSiteCommand(theCMD);

    if (!rc) {
        log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN);
    } else {

        myReply = ftp.getReplyStrings();

        for (int x = 0; x < myReply.length; x++) {
            if (myReply[x].indexOf("200") == -1) {
                log(myReply[x], Project.MSG_WARN);
            }
        }
    }
}

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

@Override
public String put(final FlowFile flowFile, final String path, final String filename, final InputStream content)
        throws IOException {
    final FTPClient client = getClient(flowFile);

    final String fullPath;
    if (path == null) {
        fullPath = filename;/*from  w  w  w  .j  av a 2  s  .c o m*/
    } else {
        final String workingDir = setAndGetWorkingDirectory(path);
        fullPath = workingDir.endsWith("/") ? workingDir + filename : workingDir + "/" + filename;
    }

    String tempFilename = ctx.getProperty(TEMP_FILENAME).evaluateAttributeExpressions(flowFile).getValue();
    if (tempFilename == null) {
        final boolean dotRename = ctx.getProperty(DOT_RENAME).asBoolean();
        tempFilename = dotRename ? "." + filename : filename;
    }

    final boolean storeSuccessful = client.storeFile(tempFilename, content);
    if (!storeSuccessful) {
        throw new IOException("Failed to store file " + tempFilename + " to " + fullPath + " due to: "
                + client.getReplyString());
    }

    final String lastModifiedTime = ctx.getProperty(LAST_MODIFIED_TIME).evaluateAttributeExpressions(flowFile)
            .getValue();
    if (lastModifiedTime != null && !lastModifiedTime.trim().isEmpty()) {
        try {
            final DateFormat informat = new SimpleDateFormat(FILE_MODIFY_DATE_ATTR_FORMAT, Locale.US);
            final Date fileModifyTime = informat.parse(lastModifiedTime);
            final DateFormat outformat = new SimpleDateFormat(FTP_TIMEVAL_FORMAT, Locale.US);
            final String time = outformat.format(fileModifyTime);
            if (!client.setModificationTime(tempFilename, time)) {
                // FTP server probably doesn't support MFMT command
                logger.warn("Could not set lastModifiedTime on {} to {}",
                        new Object[] { flowFile, lastModifiedTime });
            }
        } catch (final Exception e) {
            logger.error("Failed to set lastModifiedTime on {} to {} due to {}",
                    new Object[] { flowFile, lastModifiedTime, e });
        }
    }
    final String permissions = ctx.getProperty(PERMISSIONS).evaluateAttributeExpressions(flowFile).getValue();
    if (permissions != null && !permissions.trim().isEmpty()) {
        try {
            int perms = numberPermissions(permissions);
            if (perms >= 0) {
                if (!client.sendSiteCommand("chmod " + Integer.toOctalString(perms) + " " + tempFilename)) {
                    logger.warn("Could not set permission on {} to {}", new Object[] { flowFile, permissions });
                }
            }
        } catch (final Exception e) {
            logger.error("Failed to set permission on {} to {} due to {}",
                    new Object[] { flowFile, permissions, e });
        }
    }

    if (!filename.equals(tempFilename)) {
        try {
            logger.debug("Renaming remote path from {} to {} for {}",
                    new Object[] { tempFilename, filename, flowFile });
            final boolean renameSuccessful = client.rename(tempFilename, filename);
            if (!renameSuccessful) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " due to: " + client.getReplyString());
            }
        } catch (final IOException e) {
            try {
                client.deleteFile(tempFilename);
                throw e;
            } catch (final IOException e1) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " and failed to delete it when attempting to clean up", e1);
            }
        }
    }

    return fullPath;
}

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logInfo("[putFile] starting...", module);
    InputStream localFile = null;
    try {/*ww  w .  ja v  a 2  s. c  om*/
        localFile = new FileInputStream((String) context.get("localFilename"));
    } catch (IOException ioe) {
        Debug.logError(ioe, "[putFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            Debug.logInfo("[putFile] Server refused connection", module);
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
            if (!ftp.login(username, password)) {
                Debug.logInfo("[putFile] login failed", module);
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"),
                        module);
                if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
                    Debug.logInfo("[putFile] store was unsuccessful", module);
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                } else {
                    Debug.logInfo("[putFile] store was successful", module);
                    List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
                    if (siteCommands != null) {
                        for (String command : siteCommands) {
                            Debug.logInfo("[putFile] sending SITE command: " + command, module);
                            if (!ftp.sendSiteCommand(command)) {
                                errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed",
                                        UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()),
                                        locale));
                            }
                        }
                    }
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    Debug.logInfo("[putFile] finished successfully", module);
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Sends a site command to the ftp server
 * @param ftp ftp client/*  ww  w. j  ava  2 s . c  o m*/
 * @param theCMD command to execute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void doSiteCommand(FTPClient ftp, String theCMD) throws IOException, BuildException {
    boolean rc;
    String[] myReply = null;

    log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE);

    rc = ftp.sendSiteCommand(theCMD);

    if (!rc) {
        log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN);
    } else {

        myReply = ftp.getReplyStrings();

        for (int x = 0; x < myReply.length; x++) {
            if (myReply[x] != null && myReply[x].indexOf("200") == -1) {
                log(myReply[x], Project.MSG_WARN);
            }
        }
    }
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 * Sends a site command to the ftp server
 * @param ftp ftp client/*w  w  w. j a va  2 s  . c o m*/
 * @param theCMD command to execute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void doSiteCommand(FTPClient ftp, String theCMD) throws IOException, BuildException {
    boolean rc;
    String[] myReply = null;

    task.log("Doing Site Command: " + theCMD, Project.MSG_VERBOSE);

    rc = ftp.sendSiteCommand(theCMD);

    if (!rc) {
        task.log("Failed to issue Site Command: " + theCMD, Project.MSG_WARN);
    } else {

        myReply = ftp.getReplyStrings();

        for (int x = 0; x < myReply.length; x++) {
            if (myReply[x].indexOf("200") == -1) {
                task.log(myReply[x], Project.MSG_WARN);
            }
        }
    }
}