List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:com.isencia.passerelle.actor.ftp.FtpSenderChannel.java
/** * @see ISenderChannel#open()/*from w w w.j a v a2 s . c o m*/ */ public void open() throws ChannelException { if (logger.isTraceEnabled()) logger.trace(""); if (server == null) throw new ChannelException("Server is not specified"); if (username == null) throw new ChannelException("Username is not specified"); if (password == null) throw new ChannelException("Password is not specified"); if (remote == null) throw new ChannelException("File is not specified"); // CONNECT TO SERVER try { int reply; ftp.connect(server); logger.debug("Connected to " + server + "."); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); logger.error("FTP server refused connection"); throw new ChannelException("FTP server refused connection"); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } logger.error("Could not connect to server"); throw new ChannelException("Could not connect to server"); } try { // LOGIN TO THE SERVER if (!ftp.login(username, password)) { ftp.logout(); throw new ChannelException( "Can't login with username " + this.username + " and password " + this.password); } logger.debug("Remote system is " + ftp.getSystemName()); // ADJUST SETTINGS if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } if (passiveMode) { // Use passive mode as default because most of us are // behind firewalls these days. ftp.enterLocalPassiveMode(); //Remark: after the login! } } catch (ChannelException e1) { throw new ChannelException(e1.getMessage()); } catch (IOException e1) { //TODO: need to think about this... throw new ChannelException(e1.getMessage() + " (IOException)"); } try { setWriter(new OutputStreamWriter(ftp.storeFileStream(remote), "UTF-8")); } catch (Exception e) { logger.error("Error opening destination file " + remote, e); throw new ChannelException("Error opening destination file " + remote + " : " + e.getMessage()); } super.open(); if (logger.isTraceEnabled()) logger.trace("exit"); }
From source file:ServeurFTP.java
public ServeurFTP(String server10, String username10, String password10, String file10, String server20, String username20, String password20, String file20) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;//w w w . j av a 2 s.co m int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; server1 = server10; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = username10; password1 = password10; file1 = file10; server2 = server20; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = username20; password2 = password20; file2 = file20; listener = new PrintCommandListener(new PrintWriter(System.out), true); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } try { int reply; if (port2 > 0) { ftp2.connect(server2, port2); } else { ftp2.connect(server2); } System.out.println("Connected to " + server2 + "."); reply = ftp2.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp2.disconnect(); System.err.println("FTP server2 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp2.isConnected()) { try { ftp2.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server2."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp1.login(username1, password1)) { System.err.println("Could not login to " + server1); break __main; } if (!ftp2.login(username2, password2)) { System.err.println("Could not login to " + server2); break __main; } // Let's just assume success for now. ftp2.enterRemotePassiveMode(); ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort()); // Although you would think the store command should be sent to server2 // first, in reality, ftp servers like wu-ftpd start accepting data // connections right after entering passive mode. Additionally, they // don't even send the positive preliminary reply until after the // transfer is completed (in the case of passive mode transfers). // Therefore, calling store first would hang waiting for a preliminary // reply. if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) { // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) { // We have to fetch the positive completion reply. ftp1.completePendingCommand(); ftp2.completePendingCommand(); } else { System.err.println("Couldn't initiate transfer. Check that filenames are valid."); break __main; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (ftp1.isConnected()) { ftp1.logout(); ftp1.disconnect(); } } catch (IOException e) { // do nothing } try { if (ftp2.isConnected()) { ftp2.logout(); ftp2.disconnect(); } } catch (IOException e) { // do nothing } } }
From source file:edu.monash.merc.system.remote.FTPFileGetter.java
/** * A convenience method for connecting and logging in * * @param host/*from w w w . j a v a 2 s . co m*/ * @param userName * @param password * @return */ public boolean connectAndLogin(String host, String userName, String password) { boolean success = false; try { connect(host); int reply = getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { success = login(userName, password); } if (!success) { disconnect(); } } catch (Exception ex) { throw new DMFTPException(ex); } return success; }
From source file:de.ep3.ftpc.controller.portal.CrawlerDownloadController.java
@Override public void mouseClicked(MouseEvent e) { CrawlerResultsItem.PreviewPanel previewPanel = (CrawlerResultsItem.PreviewPanel) e.getSource(); CrawlerResult crawlerResult = previewPanel.getCrawlerResult(); CrawlerFile crawlerFile = crawlerResult.getFile(); FTPClient ftpClient = crawlerResult.getFtpClient(); if (ftpClient.isConnected()) { JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadWhileConnected"), null, JOptionPane.ERROR_MESSAGE); return;/*from w w w . j a va2 s. c om*/ } String fileExtension = crawlerFile.getExtension(); JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter chooserFilter = new FileNameExtensionFilter( i18n.translate("fileType", fileExtension.toUpperCase()), crawlerFile.getExtension()); chooser.setApproveButtonText(i18n.translate("buttonSave")); chooser.setDialogTitle(i18n.translate("fileDownloadTo")); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setFileFilter(chooserFilter); chooser.setSelectedFile(new File(crawlerFile.getName())); int selection = chooser.showSaveDialog(portalFrame); if (selection == JFileChooser.APPROVE_OPTION) { File fileToSave = chooser.getSelectedFile(); Server relatedServer = crawlerResult.getServer(); try { ftpClient.connect(relatedServer.need("server.ip"), Integer.parseInt(relatedServer.need("server.port"))); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new IOException(i18n.translate("crawlerServerRefused")); } if (relatedServer.has("user.name")) { String userName = relatedServer.get("user.name"); String userPassword = ""; if (relatedServer.hasTemporary("user.password")) { userPassword = relatedServer.getTemporary("user.password"); } boolean loggedIn = ftpClient.login(userName, userPassword); if (!loggedIn) { throw new IOException(i18n.translate("crawlerServerAuthFail")); } } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); /* Download file */ InputStream is = ftpClient.retrieveFileStream(crawlerFile.getFullName()); if (is != null) { byte[] rawFile = new byte[(int) crawlerFile.getSize()]; int i = 0; while (true) { int b = is.read(); if (b == -1) { break; } rawFile[i] = (byte) b; i++; /* Occasionally update the download progress */ if (i % 1024 == 0) { int progress = Math.round((((float) i) / crawlerFile.getSize()) * 100); status.add(i18n.translate("crawlerDownloadProgress", progress)); } } is.close(); is = null; if (!ftpClient.completePendingCommand()) { throw new IOException(); } Files.write(fileToSave.toPath(), rawFile); } /* Logout and disconnect */ ftpClient.logout(); tryDisconnect(ftpClient); status.add(i18n.translate("crawlerDownloadDone")); } catch (IOException ex) { tryDisconnect(ftpClient); JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadFailed", ex.getMessage()), null, JOptionPane.ERROR_MESSAGE); } } }
From source file:com.feilong.tools.net.filetransfer.FTPUtil.java
@Override protected boolean connect() { // ??, ??// w w w.ja v a2 s .com boolean isSuccess = false; try { // ftpClient.connect(hostName); log.debug("connect hostName:{}", hostName); boolean isLoginSuccess = ftpClient.login(userName, password); Object[] params = { userName, password, isLoginSuccess }; log.debug("login:[{}] [{}], {}~~~", params); if (isLoginSuccess) { int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { log.error("FTP ???ReplyCode is:{},will ftpClient.disconnect()", replyCode); ftpClient.disconnect(); return false; } else { // ******************************************************************************************* // ? ?login?, ??FTPClient. ftpClient.enterLocalPassiveMode(); // FTPClientASCII?, ? // ??,?,[?login?]. ?????"TYPE I" ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String systemName = ftpClient.getSystemName(); log.debug("ftpClient systemName:[{}]", systemName); // FTP??--?? // FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); // ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); // ftpClient.configure(ftpClientConfig); // ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); // ? isSuccess = true; } } } catch (SocketException e) { log.error(e.getClass().getName(), e); disconnect(); } catch (IOException e) { disconnect(); throw new UncheckedIOException(e); } log.info("connect :{}", isSuccess); return isSuccess; }
From source file:com.savy3.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null;/*from w w w . ja v a 2 s. c om*/ try { 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())); System.out.println("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 Binary transfer mode ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.featureValue("LITERAL SITE RDW"); ftp.doCommand("SITE", "RDW"); System.out.println("reply for LITERAL" + ftp.getReplyString()); // 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:net.paissad.jcamstream.utils.FTPUtils.java
public void estabishConnection() throws SocketException, IOException, FTPException { this.setFtpClient(new FTPClient()); String errMsg;/*w ww .jav a 2s . c o m*/ FTPClient client = this.getFtpClient(); PrintCommandListener listener = new PrintCommandListener(System.out); client.addProtocolCommandListener(listener); // Connects to the FTP server String host = this.getFtpServerHost(); int port = this.getFtpServerPort(); client.connect(host, port); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); errMsg = "Unable to connect to the server " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Login to the FTP server String username = this.getFtpUser(); String pass = this.getFtpPassword(); if (!client.login(username, pass)) { errMsg = "Unable to login to " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Change the current directory String dirname = this.getFtpServerDir(); if (!client.changeWorkingDirectory(dirname)) { System.out.println("Unable to change to the directory '" + dirname + "'."); System.out.println("Going to create the directory !"); this.mkdirs(dirname); System.out.println("Creation of the directory is successful."); } client.changeWorkingDirectory(dirname); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { errMsg = "Unable to change to the directory : " + dirname; this.verifyReplyCode(errMsg); } client.pwd(); }
From source file:com.adaptris.ftp.ApacheFtpClientImpl.java
private T ftpClient() throws IOException { if (ftp == null) { ftp = createFTPClient();//from w w w.j av a 2 s .c o m preConnectSettings(ftp); ftp.setConnectTimeout(getTimeout()); ftp.setDataTimeout(getTimeout()); try { ftp.connect(remoteHost, port); logReply(ftp.getReplyStrings()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new IOException("FTP Server refused connection"); } postConnectSettings(ftp); } catch (IOException | RuntimeException e) { if (ftp.isConnected()) { ftp.disconnect(); ftp = null; } throw e; } } return ftp; }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient ftp = null;/*from ww w. j a va 2 s.c om*/ try { ftp = new FTPClient(); // For debug // f.addProtocolCommandListener(new PrintCommandListener( // new PrintWriter(System.out))); ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(fpi.getHost()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); ftp.login(fpi.getUsername(), fpi.getPassword()); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); if (fpi.isFtpUsePassiveMode()) ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); FTPClient ftpReturn = ftp; ftp = null; return ftpReturn; } finally { if (ftp != null) ftpQuietDisconnect(ftp); } }
From source file:AIR.Common.Web.FileFtpHandler.java
/** * Makes FTP call to the provided URI and retrieves contents * /* ww w.j a v a 2 s . co m*/ * @param uri * @return ByteArrayInputStream * @throws FtpResourceException */ public static byte[] getBytes(URI uri) throws FtpResourceException { try { FTPClient ftp = new FTPClient(); String[] credentialsAndHost = uri.getAuthority().split("@"); String host = credentialsAndHost[1]; String[] credentials = credentialsAndHost[0].split(":"); ftp.connect(host); ftp.enterLocalPassiveMode(); if (!ftp.login(credentials[0], credentials[1])) { ftp.logout(); ftp.disconnect(); throw new RuntimeException("FTP Authentication Failure"); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.logout(); ftp.disconnect(); throw new RuntimeException("FTP No reponse from server"); } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ByteArrayOutputStream output = new ByteArrayOutputStream(); ftp.retrieveFile(uri.getPath(), output); output.close(); ftp.logout(); ftp.disconnect(); return output.toByteArray(); } catch (IOException ex) { throw new FtpResourceException(ex); } }