List of usage examples for org.apache.commons.net.ftp FTPClient disconnect
@Override public void disconnect() throws IOException
From source file:dk.dma.dmiweather.service.FTPLoader.java
/** * Check for files every 10 minutes. New files are given to the gridWeatherService *//* w w w . j av a2 s.co m*/ @Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000) public void checkFiles() { log.info("Checking FTP files at DMI."); FTPClient client = new FTPClient(); try { client.setDataTimeout(20 * 1000); client.setBufferSize(1024 * 1024); client.connect(hostname); if (client.login("anonymous", "")) { try { client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); for (ForecastConfiguration configuration : configurations) { // DMI creates a Newest link once all files have been created if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) { if (client.getReplyCode() != 250) { log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode()); } String workingDirectory = new File(client.printWorkingDirectory()).getName(); String previousNewest = newestDirectories.get(configuration); if (!workingDirectory.equals(previousNewest)) { // a new directory for this configuration is available on the server FTPFile[] listFiles = client.listFiles(); List<FTPFile> files = Arrays.stream(listFiles) .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches()) .collect(Collectors.toList()); try { Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory, files); gridWeatherService.newFiles(localFiles, configuration); } catch (IOException e) { log.warn("Unable to get new weather files from DMI", e); } if (previousNewest != null) { File previous = new File(tempDirLocation, previousNewest); deleteRecursively(previous); } newestDirectories.put(configuration, workingDirectory); } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to change ftp directory to {}", configuration.getFolder()); } } } finally { try { client.logout(); } catch (IOException e) { log.info("Failed to logout", e); } } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to login to {}", hostname); } } catch (IOException e) { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to update weather files from DMI", e); } finally { try { client.disconnect(); } catch (IOException e) { log.info("Failed to disconnect", e); } } log.info("Check completed."); }
From source file:com.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java
@Override public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog) throws SearchLibException { String server = properties.getValue(propServer); String path = properties.getValue(propPath); String login = properties.getValue(propLogin); String password = properties.getValue(propPassword); String fileNamePattern = properties.getValue(propFileNamePattern); boolean deleteAfterLoad = Boolean.TRUE.toString().equals(properties.getValue(propDeleteAfterLoad)); boolean truncateWhenFilesFound = Boolean.TRUE.toString() .equals(properties.getValue(propTruncateIndexWhenFilesFound)); Pattern pattern = null;//from www.j a v a 2 s.co m if (fileNamePattern != null && fileNamePattern.length() > 0) pattern = Pattern.compile(fileNamePattern); String p = properties.getValue(propBuffersize); String xsl = properties.getValue(propXsl); File xmlTempResult = null; int bufferSize = 50; if (p != null && p.length() > 0) bufferSize = Integer.parseInt(p); HttpDownloader httpDownloader = client.getWebCrawlMaster().getNewHttpDownloader(true); FTPClient ftp = null; InputStream inputStream = null; try { // FTP Connection ftp = new FTPClient(); checkConnect(ftp, server, login, password); FTPFile[] files = ftp.listFiles(path, new FtpFileInstance.FtpInstanceFileFilter(true, false, null)); if (files == null) return; // Sort by ascendant filename String[] fileNames = new String[files.length]; int i = 0; for (FTPFile file : files) fileNames[i++] = file.getName(); Arrays.sort(fileNames); int ignored = 0; int loaded = 0; boolean bAlreadyTruncated = false; for (String fileName : fileNames) { String filePathName = FilenameUtils.concat(path, fileName); if (pattern != null) if (!pattern.matcher(fileName).find()) { ignored++; continue; } if (truncateWhenFilesFound && !bAlreadyTruncated) { client.deleteAll(); bAlreadyTruncated = true; } taskLog.setInfo("Working on: " + filePathName); inputStream = ftp.retrieveFileStream(filePathName); Node xmlDoc = null; if (xsl != null && xsl.length() > 0) { xmlTempResult = File.createTempFile("ossftpfeed", ".xml"); DomUtils.xslt(new StreamSource(inputStream), xsl, xmlTempResult); xmlDoc = DomUtils.readXml(new StreamSource(xmlTempResult), false); } else xmlDoc = DomUtils.readXml(new StreamSource(inputStream), false); client.updateXmlDocuments(xmlDoc, bufferSize, null, httpDownloader, taskLog); client.deleteXmlDocuments(xmlDoc, bufferSize, taskLog); inputStream.close(); inputStream = null; if (!ftp.completePendingCommand()) throw new SearchLibException("FTP Error"); if (xmlTempResult != null) { xmlTempResult.delete(); xmlTempResult = null; } checkConnect(ftp, server, login, password); if (deleteAfterLoad) ftp.deleteFile(filePathName); loaded++; } taskLog.setInfo(loaded + " file(s) loaded - " + ignored + " file(s) ignored"); } catch (XPathExpressionException e) { throw new SearchLibException(e); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (ParserConfigurationException e) { throw new SearchLibException(e); } catch (SAXException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (TransformerException e) { throw new SearchLibException(e); } finally { if (xmlTempResult != null) xmlTempResult.delete(); IOUtils.close(inputStream); try { if (ftp != null) if (ftp.isConnected()) ftp.disconnect(); } catch (IOException e) { Logging.warn(e); } if (httpDownloader != null) httpDownloader.release(); } }
From source file:GestoSAT.GestoSAT.java
@Schedule(dayOfWeek = "Sun-Sat", month = "*", hour = "22", dayOfMonth = "*", year = "*", minute = "0", second = "0", persistent = true) public void generarCopia() { // http://chuwiki.chuidiang.org/index.php?title=Backup_de_MySQL_con_Java try {/* ww w . ja v a 2 s. c om*/ Process p = Runtime.getRuntime().exec("mysqldump -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h " + mySQL.elementAt(0) + " -P " + mySQL.elementAt(1) + " gestosat"); InputStream is = p.getInputStream(); FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql"); byte[] buffer = new byte[1000]; int leido = is.read(buffer); while (leido > 0) { fos.write(buffer, 0, leido); leido = is.read(buffer); } fos.close(); //http://www.javamexico.org/blogs/lalo200/pequeno_ejemplo_para_subir_un_archivo_ftp_con_la_libreria_commons_net FTPClient clienteFTP = new FTPClient(); // Lanza excepcin si el servidor no existe clienteFTP.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1))); if (clienteFTP.login(confSeg.elementAt(2), confSeg.elementAt(3))) { clienteFTP.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql")); clienteFTP.enterLocalPassiveMode(); clienteFTP.storeFile("backupGestoSAT.sql", buffIn); buffIn.close(); clienteFTP.logout(); clienteFTP.disconnect(); } else System.out.println("Error de conexin FTP"); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.netpace.aims.controller.application.WapApplicationHelper.java
public static boolean wapFTPZipFile(File transferFile) throws AimsException { log.debug("wapFTPZipFile FTP Start. FileName: " + transferFile.getName()); boolean loginStatus = false; boolean dirChanged = false; FileInputStream transferStream = null; FTPClient ftpClient = new FTPClient(); ConfigEnvProperties envProperties = ConfigEnvProperties.getInstance(); //ftp server config String ftpServerAddress = envProperties.getProperty("wap.images.ftp.server.address"); String ftpUser = envProperties.getProperty("wap.images.ftp.user.name"); String ftpPassword = envProperties.getProperty("wap.images.ftp.user.password"); String ftpWorkingDirectory = envProperties.getProperty("wap.images.ftp.working.dir"); //general exception for ftp transfer AimsException aimsException = new AimsException("Error"); aimsException.addException(new AimsException("error.wap.app.ftp.transfer")); String errorMessage = ""; boolean transfered = false; try {//from w ww . j a v a 2 s. com ftpClient.connect(ftpServerAddress); loginStatus = ftpClient.login(ftpUser, ftpPassword); log.debug("Connection to server " + ftpServerAddress + " " + (loginStatus ? "success" : "failure")); if (loginStatus) { dirChanged = ftpClient.changeWorkingDirectory(ftpWorkingDirectory); log.debug("change remote directory to " + ftpWorkingDirectory + ": " + dirChanged); if (dirChanged) { transferStream = new FileInputStream(transferFile); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); transfered = ftpClient.storeFile(transferFile.getName(), transferStream); log.debug(transferFile.getName() + " transfered: " + transfered + " on server: " + ftpServerAddress); if (!transfered) { errorMessage = "File: " + transferFile.getName() + " not transfered to " + (ftpServerAddress + "/" + ftpServerAddress); System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } else { errorMessage = "Directory: " + ftpWorkingDirectory + " not found in " + ftpServerAddress; System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } //end loginstatus else { errorMessage = "FTP Authentication failed. \n\nServer: " + ftpServerAddress + "\nUserID: " + ftpUser + "\nPassword: " + ftpPassword; System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } //end try catch (FileNotFoundException e) { System.out.println("Exception: " + transferFile.getName() + " not found in temp directory"); e.printStackTrace();//zip file not found throw aimsException; } catch (IOException ioe) { System.out.println("Exception: Error in connection " + ftpServerAddress); ioe.printStackTrace(); sendFTPErrorMail("Error in connection to : " + ftpServerAddress + "\n\n" + MiscUtils.getExceptionStackTraceInfo(ioe)); throw aimsException; } finally { try { //close stream if (transferStream != null) { transferStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { //logout. Issues QUIT command ftpClient.logout(); } catch (IOException ioex) { ioex.printStackTrace(); } finally { try { //disconnect ftp session ftpClient.disconnect(); } catch (IOException ioexc) { ioexc.printStackTrace(); } } } } } log.debug("wapFTPZipFile FTP end. FileName: " + transferFile.getName() + "\t transfered: " + transfered); return transfered; }
From source file:GestoSAT.GestoSAT.java
public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo) throws Exception { FileReader file;/*from w w w .ja v a 2s. com*/ try { this.iva = Math.abs(iva); BufferedImage image = null; byte[] imageByte; BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(logo.split(",")[1]); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); // write the image to a file File outputfile = new File("logo"); String formato = logo.split("/")[1].split(";")[0]; ImageIO.write(image, formato, outputfile); // MySQL if (mySQL.elementAt(0).equals(this.mySQL.elementAt(0))) { if (!mySQL.elementAt(1).equals(this.mySQL.elementAt(1)) && !mySQL.elementAt(2).equals(this.mySQL.elementAt(2)) && (!mySQL.elementAt(3).equals(this.mySQL.elementAt(3)) || !mySQL.elementAt(0).equals(""))) { Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection("jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); } } else { // Comprobar que pass != "" Process pGet = Runtime.getRuntime() .exec("mysqldump -u " + this.mySQL.elementAt(2) + " -p" + this.mySQL.elementAt(3) + " -h " + this.mySQL.elementAt(0) + " -P " + this.mySQL.elementAt(1) + " gestosat"); InputStream is = pGet.getInputStream(); FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql"); byte[] bufferOut = new byte[1000]; int leido = is.read(bufferOut); while (leido > 0) { fos.write(bufferOut, 0, leido); leido = is.read(bufferOut); } fos.close(); Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection( "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); Process pPut = Runtime.getRuntime() .exec("mysql -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h " + mySQL.elementAt(0) + " -P " + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + " gestosat"); OutputStream os = pPut.getOutputStream(); FileInputStream fis = new FileInputStream("backupGestoSAT.sql"); byte[] bufferIn = new byte[1000]; int escrito = fis.read(bufferIn); while (escrito > 0) { os.write(bufferIn, 0, leido); escrito = fis.read(bufferIn); } os.flush(); os.close(); fis.close(); } // FTP FTPClient cliente = new FTPClient(); if (!confSeg.elementAt(3).equals("")) { cliente.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1))); if (cliente.login(confSeg.elementAt(2), confSeg.elementAt(3))) { cliente.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql")); cliente.enterLocalPassiveMode(); cliente.storeFile("backupGestoSAT.sql", buffIn); buffIn.close(); cliente.logout(); cliente.disconnect(); this.confSeg = confSeg; } else return false; } File archConf = new File("confGestoSAT"); BufferedWriter bw = new BufferedWriter(new FileWriter(archConf)); bw.write(this.mySQL.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.mySQL.elementAt(1))) + ";" + this.mySQL.elementAt(2) + ";" + this.mySQL.elementAt(3) + ";" + this.confSeg.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.confSeg.elementAt(1))) + ";" + this.confSeg.elementAt(2) + ";" + this.confSeg.elementAt(3) + ";" + Math.abs(iva)); bw.close(); return true; } catch (Exception ex) { file = new FileReader("confGestoSAT"); BufferedReader b = new BufferedReader(file); String cadena; cadena = b.readLine(); String[] valores = cadena.split(";"); this.mySQL.add(valores[0]); this.mySQL.add(Math.abs(Integer.parseInt(valores[1])) + ""); this.mySQL.add(valores[2]); this.mySQL.add(valores[3]); con.close(); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager .getConnection("jdbc:mysql://" + this.mySQL.elementAt(0) + ":" + this.mySQL.elementAt(1) + "/gestosat?user=" + this.mySQL.elementAt(2) + "&password=" + this.mySQL.elementAt(3)); this.confSeg.add(valores[4]); this.confSeg.add(Math.abs(Integer.parseInt(valores[5])) + ""); this.confSeg.add(valores[6]); this.confSeg.add(valores[7]); file.close(); Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:com.thebigbang.ftpclient.FTPOperation.java
/** * will force keep the device turned on for all the operation duration. * @param params/*from ww w.j a va2s. c om*/ * @return */ @SuppressLint("Wakelock") @SuppressWarnings("deprecation") @Override protected Boolean doInBackground(FTPBundle... params) { Thread.currentThread().setName("FTPOperationWorker"); for (final FTPBundle bundle : params) { FTPClient ftp = new FTPClient(); PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client"); try { // setup ftp connection: InetAddress addr = InetAddress.getByName(bundle.FTPServerHost); //set here the timeout. TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() { @Override public void Occurred(TimeoutException e) { bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; publishProgress(bundle); } }); timeout.start(); ftp.connect(addr, bundle.FTPServerPort); int reply = ftp.getReplyCode(); timeout.Stop(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("connection refuse"); } ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword); if (bundle.OperationType == FTPOperationType.Connect) { bundle.OperationStatus = FTPOperationStatus.Succed; publishProgress(bundle); continue; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); w.acquire(); // then switch between enum of operation types. if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.GetData) { String finalFPFi = bundle.LocalFilePathName; // The remote filename to be downloaded. if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") { File f = new File(bundle.LocalWorkingDirectory); f.mkdirs(); finalFPFi = bundle.LocalWorkingDirectory + finalFPFi; } FileOutputStream fos = new FileOutputStream(finalFPFi); // Download file from FTP server String finalFileN = bundle.RemoteFilePathName; if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") { finalFileN = bundle.RemoteWorkingDirectory + finalFileN; } boolean b = ftp.retrieveFile(finalFileN, fos); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; fos.close(); } else if (bundle.OperationType == FTPOperationType.SendData) { InputStream istr = new FileInputStream(bundle.LocalFilePathName); ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr); istr.close(); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; } else if (bundle.OperationType == FTPOperationType.DeleteData) { throw new IOException("DeleteData is Not yet implemented"); } ftp.disconnect(); // then finish/return. //publishProgress(bundle); } catch (IOException e) { e.printStackTrace(); bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; } try { w.release(); } catch (RuntimeException ex) { ex.printStackTrace(); } publishProgress(bundle); } return true; }
From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java
public FTPClient getFtpClient() throws IOException { FTPClient aClient = new FTPClient(); // Debug output // aClient.addProtocolCommandListener(new PrintCommandListener(new // PrintWriter(System.out), true)); if (activeExternalIPAddress != null) { aClient.setActiveExternalIPAddress(activeExternalIPAddress); }//w w w. jav a 2 s . c o m if (activeMinPort != null && activeMaxPort != null) { aClient.setActivePortRange(activeMinPort, activeMaxPort); } if (autodetectUTF8 != null) { aClient.setAutodetectUTF8(autodetectUTF8); } if (bufferSize != null) { aClient.setBufferSize(bufferSize); } if (charset != null) { aClient.setCharset(charset); } if (connectTimeout != null) { aClient.setConnectTimeout(connectTimeout); } if (controlEncoding != null) { aClient.setControlEncoding(controlEncoding); } if (controlKeepAliveReplyTimeout != null) { aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } if (controlKeepAliveTimeout != null) { aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout); } if (dataTimeout != null) { aClient.setDataTimeout(dataTimeout); } if (defaultPort != null) { aClient.setDefaultPort(defaultPort); } if (defaultTimeout != null) { aClient.setDefaultTimeout(defaultTimeout); } if (fileStructure != null) { aClient.setFileStructure(fileStructure); } if (keepAlive != null) { aClient.setKeepAlive(keepAlive); } if (listHiddenFiles != null) { aClient.setListHiddenFiles(listHiddenFiles); } if (parserFactory != null) { aClient.setParserFactory(parserFactory); } if (passiveLocalIPAddress != null) { aClient.setPassiveLocalIPAddress(passiveLocalIPAddress); } if (passiveNatWorkaround != null) { aClient.setPassiveNatWorkaround(passiveNatWorkaround); } if (proxy != null) { aClient.setProxy(proxy); } if (receieveDataSocketBufferSize != null) { aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize); } if (receiveBufferSize != null) { aClient.setReceiveBufferSize(receiveBufferSize); } if (remoteVerificationEnabled != null) { aClient.setRemoteVerificationEnabled(remoteVerificationEnabled); } if (reportActiveExternalIPAddress != null) { aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress); } if (sendBufferSize != null) { aClient.setSendBufferSize(sendBufferSize); } if (sendDataSocketBufferSize != null) { aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize); } if (strictMultilineParsing != null) { aClient.setStrictMultilineParsing(strictMultilineParsing); } if (tcpNoDelay != null) { aClient.setTcpNoDelay(tcpNoDelay); } if (useEPSVwithIPv4 != null) { aClient.setUseEPSVwithIPv4(useEPSVwithIPv4); } if (systemKey != null) { FTPClientConfig aClientConfig = new FTPClientConfig(systemKey); if (defaultDateFormat != null) { aClientConfig.setDefaultDateFormatStr(defaultDateFormat); } if (recentDateFormat != null) { aClientConfig.setRecentDateFormatStr(recentDateFormat); } if (serverLanguageCode != null) { aClientConfig.setServerLanguageCode(serverLanguageCode); } if (shortMonthNames != null) { aClientConfig.setShortMonthNames(shortMonthNames); } if (serverTimeZoneId != null) { aClientConfig.setServerTimeZoneId(serverTimeZoneId); } aClient.configure(aClientConfig); } if (LOGGER.isInfoEnabled()) { LOGGER.info("Connecting to : {}", host); } if (port == null) { aClient.connect(host); } else { aClient.connect(host, port); } int aReplyCode = aClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(aReplyCode)) { aClient.disconnect(); throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode); } try { if (localPassiveMode) { aClient.enterLocalPassiveMode(); } boolean aIsLoggedIn = false; if (account == null) { aIsLoggedIn = aClient.login(username, password); } else { aIsLoggedIn = aClient.login(username, password, account); } if (!aIsLoggedIn) { throw new IOException(aClient.getReplyString()); } } catch (IOException e) { aClient.disconnect(); throw e; } if (fileTransferMode != null) { aClient.setFileTransferMode(fileTransferMode); } if (fileType != null) { aClient.setFileType(fileType); } return aClient; }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String FTPGetFile(String sServer, String sSrcFileName, String sDstFileName, OutputStream out) { byte[] buffer = new byte[4096]; int nRead = 0; long lTotalRead = 0; String sRet = sErrorPrefix + "FTP Get failed for " + sSrcFileName; String strRet = ""; int reply = 0; FileOutputStream outStream = null; String sTmpDstFileName = fixFileName(sDstFileName); FTPClient ftp = new FTPClient(); try {//from w w w. j a va 2 s . c o m ftp.connect(sServer); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { ftp.login("anonymous", "b@t.com"); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { ftp.enterLocalPassiveMode(); if (ftp.setFileType(FTP.BINARY_FILE_TYPE)) { File dstFile = new File(sTmpDstFileName); outStream = new FileOutputStream(dstFile); FTPFile[] ftpFiles = ftp.listFiles(sSrcFileName); if (ftpFiles.length > 0) { long lFtpSize = ftpFiles[0].getSize(); if (lFtpSize <= 0) lFtpSize = 1; InputStream ftpIn = ftp.retrieveFileStream(sSrcFileName); while ((nRead = ftpIn.read(buffer)) != -1) { lTotalRead += nRead; outStream.write(buffer, 0, nRead); strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received " + ((lTotalRead * 100) / lFtpSize) + "% completed"; out.write(strRet.getBytes()); out.flush(); } ftpIn.close(); @SuppressWarnings("unused") boolean bRet = ftp.completePendingCommand(); outStream.flush(); outStream.close(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); } else { strRet = sRet; } } ftp.logout(); ftp.disconnect(); sRet = "\n" + strRet; } else { ftp.disconnect(); System.err.println("FTP server refused login."); } } else { ftp.disconnect(); System.err.println("FTP server refused connection."); } } catch (SocketException e) { sRet = e.getMessage(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); sRet += "\n" + strRet; e.printStackTrace(); } catch (IOException e) { sRet = e.getMessage(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); sRet += "\n" + strRet; e.printStackTrace(); } return (sRet); }
From source file:com.ibm.cics.ca1y.Emit.java
/** * Get the contents of a file from an FTP server. * //w w w . j ava 2 s . c o m * @param filename * - * @param server * - * @param useraname * - * @param userpassword * - * @param transfer * - * @param mode * - * @param epsv * - * @param protocol * - * @param trustmgr * - * @param datatimeout * - * @param proxyserver * - * @param proxyusername * - * @param proxypassword * - * @param anonymouspassword * - * @return byte[] representing the retrieved file, null otherwise. */ private static byte[] getFileUsingFTP(String filename, String server, String username, String userpassword, String transfer, String mode, String epsv, String protocol, String trustmgr, String datatimeout, String proxyserver, String proxyusername, String proxypassword, String anonymouspassword) { FTPClient ftp; if (filename == null || server == null) return null; int port = 0; if (server != null) { String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (Exception _ex) { } } } int proxyport = 0; if (proxyserver != null) { String parts[] = proxyserver.split(":"); if (parts.length == 2) { proxyserver = parts[0]; try { proxyport = Integer.parseInt(parts[1]); } catch (Exception _ex) { } } } if (username == null) { username = "anonymous"; if (userpassword == null) userpassword = anonymouspassword; } if (protocol == null) { if (proxyserver != null) ftp = new FTPHTTPClient(proxyserver, proxyport, proxyusername, proxypassword); else ftp = new FTPClient(); } else { FTPSClient ftps = null; if ("true".equalsIgnoreCase(protocol)) { ftps = new FTPSClient(true); } else if ("false".equalsIgnoreCase(protocol)) { ftps = new FTPSClient(false); } else if (protocol != null) { String parts[] = protocol.split(","); if (parts.length == 1) ftps = new FTPSClient(protocol); else ftps = new FTPSClient(parts[0], Boolean.parseBoolean(parts[1])); } ftp = ftps; if ("all".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(null); } } if (datatimeout != null) { try { ftp.setDataTimeout(Integer.parseInt(datatimeout)); } catch (Exception _ex) { ftp.setDataTimeout(-1); } } if (port <= 0) { port = ftp.getDefaultPort(); } if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append(Emit.messages.getString("FTPAboutToGetFileFromServer")).append(" - ").append("file name:") .append(filename).append(",server:").append(server).append(":").append(port) .append(",username:").append(username).append(",userpassword:") .append(userpassword != null && !"anonymous".equals(username) ? "<obscured>" : userpassword) .append(",transfer:").append(transfer).append(",mode:").append(mode).append(",epsv:") .append(epsv).append(",protocol:").append(protocol).append(",trustmgr:").append(trustmgr) .append(",datatimeout:").append(datatimeout).append(",proxyserver:").append(proxyserver) .append(":").append(proxyport).append(",proxyusername:").append(proxyusername) .append(",proxypassword:").append(proxypassword != null ? "<obscured>" : null); logger.fine(sb.toString()); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer")); return null; } } catch (IOException _ex) { logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer")); if (ftp.isConnected()) try { ftp.disconnect(); } catch (IOException _ex2) { } return null; } ByteArrayOutputStream output; try { if (!ftp.login(username, userpassword)) { ftp.logout(); logger.warning(Emit.messages.getString("FTPServerRefusedLoginCredentials")); return null; } if ("binary".equalsIgnoreCase(transfer)) { ftp.setFileType(2); } else { ftp.setFileType(0); } if ("localactive".equalsIgnoreCase(mode)) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4("true".equalsIgnoreCase(epsv)); output = new ByteArrayOutputStream(); ftp.retrieveFile(filename, output); output.close(); ftp.noop(); ftp.logout(); } catch (IOException _ex) { logger.warning(Emit.messages.getString("FTPFailedToTransferFile")); if (ftp.isConnected()) try { ftp.disconnect(); } catch (IOException _ex2) { } return null; } return output.toByteArray(); }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToFTPserver(final Activity activity, final Handler handler, final String latestVideoFile_filename, final String latestVideoFile_absolutepath, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doVideoFTP starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FTP); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. // FTP; connect preferences here! ////from ww w. j ava 2 s. c o m SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); String ftpHostName = prefs.getString("defaultFTPhostPreference", null); String ftpUsername = prefs.getString("defaultFTPusernamePreference", null); String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null); // use name of local file. String ftpRemoteFtpFilename = latestVideoFile_filename; // FTP FTPClient ftpClient = new FTPClient(); InetAddress uploadhost = null; try { uploadhost = InetAddress.getByName(ftpHostName); } catch (UnknownHostException e1) { // If DNS resolution fails then abort immediately - show // dialog to // inform user first. e1.printStackTrace(); Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed."); uploadhost = null; } if (uploadhost == null) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean connected = false; try { ftpClient.connect(uploadhost); connected = true; } catch (SocketException e) { e.printStackTrace(); connected = false; } catch (UnknownHostException e) { // e.printStackTrace(); connected = false; } catch (IOException e) { // e.printStackTrace(); connected = false; } if (!connected) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean reply = false; try { reply = ftpClient.login(ftpUsername, ftpPassword); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp.login - video uploading failed."); } // check the reply code here // If we cant login, abort after showing user a dialog. if (!reply) { try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); } // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } // Set File type to binary try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { // e.printStackTrace(); // keep going?! } // BEYOND HERE DONT USE DIALOGS! // Construct the input stream to send to Ftp server, from the // local // video file on the sd card BufferedInputStream buffIn = null; File file = new File(latestVideoFile_absolutepath); try { buffIn = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { // e.printStackTrace(); Log.e(TAG, " got exception on local video file - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... return; } ftpClient.enterLocalPassiveMode(); try { // UPLOAD THE LOCAL VIDEO FILE. ftpClient.storeFile(ftpRemoteFtpFilename, buffIn); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on storeFile - video uploading failed."); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { buffIn.close(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on buff.close - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.logout(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp logout - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp disconnect - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } if (emailAddress != null && ftpHostName != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_)); } }, 0); } }); t.start(); return t; }