List of usage examples for org.apache.commons.net.ftp FTPClient retrieveFile
public boolean retrieveFile(String remote, OutputStream local) throws IOException
From source file:org.sipfoundry.preflight.FTP.java
public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService, InetAddress bindAddress) { ResultCode results = NONE;/*from ww w. j av a2 s . c o m*/ InetAddress ftpServerAddress = null; String testFile = new String("00D01EFFFFFE"); String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server", "[PROVISION]", "decrypt_key" }; if (networkResources.configServer == null) { journalService.println("No FTP server provided, skipping test.\n"); return CONFIG_SERVER_MISSING; } journalService.println("Starting FTP server test."); if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) { try { ftpServerAddress = InetAddress.getByName(networkResources.configServer); } catch (UnknownHostException e) { // Should never get here. e.printStackTrace(); } journalService.println("Using FTP server literal address: " + networkResources.configServer); } else { // Try to retrieve A RECORD for FTP server, checking each DNS server. SimpleResolver resolver = null; try { resolver = new SimpleResolver(); resolver.setLocalAddress(bindAddress); resolver.setTimeout(timeout); } catch (UnknownHostException e) { e.printStackTrace(); } for (InetAddress dnsServer : networkResources.domainNameServers) { journalService.println( "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName()); String targetMessage = new String(" FTP server address \"" + networkResources.configServer + "\""); resolver.setAddress(dnsServer); Lookup aLookup = null; try { aLookup = new Lookup(networkResources.configServer, Type.A); } catch (TextParseException e) { journalService.println(" is malformed.\n"); journalService.println(targetMessage); return FTP_ADDRESS_MALFORMED; } aLookup.setResolver(resolver); Record[] aRecords = aLookup.run(); switch (aLookup.getResult()) { case Lookup.SUCCESSFUL: if (aRecords != null) { InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress(); targetMessage += " resolves to: " + targetAddress.getHostAddress(); journalService.println(targetMessage); if (ftpServerAddress == null) { ftpServerAddress = targetAddress; } else { // Check that multiple lookups result in same // address. if (!ftpServerAddress.equals(targetAddress)) { journalService.println(" FTP server address does not match prior lookup."); results = MULTIPLE_CONFIG_TARGETS; } } } else { targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; } break; case Lookup.UNRECOVERABLE: targetMessage += " [Unrecoverable error]"; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.TRY_AGAIN: targetMessage += " [Lookup timeout]"; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.HOST_NOT_FOUND: targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; case Lookup.TYPE_NOT_FOUND: targetMessage += " could not be resolved."; journalService.println(targetMessage); results = FTP_TARGET_UNRESOLVED; break; } } } if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) { journalService.println("Cannot recover from previous errors, aborting FTP test.\n"); return results; } journalService.println("Beginning FTP get request of test file: " + testFile); // Open the FTP connection. FTPClient ftp = new FTPClient(); ftp.setDefaultTimeout(timeout * 1000); ftp.addProtocolCommandListener(new PrintCommandListener(journalService)); try { int reply; ftp.connect(ftpServerAddress, 21, bindAddress, bindPort); // After connection, check reply code to verify. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); journalService.println("FTP client failure: " + reply + "\n"); return FTP_CLIENT_FAILURE; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // Ignore. } } journalService.println("FTP client failure: " + e.getMessage() + "\n"); return FTP_CLIENT_FAILURE; } try { if (!ftp.login(ftpUser, ftpPassword)) { ftp.logout(); journalService.println("FTP client unable to log in.\n"); return FTP_GET_FAILED; } journalService.println("FTP client connected to: " + ftp.getSystemName()); ftp.enterLocalPassiveMode(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ftp.retrieveFile(testFile, output); // After receiving, check reply code to verify. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); journalService.println("FTP get failure: " + reply + "\n"); return FTP_GET_FAILED; } ftp.logout(); String testFileContents = output.toString(); boolean verified = true; for (String verificationString : verificationStrings) { if (!testFileContents.contains(verificationString)) { verified = false; } } if (verified) { journalService.println("File received successfully."); } else { journalService.println("File received but contents do not verify."); System.err.println(testFileContents); results = FTP_CONTENTS_FAILED; } } catch (FTPConnectionClosedException e) { journalService.println("FTP server closed connection prematurely.\n"); return FTP_GET_FAILED; } catch (IOException e) { journalService.println("FTP client failure. " + e.getMessage() + "\n"); return FTP_CLIENT_FAILURE; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // Ignore. } } } journalService.println(""); return results; }
From source file:org.spka.cursus.publish.website.ftp.DownloadDataFiles.java
public void from(FTPClient ftp) throws IOException { if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IllegalStateException("Unable to set mode to binary"); }// w w w . ja v a2 s .co m for (String fileName : files.keySet()) { if (fileName.startsWith(Constants.RESULTS_DIR + "/__") && fileName.endsWith(".xml")) { if (files.get(fileName) == null) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); if (!ftp.retrieveFile(fileName, buf)) { throw new IllegalStateException("Unable to retrieve " + fileName); } buf.close(); files.put(fileName, ByteSource.wrap(buf.toByteArray())); } } } }
From source file:org.spka.cursus.publish.website.ftp.Uploader.java
public void to(FTPClient ftp, Map<String, ByteSource> newFiles) throws IOException { if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IllegalStateException("Unable to set mode to binary"); }//from ww w.j ava2 s . c o m for (Map.Entry<String, ByteSource> file : newFiles.entrySet()) { ByteSource other = null; if (existingFiles.containsKey(file.getKey())) { other = existingFiles.get(file.getKey()); if (other == null) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); if (!ftp.retrieveFile(file.getKey(), buf)) { throw new IllegalStateException("Unable to retrieve " + file.getKey()); } buf.close(); other = ByteSource.wrap(buf.toByteArray()); existingFiles.put(file.getKey(), other); } } if (other == null || !file.getValue().contentEquals(other)) { InputStream in = file.getValue().openStream(); if (!ftp.storeFile(file.getKey(), in)) { throw new IllegalStateException("Unable to store " + file.getKey()); } in.close(); existingFiles.put(file.getKey(), file.getValue()); } } }
From source file:org.waarp.ftp.client.FTPClientExample.java
public static final void main(String[] args) { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;/*from w w w. j a va2 s. co m*/ boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = false; boolean lenient = false; long keepAliveTimeout = -1; int controlKeepAliveReplyTimeout = -1; int minParams = 5; // listings require 3 params String protocol = null; // SSL protocol String doCommand = null; String trustmgr = null; String proxyHost = null; int proxyPort = 80; String proxyUser = null; String proxyPassword = null; int base = 0; for (base = 0; base < args.length; base++) { if (args[base].equals("-s")) { storeFile = true; } else if (args[base].equals("-a")) { localActive = true; } else if (args[base].equals("-b")) { binaryTransfer = true; } else if (args[base].equals("-c")) { doCommand = args[++base]; minParams = 3; } else if (args[base].equals("-d")) { mlsd = true; minParams = 3; } else if (args[base].equals("-e")) { useEpsvWithIPv4 = true; } else if (args[base].equals("-f")) { feat = true; minParams = 3; } else if (args[base].equals("-h")) { hidden = true; } else if (args[base].equals("-k")) { keepAliveTimeout = Long.parseLong(args[++base]); } else if (args[base].equals("-l")) { listFiles = true; minParams = 3; } else if (args[base].equals("-L")) { lenient = true; } else if (args[base].equals("-n")) { listNames = true; minParams = 3; } else if (args[base].equals("-p")) { protocol = args[++base]; } else if (args[base].equals("-t")) { mlst = true; minParams = 3; } else if (args[base].equals("-w")) { controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]); } else if (args[base].equals("-T")) { trustmgr = args[++base]; } else if (args[base].equals("-PrH")) { proxyHost = args[++base]; String parts[] = proxyHost.split(":"); if (parts.length == 2) { proxyHost = parts[0]; proxyPort = Integer.parseInt(parts[1]); } } else if (args[base].equals("-PrU")) { proxyUser = args[++base]; } else if (args[base].equals("-PrP")) { proxyPassword = args[++base]; } else if (args[base].equals("-#")) { printHash = true; } else { break; } } int remain = args.length - base; if (remain < minParams) // server, user, pass, remote, local [protocol] { System.err.println(USAGE); System.exit(1); } String server = args[base++]; int port = 0; String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); } String username = args[base++]; String password = args[base++]; String account = args[base++]; String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } boolean mustCallProtP = false; final FTPClient ftp; if (protocol == null) { if (proxyHost != null) { System.out.println("Using HTTP proxy server: " + proxyHost); ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword); } else { ftp = new FTPClient(); } } else { FTPSClient ftps; if (protocol.equals("true")) { System.out.println("Implicit FTPS"); ftps = new FTPSClient(true); } else if (protocol.equals("false")) { System.out.println("Explicit FTPS"); ftps = new FTPSClient(false); mustCallProtP = true; } else { String prot[] = protocol.split(","); System.out.println("Protocl FTPS: " + protocol); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false mustCallProtP = !Boolean.parseBoolean(prot[1]); ftps = new FTPSClient(prot[0], !mustCallProtP); } } ftp = ftps; if ("all".equals(trustmgr)) { System.out.println("Accept all"); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { System.out.println("Accept after valid"); ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { System.out.println("Accept none"); ftps.setTrustManager(null); } } if (printHash) { ftp.setCopyStreamListener(createListener()); } if (keepAliveTimeout >= 0) { ftp.setControlKeepAliveTimeout(keepAliveTimeout); } if (controlKeepAliveReplyTimeout >= 0) { ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.getDataConnectionMode() == FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (account == null) { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } } else { if (!ftp.login(username, password, account)) { ftp.logout(); error = true; break __main; } } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (localActive) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4(useEpsvWithIPv4); if (mustCallProtP) { ((FTPSClient) ftp).execPBSZ(0); ((FTPSClient) ftp).execPROT("P"); } if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } else if (listFiles) { if (lenient) { FTPClientConfig config = new FTPClientConfig(); config.setLenientFutureDates(true); ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString()); } } else if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } else if (feat) { // boolean feature check if (remote != null) { // See if the command is present if (ftp.hasFeature(remote)) { System.out.println("Has feature: " + remote); } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " was not detected"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } // Strings feature check String[] features = ftp.featureValues(remote); if (features != null) { for (String f : features) { System.out.println("FEAT " + remote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " is not present"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } } else { if (ftp.features()) { // Command listener has already printed the output } else { System.out.println("Failed: " + ftp.getReplyString()); } } } else if (doCommand != null) { if (ftp.doCommand(doCommand, remote)) { // Command listener has already printed the output // for(String s : ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.getDataConnectionMode() == FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:org.wso2.iot.agent.services.FileDownloadService.java
/** * This method downloads the file using sftp client. * * @param operation - operation object. * @param host - host address. * @param ftpUserName - ftp user name. * @param ftpPassword - ftp password. * @param savingLocation - location in the device to save the file. * @param fileName - name of the file to download. * @param serverPort - ftp server port. * @param fileDirectory - the directory of the file in FTP server. * @throws AndroidAgentException - Android agent exception. *//*from w ww. j a va 2 s . co m*/ private void downloadFileUsingFTPClient(Operation operation, String host, String ftpUserName, String ftpPassword, String savingLocation, String fileName, int serverPort, String fileDirectory) throws AndroidAgentException { FTPClient ftpClient = new FTPClient(); FileOutputStream fileOutputStream = null; OutputStream outputStream = null; String response; try { ftpClient.connect(host, serverPort); if (ftpClient.login(ftpUserName, ftpPassword)) { ftpClient.enterLocalPassiveMode(); fileOutputStream = new FileOutputStream(savingLocation + File.separator + fileName); outputStream = new BufferedOutputStream(fileOutputStream); ftpClient.changeWorkingDirectory(fileDirectory); if (ftpClient.retrieveFile(fileName, outputStream)) { response = "File uploaded to the device successfully ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_completed)); } else { response = "File uploaded to the device not completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_error)); } operation.setOperationResponse(response); } else { downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName, serverPort, fileDirectory); } } catch (FTPConnectionClosedException | ConnectException e) { downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName, serverPort, fileDirectory); } catch (IOException e) { handleOperationError(operation, fileTransferExceptionCause(e, fileName), e); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ignored) { } cleanupStreams(null, outputStream, null, fileOutputStream, null, null, null, null); } }
From source file:patcher.FXMLDocumentController.java
private void updateFiles(ArrayList<String> missing, FTPClient ftp) throws IOException { System.out.println(missing.size() + " new items found."); double step = 0.0; if (missing.size() > 0) { step = 100.0 / missing.size();//from w w w.ja v a 2 s .co m } double progressFill = 0.0; progress.setProgress(progressFill); for (String item : missing) { System.out.println("File missing, downloading: " + item); String remoteFile1 = folder + item; File downloadFile1 = new File(localdir + "/" + item); boolean success; try (OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1))) { success = ftp.retrieveFile(remoteFile1, outputStream1); } if (success) { System.out.println("File " + item + " has been downloaded successfully."); label.setText(item + " has been downloaded sucessfully"); progressFill += step; progress.setProgress(progressFill); } } progress.setProgress(100.0); System.out.println("Finished downloading missing files."); label.setText("Finished downloading missing files."); }
From source file:pl.psnc.synat.wrdz.zmd.download.adapters.FtpDownloadAdapter.java
/** * Downloads resource from the FTP server or throws exceptions if any problesmw ith download occur. * // w w w . j a v a 2s .co m * @param ftpClient * client instance to operate on. * @param cachedFilePath * path to the download destination in cache. * @param remotePath * path to the resource on the server. * @throws DownloadAdapterException * should any problems occur. */ private void downloadFromFtp(FTPClient ftpClient, String cachedFilePath, String remotePath) throws DownloadAdapterException { OutputStream output = null; try { output = new FileOutputStream(cachedFilePath); if (!ftpClient.retrieveFile(remotePath, output)) { throw new DownloadAdapterException( "Unable to download file, ftp server returned response code: " + ftpClient.getReplyCode()); } } catch (FileNotFoundException e) { throw new WrdzRuntimeException("Unable to create new file in cache.", e); } catch (IOException e) { throw new DownloadAdapterException("Exception while downloading the file - Unable to download ", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { throw new WrdzRuntimeException("Unable to close open output stream.", e); } } } }
From source file:rems.Global.java
public static String DownloadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName, String fullLocFileUrl, String userName, String password) { File f = new File(fullLocFileUrl); // get an ftpClient object FTPClient ftpClient = new FTPClient(); String responsTxt = ""; try {//from www .ja v a 2 s. c o m // pass directory path on server to connect ftpClient.connect(ftpserverurl, 21); // pass username and password, returned true if authentication is // successful boolean login = ftpClient.login(userName, password); if (login) { ftpClient.enterLocalPassiveMode(); //ftpClient.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(f)); boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, outputStream1); outputStream1.close(); //fos = new FileOutputStream(fullLocFileUrl); //boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, fos); responsTxt = ftpClient.getReplyString(); if (download) { responsTxt += "File downloaded successfully !"; } else { responsTxt += "Error in downloading file !::" + serverAppDirectory + PureFileName; } Global.updateLogMsg(Global.logMsgID, "\r\n\r\nDownload Response ==>\r\n" + responsTxt, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); Global.writeToLog(); // logout the user, returned true if logout successfully boolean logout = ftpClient.logout(); if (logout) { //System.out.println("Connection close..."); } } else { Global.errorLog += "Connection Failed..." + responsTxt; Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); Global.writeToLog(); } return responsTxt; } catch (SocketException e) { Global.errorLog += Arrays.toString(e.getStackTrace()); Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); Global.writeToLog(); } catch (IOException e) { Global.errorLog += Arrays.toString(e.getStackTrace()); Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); Global.writeToLog(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { Global.errorLog += Arrays.toString(e.getStackTrace()); Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); Global.writeToLog(); } finally { } } Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + responsTxt, Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID); return responsTxt; }
From source file:s32a.Client.Startup.FTPHandler.java
/** * Retrieves server and codebase info from FTP server. * Codebase will need to be queried separately afterwards. * @return // w w w .j ava2s. com */ public List<ServerInfo> getFTPData() { FTPClient client = null; FileInputStream fis = null; FileOutputStream fos = null; List<ServerInfo> output = new ArrayList<>(); if (SSL) { client = new FTPSClient(false); } else { client = new FTPClient(); } try { System.out.println("connecting"); client.connect(ftpServer); boolean login = client.login(this.username, this.password); System.out.println("login: " + login); client.enterLocalPassiveMode(); // Reads codebase file from server File codebase = new File("codebase.properties"); fos = new FileOutputStream(codebase.getAbsolutePath()); client.retrieveFile("/Airhockey/Codebase/codebase.properties", fos); fos.close(); this.codebaseURL = this.readCodebaseInfo(codebase); // Retrieves all currently active files from server File server = null; for (FTPFile f : client.listFiles("/Airhockey/Servers")) { server = new File(f.getName()); fos = new FileOutputStream(server); client.retrieveFile("/Airhockey/Servers/" + f.getName(), fos); fos.close(); output.add(this.readServerFile(server)); } //Removes null entries output.remove(null); client.logout(); } catch (IOException ex) { System.out.println("IOException: " + ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { System.out.println("exception caught: " + ex.getMessage()); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return output; }
From source file:s32a.Server.Startup.FTPHandler.java
/** * Registers/* ww w . j av a2s. c o m*/ * * @param input The server info to be registered * @return The url that should be used as java for codebase purposes */ public String registerServer(ServerInfo input) { File infoFile = this.saveInfoToFile(input); if (infoFile == null || infoFile.length() == 0) { showDialog("Error", "No file to store: " + infoFile.getAbsolutePath()); //System.out.println("No file to store: " + infoFile.getAbsolutePath()); return null; } FTPClient client = null; FileInputStream fis = null; FileOutputStream fos = null; String output = null; if (SSL) { client = new FTPSClient(false); } else { client = new FTPClient(); } try { System.out.println("connecting"); client.connect(ftpServer); boolean login = client.login(this.username, this.password); System.out.println("login: " + login); client.enterLocalPassiveMode(); fis = new FileInputStream(infoFile); this.ftpRefLocation = "/Airhockey/Servers/" + input.getIP() + "-" + input.getBindingName() + ".server"; client.storeFile(this.ftpRefLocation, fis); File codebase = new File("codebase.properties"); fos = new FileOutputStream(codebase.getAbsolutePath()); client.retrieveFile("/Airhockey/Codebase/codebase.properties", fos); fos.close(); output = this.readCodebaseInfo(codebase); client.logout(); } catch (IOException ex) { showDialog("Error", "FTP: IOException " + ex.getMessage()); // System.out.println("IOException: " + ex.getMessage()); // ex.printStackTrace(); } catch (Exception ex) { showDialog("Error", "FTP: Exception: " + ex.getMessage()); //System.out.println("exception caught: " + ex.getMessage()); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } client.disconnect(); infoFile.delete(); } catch (IOException e) { e.printStackTrace(); } } return output; }