List of usage examples for org.apache.commons.net.ftp FTPClient getReplyString
public String getReplyString()
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 {//from w w w . j a v a2 s . co m 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.ofbiz.common.FtpServices.java
public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); String localFilename = (String) context.get("localFilename"); OutputStream localFile = null; try {//from w w w.j a va2 s .co m localFile = new FileOutputStream(localFilename); } catch (IOException ioe) { Debug.logError(ioe, "[getFile] 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("[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module); ftp.setDefaultTimeout(defaultTimeout.intValue()); } ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale)); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); if (!ftp.login(username, password)) { 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) ? false : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) { errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale)); } } ftp.logout(); } } catch (IOException ioe) { Debug.logWarning(ioe, "[getFile] 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, "[getFile] Problem with FTP disconnect: ", module); } try { localFile.close(); } catch (Exception e) { Debug.logWarning(e, "[getFile] Problem closing local file: ", module); } } if (errorList.size() > 0) { Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } return ServiceUtil.returnSuccess(); }
From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration) throws IOException { FTPClient ftp = null; try {//from www .j av a 2s . c om String username = linkConfiguration.linkConfig.username; String password; if (username == null) { username = "anonymous"; password = ""; } else { password = linkConfiguration.linkConfig.password; } String connectString = linkConfiguration.linkConfig.uri; String server = connectString; int port = 0; String[] parts = connectString.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { LOG.warn("Invalid port number: " + e.toString()); } } if (null != mockFTPClient) { ftp = mockFTPClient; } else { ftp = new FTPClient(); } // The following section to get the system key for FTPClientConfig is just there for testing purposes String systemKey = null; String systemTypeString = context.getString("spark.mainframe.connector.system.type", "MVS"); if (systemTypeString.equals("MVS")) { systemKey = FTPClientConfig.SYST_MVS; } else if (systemTypeString.equals("UNIX")) { systemKey = FTPClientConfig.SYST_UNIX; } else { assert (false); } FTPClientConfig config = new FTPClientConfig(systemKey); ftp.configure(config); try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } } catch (IOException ioexp) { throw new IOException("Could not connect to server " + server, ioexp); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString()); } LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set ASCII transfer mode ftp.setFileType(FTP.ASCII_FILE_TYPE); // Use passive mode as default. ftp.enterLocalPassiveMode(); } catch (IOException ioe) { if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } ftp = null; throw ioe; } return ftp; }
From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java
public static void setWorkingDirectory(TransferableContext context, FTPClient ftp, String datasetName) throws IOException { String modifiedDatasetName = MainframeUtils.getDatasetName(context, datasetName); boolean replyCode = ftp.changeWorkingDirectory(modifiedDatasetName); if (!replyCode) { throw new IOException("Unable to change working directory to " + modifiedDatasetName + " for ftp transfer with ftp client = " + ftp + ". " + ftp.getReplyString()); }// w ww . j a v a 2s.c o m }
From source file:org.apache.sqoop.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null; try {/*from w ww . jav a2 s . c o m*/ String username = conf.get(DBConfiguration.USERNAME_PROPERTY); String password; if (username == null) { username = "anonymous"; password = ""; } else { password = DBConfiguration.getPassword((JobConf) conf); } String connectString = conf.get(DBConfiguration.URL_PROPERTY); String server = connectString; int port = 0; String[] parts = connectString.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { LOG.warn("Invalid port number: " + e.toString()); } } if (null != mockFTPClient) { ftp = mockFTPClient; } else { ftp = new FTPClient(); } FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS); ftp.configure(config); if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } } catch (IOException ioexp) { throw new IOException("Could not connect to server " + server, ioexp); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString()); } LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set ASCII transfer mode ftp.setFileType(FTP.ASCII_FILE_TYPE); // Use passive mode as default. ftp.enterLocalPassiveMode(); LOG.info("System type detected: " + ftp.getSystemType()); } catch (IOException ioe) { if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } ftp = null; throw ioe; } return ftp; }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Sends a single file to the remote host. <code>filename</code> may * contain a relative path specification. When this is the case, <code>sendFile</code> * will attempt to create any necessary parent directories before sending * the file. The file will then be sent using the entire relative path * spec - no attempt is made to change directories. It is anticipated that * this may eventually cause problems with some FTP servers, but it * simplifies the coding./*from ww w .j av a 2s .co m*/ * @param ftp ftp client * @param dir base directory of the file to be sent (local) * @param filename relative path of the file to be send * locally relative to dir * remotely relative to the remotedir attribute * @throws IOException in unknown circumstances * @throws BuildException in unknown circumstances */ protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException { InputStream instream = null; try { // TODO - why not simply new File(dir, filename)? File file = getProject().resolveFile(new File(dir, filename).getPath()); if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) { return; } if (verbose) { log("transferring " + file.getAbsolutePath()); } instream = new BufferedInputStream(new FileInputStream(file)); createParents(ftp, filename); ftp.storeFile(resolveFile(filename), instream); boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (!success) { String s = "could not put file: " + ftp.getReplyString(); if (skipFailedTransfers) { log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { // see if we should issue a chmod command if (chmod != null) { doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename)); } log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE); transferred++; } } finally { FileUtils.close(instream); } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Create the specified directory on the remote host. * * @param ftp The FTP client connection//from w w w . jav a2 s . c om * @param dir The directory to create (format must be correct for host * type) * @throws IOException in unknown circumstances * @throws BuildException if ignoreNoncriticalErrors has not been set to true * and a directory could not be created, for instance because it was * already existing. Precisely, the codes 521, 550 and 553 will trigger * a BuildException */ protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException { String workingDirectory = ftp.printWorkingDirectory(); if (verbose) { if (dir.startsWith("/") || workingDirectory == null) { log("Creating directory: " + dir + " in /"); } else { log("Creating directory: " + dir + " in " + workingDirectory); } } if (dir.startsWith("/")) { ftp.changeWorkingDirectory("/"); } String subdir = ""; StringTokenizer st = new StringTokenizer(dir, "/"); while (st.hasMoreTokens()) { subdir = st.nextToken(); log("Checking " + subdir, Project.MSG_DEBUG); if (!ftp.changeWorkingDirectory(subdir)) { if (!ftp.makeDirectory(subdir)) { // codes 521, 550 and 553 can be produced by FTP Servers // to indicate that an attempt to create a directory has // failed because the directory already exists. int rc = ftp.getReplyCode(); if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) { throw new BuildException("could not create directory: " + ftp.getReplyString()); } if (verbose) { log("Directory already exists"); } } else { if (verbose) { log("Directory created OK"); } ftp.changeWorkingDirectory(subdir); } } } if (workingDirectory != null) { ftp.changeWorkingDirectory(workingDirectory); } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * look at the response for a failed mkdir action, decide whether * it matters or not. If it does, we throw an exception * @param ftp current ftp connection/*from w ww. j ava 2 s .c o m*/ * @throws BuildException if this is an error to signal */ private void handleMkDirFailure(FTPClient ftp) throws BuildException { int rc = ftp.getReplyCode(); if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) { throw new BuildException("could not create directory: " + ftp.getReplyString()); } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Runs the task.//from w ww .j a va 2 s . c o m * * @throws BuildException if the task fails or is not configured * correctly. */ public void execute() throws BuildException { checkAttributes(); FTPClient ftp = null; try { log("Opening FTP connection to " + server, Project.MSG_VERBOSE); ftp = new FTPClient(); if (this.isConfigurationSet) { ftp = FTPConfigurator.configure(ftp, this); } ftp.setRemoteVerificationEnabled(enableRemoteVerification); ftp.connect(server, port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } log("connected", Project.MSG_VERBOSE); log("logging in to FTP server", Project.MSG_VERBOSE); if ((this.account != null && !ftp.login(userid, password, account)) || (this.account == null && !ftp.login(userid, password))) { throw new BuildException("Could not login to FTP server"); } log("login succeeded", Project.MSG_VERBOSE); if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (passive) { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.initialSiteCommand); } }, "initial site command: " + this.initialSiteCommand); } // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + umask); } }, "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, remotedir); } }, remotedir); } else if (action == SITE_CMD) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.siteCommand); } }, "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { // in this case we want to find how much time span there is between local // and remote timeDiffMillis = getTimeDiff(ftp); } log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java
/** * Creates all parent directories specified in a complete relative * pathname. Attempts to create existing directories will not cause * errors./*w w w. j ava2s . c o m*/ * * @param ftp the FTP client instance to use to execute FTP actions on * the remote server. * @param filename the name of the file whose parents should be created. * @throws IOException under non documented circumstances * @throws BuildException if it is impossible to cd to a remote directory * */ protected void createParents(FTPClient ftp, String filename) throws IOException, BuildException { File dir = new File(filename); if (dirCache.contains(dir)) { return; } Vector parents = new Vector(); String dirname; while ((dirname = dir.getParent()) != null) { File checkDir = new File(dirname); if (dirCache.contains(checkDir)) { break; } dir = checkDir; parents.addElement(dir); } // find first non cached dir int i = parents.size() - 1; if (i >= 0) { String cwd = ftp.printWorkingDirectory(); String parent = dir.getParent(); if (parent != null) { if (!ftp.changeWorkingDirectory(resolveFile(parent))) { throw new BuildException("could not change to " + "directory: " + ftp.getReplyString()); } } while (i >= 0) { dir = (File) parents.elementAt(i--); // check if dir exists by trying to change into it. if (!ftp.changeWorkingDirectory(dir.getName())) { // could not change to it - try to create it task.log("creating remote directory " + resolveFile(dir.getPath()), Project.MSG_VERBOSE); if (!ftp.makeDirectory(dir.getName())) { handleMkDirFailure(ftp); } if (!ftp.changeWorkingDirectory(dir.getName())) { throw new BuildException("could not change to " + "directory: " + ftp.getReplyString()); } } dirCache.add(dir); } ftp.changeWorkingDirectory(cwd); } }