List of usage examples for org.apache.commons.net.ftp FTPClient disconnect
@Override public void disconnect() throws IOException
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
private void Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;/*w w w . j av a2s . c o m*/ try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(SourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); Report = "Server Error"; jLabel6.setText(Report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java
private static boolean processDownload(final BackgroundTaskStatusProviderSupportingExternalCallImpl status, String downloadURL, String targetFileName, ObjectRef lastStatus, final int thisRun, String server, String remote, final FTPClient ftp) { String username;//from w ww. j a v a 2 s . com String password; String local; username = "anonymous@" + server; password = "anonymous"; local = targetFileName; final ObjectRef myoutputstream = new ObjectRef(); ftp.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent arg0) { // System.out.print("out: " + arg0.getMessage()); status.setCurrentStatusText1("Command: " + arg0.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent arg0) { // System.out.print("in : " + arg0.getMessage()); status.setCurrentStatusText2("Message: " + arg0.getMessage()); if (myoutputstream.getObject() != null) { String msg = arg0.getMessage(); if (msg.indexOf("Opening BINARY mode") >= 0) { if (msg.indexOf("(") > 0) { msg = msg.substring(msg.indexOf("(") + "(".length()); if (msg.indexOf(" ") > 0) { msg = msg.substring(0, msg.indexOf(" ")); try { long max = Long.parseLong(msg); MyOutputStream os = (MyOutputStream) myoutputstream.getObject(); os.setMaxBytes(max); } catch (Exception e) { System.out.println( "Could not determine file length for detailed progress information"); } } } } } } }); System.out.println("FTP DOWNLOAD: " + downloadURL); try { if (ftp.isConnected()) { status.setCurrentStatusText2("Using open FTP connection"); System.out.println("Reusing open FTP connection"); } else { ftp.connect(server); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); status.setCurrentStatusText1("Can't connect to FTP server"); status.setCurrentStatusText2("ERROR"); return false; } if (!ftp.login("anonymous", "anonymous")) { if (!ftp.login(username, password)) { ftp.disconnect(); status.setCurrentStatusText1("Can't login to FTP server"); status.setCurrentStatusText2("ERROR"); return false; } } status.setCurrentStatusText1("Set Binary Transfer Mode"); ftp.setFileType(FTP.BINARY_FILE_TYPE); status.setCurrentStatusText2("Activate Passive Transfer Mode"); ftp.enterLocalPassiveMode(); } status.setCurrentStatusText1("Start download..."); status.setCurrentStatusText2("Please Wait."); // ftp.listFiles(pathname); OutputStream output = new MyOutputStream(lastStatus, status, new FileOutputStream(local)); myoutputstream.setObject(output); ftp.setRemoteVerificationEnabled(false); long tA = System.currentTimeMillis(); boolean result = ftp.retrieveFile(remote, output); output.close(); long tB = System.currentTimeMillis(); if (!result) { new File(local).delete(); MainFrame.showMessage("Can't download " + downloadURL + ". File not available.", MessageType.INFO); } else { File f = new File(local); System.out.println("Download completed (" + f.getAbsolutePath() + ", " + (f.length() / 1024) + " KB, " + (int) ((f.length() / 1024d / (tB - tA) * 1000d)) + " KB/s)."); } BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() { public void run() { try { synchronized (GUIhelper.class) { if (runIdx == thisRun) { System.out.println("Disconnect FTP connection"); ftp.disconnect(); } } } catch (Exception err) { ErrorMsg.addErrorMessage(err); } } }); return result; } catch (Exception err) { System.out.println("ERROR: FTP DOWNLOAD ERROR: " + err.getMessage()); if (ftp != null && ftp.isConnected()) { try { System.out.println("Disconnect FTP connection (following error condition)"); ftp.disconnect(); } catch (Exception err2) { ErrorMsg.addErrorMessage(err2); } } return false; } }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;//from w ww . j av a2 s .c o m try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(sourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + sourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); report = "Server Error"; jLabel6.setText(report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java
/** * FTP????????//from w ww . j av a2 s . co m * * @param addressText * @return FTP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); FTPClient client = new FTPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } else { retry = false; isReachable = false; } } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(FTP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.jmeter.alfresco.utils.FtpUtils.java
/** * Upload directory or file.// w w w.j av a 2 s .c om * * @param host the host * @param port the port * @param userName the user name * @param password the password * @param fromLocalDirOrFile the local dir * @param toRemoteDirOrFile the remote dir * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String uploadDirectoryOrFile(final String host, final int port, final String userName, final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile) throws IOException { final FTPClient ftpClient = new FTPClient(); String responseMessage = Constants.EMPTY; try { // Connect and login to get the session ftpClient.connect(host, port); final int replyCode = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { final boolean loginSuccess = ftpClient.login(userName, password); if (loginSuccess) { LOG.debug("Connected to remote host!"); //Use local passive mode to pass fire-wall //In this mode a data connection is made by opening a port on the server for the client to connect //and this is not blocked by fire-wall. ftpClient.enterLocalPassiveMode(); final File localDirOrFileObj = new File(fromLocalDirOrFile); if (localDirOrFileObj.isFile()) { LOG.debug("Uploading file: " + fromLocalDirOrFile); uploadFile(ftpClient, fromLocalDirOrFile, toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName()); } else { uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY); } responseMessage = "Upload completed successfully!"; } else { responseMessage = "Could not login to the remote host!"; } //Log out and disconnect from the server once FTP operation is completed. if (ftpClient.isConnected()) { try { ftpClient.logout(); } catch (IOException ignored) { LOG.error("Ignoring the exception while logging out from remote host: ", ignored); } try { ftpClient.disconnect(); LOG.debug("Disconnected from remote host!"); } catch (IOException ignored) { LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored); } } } else { responseMessage = "Host connection failed!"; } LOG.debug("ResponseMessage:=> " + responseMessage); } catch (IOException ioexcp) { LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp); throw ioexcp; } return responseMessage; }
From source file:fr.acxio.tools.agia.ftp.FTPDownloadTasklet.java
@Override public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception { FTPClient aClient = ftpClientFactory.getFtpClient(); RegexFilenameFilter aFilter = new RegexFilenameFilter(); aFilter.setRegex(regexFilename);//from w ww . j a va2s . c o m try { URI aRemoteBaseURI = new URI(remoteBaseDir); URI aRemoteBasePath = new URI(aRemoteBaseURI.toASCIIString() + SEPARATOR); if (LOGGER.isInfoEnabled()) { LOGGER.info("Listing : [{}] {} ({})", aClient.getRemoteAddress().toString(), aRemoteBaseURI.toASCIIString(), regexFilename); } FTPFile[] aRemoteFiles = aClient.listFiles(aRemoteBaseURI.toASCIIString(), aFilter); if (LOGGER.isInfoEnabled()) { LOGGER.info(" {} file(s) found", aRemoteFiles.length); } for (FTPFile aRemoteFile : aRemoteFiles) { if (sContribution != null) { sContribution.incrementReadCount(); } File aLocalFile = new File(localBaseDir, aRemoteFile.getName()); URI aRemoteTFile = aRemoteBasePath.resolve(aRemoteFile.getName()); FileOutputStream aOutputStream = new FileOutputStream(aLocalFile); try { if (LOGGER.isInfoEnabled()) { LOGGER.info(" Downloading : {} => {}", aRemoteTFile.toASCIIString(), aLocalFile.getAbsolutePath()); } aClient.retrieveFile(aRemoteTFile.toASCIIString(), aOutputStream); if (removeRemote) { if (LOGGER.isInfoEnabled()) { LOGGER.info(" Deleting : {}", aRemoteTFile.toASCIIString()); } aClient.deleteFile(aRemoteTFile.toASCIIString()); } if (sContribution != null) { sContribution.incrementWriteCount(1); } } finally { aOutputStream.close(); } } } finally { aClient.logout(); aClient.disconnect(); } return RepeatStatus.FINISHED; }
From source file:madkitgroupextension.export.Export.java
private static void sendToWebSite() throws IOException { System.out.println("Enter your password :"); byte b[] = new byte[100]; int l = System.in.read(b); String pwd = new String(b, 0, l); boolean reconnect = true; long time = System.currentTimeMillis(); File current_file_transfert = null; File current_directory_transfert = null; while (reconnect) { FTPClient ftpClient = new FTPClient(); ftpClient.connect(FTPURL, 21);/*from ww w .ja va 2 s .co m*/ try { if (ftpClient.isConnected()) { System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !"); if (ftpClient.login(FTPLOGIN, pwd)) { ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); System.out.println("Logged as " + FTPLOGIN + " !"); System.out.print("Updating..."); FTPFile files[] = ftpClient.listFiles(""); FTPFile downloadroot = null; FTPFile docroot = null; for (FTPFile f : files) { if (f.getName().equals("downloads")) { downloadroot = f; if (docroot != null) break; } if (f.getName().equals("doc")) { docroot = f; if (downloadroot != null) break; } } if (downloadroot == null) { //ftpClient.changeWorkingDirectory("/"); if (!ftpClient.makeDirectory("downloads")) { System.err.println("Impossible to create directory: downloads"); } } if (docroot == null) { //ftpClient.changeWorkingDirectory("/"); if (!ftpClient.makeDirectory("doc")) { System.err.println("Impossible to create directory: doc"); } } updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert, current_directory_transfert); updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert, current_directory_transfert); reconnect = false; System.out.println("[OK]"); if (ftpClient.logout()) { System.out.println("Logged out from " + FTPLOGIN + " succesfull !"); } else System.err.println("Logged out from " + FTPLOGIN + " FAILED !"); } else System.err.println("Impossible to log as " + FTPLOGIN + " !"); ftpClient.disconnect(); System.out.println("Disconnected from " + FTPURL + " !"); } else { System.err.println("Impossible to get a connection to the server " + FTPURL + " !"); } reconnect = false; } catch (TransfertException e) { if (System.currentTimeMillis() - time > 30000) { System.err.println("A problem occured during the transfert..."); System.out.println("Reconnection in progress..."); try { ftpClient.disconnect(); } catch (Exception e2) { } current_file_transfert = e.current_file_transfert; current_directory_transfert = e.current_directory_transfert; time = System.currentTimeMillis(); } else { System.err.println("A problem occured during the transfert. Transfert aborded."); throw e.original_exception; } } } }
From source file:com.rvl.android.getnzb.LocalNZB.java
public void uploadLocalFileFTP(String filename) { UPLOADFILENAME = filename;//from ww w. j a v a2s .c o m UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server."); SharedPreferences prefs = GetNZB.preferences; if (prefs.getString("FTPHostname", "") == "") { uploadDialogHandler.sendEmptyMessage(0); Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.", Toast.LENGTH_LONG).show(); return; } new Thread() { public void run() { SharedPreferences prefs = GetNZB.preferences; FTPClient ftp = new FTPClient(); String replycode = ""; String FTPHostname = prefs.getString("FTPHostname", ""); String FTPUsername = prefs.getString("FTPUsername", "anonymous"); String FTPPassword = prefs.getString("FTPPassword", "my@email.address"); String FTPPort = prefs.getString("FTPPort", "21"); String FTPUploadPath = prefs.getString("FTPUploadPath", "~/"); if (!FTPUploadPath.matches("$/")) { Log.d(Tags.LOG, "Adding trailing slash"); FTPUploadPath += "/"; } String targetFile = FTPUploadPath + UPLOADFILENAME; try { ftp.connect(FTPHostname, Integer.parseInt(FTPPort)); if (ftp.login(FTPUsername, FTPPassword)) { ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); File file = new File(getFilesDir() + "/" + UPLOADFILENAME); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file)); Log.d(Tags.LOG, "Saving file to:" + targetFile); if (ftp.storeFile(targetFile, buffIn)) { Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: " + Integer.toString(ftp.getReplyCode())); isUploadedFTP = true; } else { Log.d(Tags.LOG, "FTP: Could not upload file Replycode: " + Integer.toString(ftp.getReplyCode())); FTPErrorCode = Integer.toString(ftp.getReplyCode()); isUploadedFTP = false; } buffIn.close(); ftp.logout(); ftp.disconnect(); } else { Log.d(Tags.LOG, "No ftp login"); } } catch (SocketException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } catch (IOException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } if (isUploadedFTP) { removeLocalNZBFile(UPLOADFILENAME); } UPLOADFILENAME = ""; uploadDialogHandlerFTP.sendEmptyMessage(0); } }.start(); }
From source file:com.droid.app.fotobot.FotoBot.java
public boolean files_to_ftp(List<String> FTP_files) { String server;//from www. j av a 2s . co m int port; String user; String pass; String FTP_folder = ""; if (FTP_server.contains("/")) { FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1)); FTP_folder = FTP_folder.substring(1); server = FTP_server.substring(0, FTP_server.indexOf("/", 1)); } else { server = FTP_server; } port = Integer.parseInt(FTP_port); user = FTP_username; pass = FTP_password; SendMessage("FTP user: " + "<br>" + user, MSG_PASS); SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS); SendMessage("FTP server: " + "<br>" + server, MSG_PASS); FTPClient ftpClient = new FTPClient(); try { int reply; ftpClient.connect(server, port); System.out.println("Connected to " + server + "."); System.out.print(ftpClient.getReplyString()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); SendMessage("FTP ?", MSG_FAIL); return false; } } catch (Exception e) { } try { ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } SendMessage( " ? FTP ?, FTP ?.", MSG_FAIL); return false; } } catch (Exception e) { } // chdir if (FTP_folder.length() > 1) { try { ftpClient.changeWorkingDirectory(FTP_folder); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println("FTP chdir error"); SendMessage( "FTP ? <br>" + FTP_folder, MSG_FAIL); return false; } SendMessage("FTP <br>" + FTP_folder, MSG_PASS); System.out.println("Successfully changed working directory."); } catch (Exception e) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e1) { e1.printStackTrace(); } SendMessage("FTP ? <br>" + FTP_folder, MSG_FAIL); System.out.println("Failed to change working directory."); return false; } } try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (Exception e) { SendMessage("FTP BINARY_FILE_TYPE", MSG_FAIL); System.out.println("Failed to change to BINARY_FILE_TYPE."); return false; } // APPROACH #1: uploads first file using an InputStream for (String str : FTP_files) { File firstLocalFile = new File(str); String firstRemoteFile = firstLocalFile.getName(); try { InputStream inputStream = new FileInputStream(firstLocalFile); SendMessage("? ", MSG_PASS); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS); } } catch (IOException ex) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } SendMessage(" ? " + "<br>" + str + "<br>" + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage() + "<br>" + " FTP ?.", MSG_FAIL); ex.printStackTrace(); } } try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); SendMessage("FTP ???? ", MSG_PASS); fbpause(h, 3); return true; } } catch (IOException ex) { ex.printStackTrace(); SendMessage("FTP ???? ", MSG_FAIL); } return false; }
From source file:com.clican.pluto.cms.core.service.impl.IssueServiceImpl.java
private boolean issue(ISite site, ITemplate template, IDataModel dataModel, String relativePath, Map<ISite, FTPClient> ftpMap) { Template t = null;/*from w w w. jav a 2 s . c om*/ Writer w = null; VelocityContext velocityContext = new VelocityContext(); velocityContext.put("this", dataModel); FTPClient client = null; try { SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(template.getContent(), template.getName()); t = new Template(); t.setName(template.getName()); t.setRuntimeServices(RuntimeSingleton.getRuntimeServices()); t.setData(node); t.initDocument(); OutputStream os = null; if (site.getUrl().startsWith("ftp://")) { client = null; if (ftpMap != null) { client = ftpMap.get(site); } if (client == null) { client = siteService.getFTPClient(site); } if (client == null) { log.error("This site[" + site.getName() + "] is unavailable"); return false; } if (!relativePath.endsWith("/")) { relativePath = relativePath + "/"; } client.mkd(relativePath); os = client.appendFileStream(relativePath + dataModel.getName() + "." + template.getSuffix()); } else if (site.getUrl().startsWith("file://")) { String filePath = site.getUrl().substring(7); File file = new File(filePath + relativePath); if (file.exists()) { file.mkdirs(); } os = new FileOutputStream(new File(file, dataModel.getName() + "." + template.getSuffix())); } else { throw new UnknownHostException(site.getUrl()); } w = new OutputStreamWriter(os, "utf-8"); t.merge(velocityContext, w); w.flush(); return true; } catch (Exception e) { log.error("", e); return false; } finally { try { if (w != null) { w.close(); } } catch (Exception e) { log.error("", e); } try { if (ftpMap == null && client != null) { client.logout(); client.disconnect(); } } catch (Exception e) { log.error("", e); } } }