List of usage examples for org.apache.commons.net.ftp FTPClient storeFile
public boolean storeFile(String remote, InputStream local) throws IOException
From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java
/** * The 'FTPTargetFile' function will get the FTP details and send off the generated file * * @param batchId The id of the batch to FTP the file for *///from www . ja v a 2 s. co m private void FTPTargetFile(int batchId, configurationTransport transportDetails) throws Exception { try { /* Update the status of the batch to locked */ transactionOutDAO.updateBatchStatus(batchId, 22); List<transactionTarget> targets = transactionOutDAO.getTransactionsByBatchDLId(batchId); if (!targets.isEmpty()) { for (transactionTarget target : targets) { /* Need to update the uploaded batch status */ transactionInManager.updateBatchStatus(target.getbatchUploadId(), 22, ""); /* Need to update the uploaded batch transaction status */ transactionInManager.updateTransactionStatus(target.getbatchUploadId(), target.gettransactionInId(), 0, 37); /* Update the downloaded batch transaction status */ transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 37); } } /* get the batch details */ batchDownloads batchFTPFileInfo = transactionOutDAO.getBatchDetails(batchId); /* Get the FTP Details */ configurationFTPFields ftpDetails = configurationTransportManager .getTransportFTPDetailsPush(transportDetails.getId()); if ("SFTP".equals(ftpDetails.getprotocol())) { JSch jsch = new JSch(); Session session = null; ChannelSftp channel = null; FileInputStream localFileStream = null; String user = ftpDetails.getusername(); int port = ftpDetails.getport(); String host = ftpDetails.getip(); Organization orgDetails = organizationManager.getOrganizationById( configurationManager.getConfigurationById(transportDetails.getconfigId()).getorgId()); if (ftpDetails.getcertification() != null && !"".equals(ftpDetails.getcertification())) { File newFile = null; fileSystem dir = new fileSystem(); dir.setDir(orgDetails.getcleanURL(), "certificates"); jsch.addIdentity(new File(dir.getDir() + ftpDetails.getcertification()).getAbsolutePath()); session = jsch.getSession(user, host, port); } else if (ftpDetails.getpassword() != null && !"".equals(ftpDetails.getpassword())) { session = jsch.getSession(user, host, port); session.setPassword(ftpDetails.getpassword()); } session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(2000); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); if (ftpDetails.getdirectory() != null && !"".equals(ftpDetails.getdirectory())) { channel.cd(ftpDetails.getdirectory()); String fileName = null; int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf("."); if (findExt >= 0) { fileName = batchFTPFileInfo.getoutputFIleName(); } else { fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".") .append(transportDetails.getfileExt()).toString(); } //Set the directory to save the brochures to fileSystem dir = new fileSystem(); String filelocation = transportDetails.getfileLocation(); filelocation = filelocation.replace("/bowlink/", ""); dir.setDirByName(filelocation); File file = new File(dir.getDir() + fileName); if (file.exists()) { FileInputStream fileInput = new FileInputStream(file); channel.put(fileInput, fileName); } } channel.disconnect(); session.disconnect(); } else { FTPClient ftp; if ("FTP".equals(ftpDetails.getprotocol())) { ftp = new FTPClient(); } else { FTPSClient ftps; ftps = new FTPSClient(true); ftp = ftps; ftps.setTrustManager(null); } ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultTimeout(3000); ftp.setConnectTimeout(3000); if (ftpDetails.getport() > 0) { ftp.connect(ftpDetails.getip(), ftpDetails.getport()); } else { ftp.connect(ftpDetails.getip()); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } else { ftp.login(ftpDetails.getusername(), ftpDetails.getpassword()); ftp.enterLocalPassiveMode(); String fileName = null; int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf("."); if (findExt >= 0) { fileName = batchFTPFileInfo.getoutputFIleName(); } else { fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".") .append(transportDetails.getfileExt()).toString(); } //Set the directory to save the brochures to fileSystem dir = new fileSystem(); String filelocation = transportDetails.getfileLocation(); filelocation = filelocation.replace("/bowlink/", ""); dir.setDirByName(filelocation); File file = new File(dir.getDir() + fileName); FileInputStream fileInput = new FileInputStream(file); ftp.changeWorkingDirectory(ftpDetails.getdirectory()); ftp.storeFile(fileName, fileInput); ftp.logout(); ftp.disconnect(); } } // we should delete file now that we ftp'ed the file try { fileSystem dir = new fileSystem(); String filelocation = transportDetails.getfileLocation(); filelocation = filelocation.replace("/bowlink/", ""); dir.setDirByName(filelocation); File sourceFile = new File(dir.getDir() + batchFTPFileInfo.getoutputFIleName()); if (sourceFile.exists()) { sourceFile.delete(); } transactionOutDAO.updateBatchStatus(batchId, 23); for (transactionTarget target : targets) { /* Need to update the uploaded batch status */ transactionInManager.updateBatchStatus(target.getbatchUploadId(), 23, ""); /* Need to update the uploaded batch transaction status */ transactionInManager.updateTransactionStatus(target.getbatchUploadId(), target.gettransactionInId(), 0, 20); /* Update the downloaded batch transaction status */ transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 20); } } catch (Exception e) { throw new Exception( "Error occurred during FTP - delete file and update statuses. batchId: " + batchId, e); } } catch (Exception e) { throw new Exception("Error occurred trying to FTP a batch target. batchId: " + batchId, e); } }
From source file:com.hdfstoftp.main.HdfsToFtp.java
/** * ?//from w w w . ja va 2s.co m * * @param srcFS * * @param src * ? * @param dst * * @param queryStr * * @param deleteSource * ?? * @param overwrite * ???? * @return boolean * @throws Exception */ private static boolean copyFromHDFSToFTP(Config config) throws Exception { // ?hdfs Configuration conf = new Configuration(); FileSystem srcFS = FileSystem.get(conf); long start = System.currentTimeMillis(); boolean isRename = config.isRenameUploaded(); int retryTimes = config.getRetryTimes(); // ? String dstPath = config.getDestDir(); Path src = new Path(config.getSouceDir()); FileStatus fileStatus = srcFS.getFileStatus(src); String subDir = null; if (fileStatus.isDirectory()) {// if (isRename) {// ??rename subDir = Config.RENAME_DIR; srcFS.mkdirs(new Path(fileStatus.getPath(), subDir)); } int threadNum = config.getThreadNum(); // ExecutorService threadPool = Executors.newFixedThreadPool(threadNum); // ?ftp FTPClientPool ftpPool = new FTPClientPool(threadNum, new FtpClientFactory(config.getFTPClientConfig())); FTPClient ftpClient = ftpPool.borrowObject(); // ? ftpClient.makeDirectory(dstPath); ftpPool.returnObject(ftpClient); // ?? FileStatus contents[] = srcFS.listStatus(src); long beginFilter = 0; long endFileter = 0; if (config.getCommandLine().hasOption("d") || config.getCommandLine().hasOption("h") || config.getCommandLine().hasOption("t")) {// ?"[" beginFilter = System.currentTimeMillis(); Long[] timeRange = parseTimeRange(config.getCommandLine()); contents = getNewContents(timeRange, contents); endFileter = System.currentTimeMillis(); } // ? if (config.getCommandLine().hasOption("r")) {// "["?? beginFilter = System.currentTimeMillis(); contents = getFilterContents(config.getCommandLine().getOptionValue("r").trim(), contents); endFileter = System.currentTimeMillis(); } logger.info("total file count:" + contents.length); Map<String, String> fileNameMap = null; long beginSkip = 0; long endSkip = 0; boolean overwrite = true; if (config.getCommandLine().hasOption("o")) { overwrite = "true".equals(config.getCommandLine().getOptionValue("o").trim()); } if (!overwrite) {// ????? beginSkip = System.currentTimeMillis(); fileNameMap = getFileNameMap(dstPath, ftpPool); endSkip = System.currentTimeMillis(); } int skiped = 0; List<Future<?>> futureList = new ArrayList<Future<?>>(); for (int i = 0; i < contents.length; i++) { if (!overwrite && fileNameMap.containsKey(contents[i].getPath().getName())) { // skiped++; Log.info("skiped filename:" + contents[i].getPath().getName()); continue; } if (contents[i].isDirectory()) { continue; } // ??? Future<?> future = threadPool.submit(new UploadFileTask(srcFS, contents[i].getPath(), new Path(dstPath, contents[i].getPath().getName()), ftpPool, false, isRename, subDir, retryTimes)); futureList.add(future); } int transfered = 0; int failed = 0; for (Future<?> future : futureList) { Boolean computeResult = (Boolean) future.get(); if (computeResult) { transfered++; if (transfered % 50 == 0 || transfered == contents.length) { logger.info("have transfered:" + transfered + " files"); } } else { failed++; logger.error("failed transter:" + failed + " files"); } } // threadPool.shutdown(); // FTPCient ftpPool.close(); // **************** logger.info("filter time:" + (endFileter - beginFilter) + " ms"); if (!overwrite) { logger.info("skip time:" + (endSkip - beginSkip) + " ms"); } logger.info("total file count:" + contents.length); logger.info("total transtered: " + transfered + ",total failed:" + failed + ",total skiped:" + skiped); } else {// BufferedReader reader = null; FtpClientFactory facotry = new FtpClientFactory(config.getFTPClientConfig()); FTPClient ftpClient = null; InputStream in = null; try { Path path = fileStatus.getPath(); if (!path.getName().contains("log")) { } reader = new BufferedReader(new FileReader(new File(path.toUri().getPath()))); String str = null; ftpClient = facotry.makeObject(); while ((str = reader.readLine()) != null) { String[] feilds = str.split("&"); Path filePath = null; if (feilds.length == 2 && feilds[1] != "") { filePath = new Path(feilds[1]); in = srcFS.open(filePath); boolean result = ftpClient.storeFile(dstPath, in); System.out.println(ftpClient.getReplyCode()); if (result) { logger.info(filePath.toString()); } else { logger_failed.info(filePath.toString()); } } else { continue; } } } catch (Exception e) { e.printStackTrace(); } finally { in.close(); reader.close(); facotry.destroyObject(ftpClient); } } long end = System.currentTimeMillis(); logger.info("finished transfer,total time:" + (end - start) / 1000 + "s"); return true; }
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 . jav a2s . 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:GestoSAT.GestoSAT.java
public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo) throws Exception { FileReader file;/*w w w .ja va 2 s. c om*/ 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.o6Systems.utils.net.FTPModule.java
private int executeFtpCommand(String[] args) throws UnknownHostException { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;/*from w w w . j av a2 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; String username = null; String password = null; int base = 0; // Print the command System.out.println("----------FTP MODULE CALL----------"); for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } System.out.println("--------------------"); // 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("-A")) { username = "anonymous"; password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName(); } 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 (username != null) { minParams -= 2; } String server = args[base++]; int port = 0; String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); } if (username == null) { username = args[base++]; password = args[base++]; } String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } 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")) { ftps = new FTPSClient(true); } else if (protocol.equals("false")) { ftps = new FTPSClient(false); } else { String prot[] = protocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } ftp = ftps; if ("all".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { 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."); return 1; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); return 1; } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should default to ASCII // but they don't all do so - see NET-500 ftp.setFileType(FTP.ASCII_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 (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.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } return error ? 1 : 0; }
From source file:com.droid.app.fotobot.FotoBot.java
public boolean files_to_ftp(List<String> FTP_files) { String server;// ww w. j a v a 2 s. c o 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.bdaum.zoom.net.core.ftp.FtpAccount.java
@SuppressWarnings("fallthrough") private int transferFiles(FTPClient ftp, File[] files, IProgressMonitor monitor, IAdaptable adaptable, boolean deleteTransferred) throws IOException { if (monitor.isCanceled()) return -1; FTPFile[] oldfiles = ftp.listFiles(); if (monitor.isCanceled()) return -1; Map<String, FTPFile> names = new HashMap<String, FTPFile>(); for (FTPFile file : oldfiles) names.put(file.getName(), file); int n = 0;// www . j a v a 2 s . co m for (File file : files) { final String filename = file.getName(); FTPFile ftpFile = names.get(filename); if (file.isDirectory()) { if (ftpFile != null) { if (!ftpFile.isDirectory()) throw new IOException( NLS.bind(Messages.FtpAccount_cannot_replace_file_with_subdir, filename)); boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename)); if (!result) throw new IOException(NLS.bind(Messages.FtpAccount_cannot_change_to_working_dir, filename)); // System.out.println(filename + " is new directory"); //$NON-NLS-1$ } else { ftp.makeDirectory(filename); boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename)); if (!result) throw new IOException(Messages.FtpAccount_creation_of_subdir_failed); // System.out.println(filename + " is new directory"); //$NON-NLS-1$ } if (monitor.isCanceled()) return -1; int c = transferFiles(ftp, file.listFiles(), monitor, adaptable, deleteTransferred); if (c < 0) return -1; n += c; ftp.changeToParentDirectory(); // System.out.println("Returned to parent directory"); //$NON-NLS-1$ } else { if (ftpFile != null) { if (ftpFile.isDirectory()) throw new IOException( NLS.bind(Messages.FtpAccount_cannot_replace_subdir_with_file, filename)); if (skipAll) { if (deleteTransferred) file.delete(); continue; } if (!replaceAll) { if (monitor.isCanceled()) return -1; int ret = 4; IDbErrorHandler errorHandler = Core.getCore().getErrorHandler(); if (errorHandler != null) { String[] buttons = (filecount > 1) ? new String[] { Messages.FtpAccount_overwrite, Messages.FtpAccount_overwrite_all, IDialogConstants.SKIP_LABEL, Messages.FtpAccount_skip_all, IDialogConstants.CANCEL_LABEL } : new String[] { Messages.FtpAccount_overwrite, IDialogConstants.SKIP_LABEL, IDialogConstants.CANCEL_LABEL }; ret = errorHandler.showMessageDialog(Messages.FtpAccount_file_already_exists, null, NLS.bind(Messages.FtpAccount_file_exists_overwrite, filename), MessageDialog.QUESTION, buttons, 0, adaptable); } if (filecount > 1) { switch (ret) { case 0: break; case 1: replaceAll = true; break; case 3: skipAll = true; /* FALL-THROUGH */ case 2: if (deleteTransferred) file.delete(); continue; default: return -1; } } else { switch (ret) { case 0: break; case 1: if (deleteTransferred) file.delete(); continue; default: return -1; } } } ftp.deleteFile(Core.encodeUrlSegment(filename)); // System.out.println(filename + " deleted"); //$NON-NLS-1$ } try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { ftp.storeFile(Core.encodeUrlSegment(filename), in); // System.out.println(filename + " stored"); //$NON-NLS-1$ n++; } finally { if (deleteTransferred) file.delete(); monitor.worked(1); } } } return n; }
From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java
public void upload(RunFileTransferEntity runFileTransferEntity) { log.debug("Start FTPUtil upload"); FTPClient ftpClient = new FTPClient(); ftpClient.enterLocalPassiveMode();/* ww w . j a v a 2 s . c o m*/ ftpClient.setBufferSize(1024000); int retryAttempt = runFileTransferEntity.getRetryAttempt(); int attemptCount = 1; int i = 0; InputStream inputStream = null; boolean login = false; File filecheck = new File(runFileTransferEntity.getInputFilePath()); log.info("input file name" + filecheck.getName()); if (runFileTransferEntity.getFailOnError()) { if (!(filecheck.isFile() || filecheck.isDirectory()) && !(runFileTransferEntity.getInputFilePath().contains("hdfs://"))) { log.error("Invalid input file path. Please provide valid input file path."); throw new FTPUtilException("Invalid input file path"); } } boolean done = false; for (i = 0; i < retryAttempt; i++) { try { log.info("Connection attempt: " + (i + 1)); if (runFileTransferEntity.getTimeOut() != 0) if (runFileTransferEntity.getEncoding() != null) ftpClient.setControlEncoding(runFileTransferEntity.getEncoding()); ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut()); log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n" + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno" + runFileTransferEntity.getPortNo()); ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo()); login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword()); if (!login) { log.error("Invalid FTP details provided. Please provide correct FTP details."); throw new FTPUtilException("Invalid FTP details"); } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (runFileTransferEntity.getInputFilePath().contains("hdfs://")) { log.debug("Processing for HDFS input file path"); String inputPath = runFileTransferEntity.getInputFilePath(); String s1 = inputPath.substring(7, inputPath.length()); String s2 = s1.substring(0, s1.indexOf("/")); int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); File f = new File("/tmp"); if (!f.exists()) f.mkdir(); Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://" + s2); FileSystem hdfsFileSystem = FileSystem.get(conf); Path local = new Path("/tmp"); String s = inputPath.substring(7, inputPath.length()); String hdfspath = s.substring(s.indexOf("/"), s.length()); File dir = new File(hdfspath); Random ran = new Random(); String tempFolder = "ftp_sftp_" + System.nanoTime() + "_" + ran.nextInt(1000); File dirs = new File("/tmp/" + tempFolder); boolean success = dirs.mkdirs(); if (hdfsFileSystem.isDirectory(new Path(hdfspath))) { log.debug("Provided HDFS input path is for directory."); InputStream is = null; OutputStream os = null; String localDirectory = hdfspath.substring(hdfspath.lastIndexOf("/") + 1); FileStatus[] fileStatus = hdfsFileSystem .listStatus(new Path(runFileTransferEntity.getInputFilePath())); Path[] paths = FileUtil.stat2Paths(fileStatus); try { String folderName = hdfspath.substring(hdfspath.lastIndexOf("/") + 1); Path hdfs = new Path(hdfspath); for (Path file : paths) { is = hdfsFileSystem.open(file); os = new BufferedOutputStream( new FileOutputStream(dirs + "" + File.separatorChar + file.getName())); IOUtils.copyBytes(is, os, conf); } ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); ftpClient.removeDirectory(folderName); ftpClient.makeDirectory(folderName); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath().replaceAll( Matcher.quoteReplacement("\\"), "/") + File.separatorChar + folderName); for (File files : dirs.listFiles()) { if (files.isFile()) ftpClient.storeFile(files.getName().toString(), new BufferedInputStream(new FileInputStream(files))); } } catch (IOException e) { log.error("Failed while doing FTP file", e); //throw e; } finally { IOUtils.closeStream(is); IOUtils.closeStream(os); if (dirs != null) { FileUtils.deleteDirectory(dirs); } } } else { try { Path hdfs = new Path(hdfspath); hdfsFileSystem.copyToLocalFile(false, hdfs, local); inputStream = new FileInputStream(dirs + file_name); ftpClient.storeFile(file_name, new BufferedInputStream(inputStream)); } catch (Exception e) { log.error("Failed while doing FTP file", e); throw new FTPUtilException("Failed while doing FTP file", e); } finally { FileUtils.deleteDirectory(dirs); } } } else { java.nio.file.Path file = new File(runFileTransferEntity.getInputFilePath()).toPath(); if (Files.isDirectory(file)) { log.debug("Provided input file path is for directory"); File dir = new File(runFileTransferEntity.getInputFilePath()); String folderName = new File(runFileTransferEntity.getInputFilePath()).getName(); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); try { ftpClient.removeDirectory(folderName); } catch (IOException e) { log.error("Failed while doing FTP file", e); throw new FTPUtilException("Failed while doing FTP file", e); } ftpClient.makeDirectory(folderName); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + folderName); for (File files : dir.listFiles()) { if (files.isFile()) ftpClient.storeFile(files.getName().toString(), new BufferedInputStream(new FileInputStream(files))); } } else { inputStream = new FileInputStream(runFileTransferEntity.getInputFilePath()); ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/")); int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); ftpClient.storeFile(file_name, new BufferedInputStream(inputStream)); } } } catch (Exception e) { log.error("Failed while doing FTP file", e); if (!login && runFileTransferEntity.getFailOnError()) { throw new FTPUtilException("Invalid FTP details"); } try { Thread.sleep(runFileTransferEntity.getRetryAfterDuration()); } catch (Exception e1) { log.error("Failed while sleeping for retry duration", e1); } continue; } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException ioe) { } } done = true; break; } try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception e) { log.error("Failed while clossing the connection", e); } catch (Error e) { log.error("Failed while clossing the connection", e); //throw new RuntimeException(e); } if (runFileTransferEntity.getFailOnError() && !done) { log.error("File transfer failed"); throw new FTPUtilException("File transfer failed"); } else if (!done) { log.error("File transfer failed but mentioned fail on error as false"); } log.debug("Finished FTPUtil upload"); }
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! //// w ww . j a v a 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; }
From source file:net.yacy.grid.io.assets.FTPStorageFactory.java
public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread) throws IOException { this.server = server; this.username = username == null ? "" : username; this.password = password == null ? "" : password; this.port = port; this.deleteafterread = deleteafterread; this.ftpClient = new Storage<byte[]>() { @Override/*w ww . j a v a2 s.co m*/ public void checkConnection() throws IOException { return; } private FTPClient initConnection() throws IOException { FTPClient ftp = new FTPClient(); ftp.setDataTimeout(3000); ftp.setConnectTimeout(20000); if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) { ftp.connect(FTPStorageFactory.this.server); } else { ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port); } ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("bad connection to ftp server: " + reply); } if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("login failure"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(8192); return ftp; } @Override public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException { long t0 = System.currentTimeMillis(); FTPClient ftp = initConnection(); try { long t1 = System.currentTimeMillis(); String file = cdPath(ftp, path); long t2 = System.currentTimeMillis(); ftp.enterLocalPassiveMode(); boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset)); long t3 = System.currentTimeMillis(); if (!success) throw new IOException("storage to path " + path + " was not successful (storeFile=false)"); Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = " + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2)); } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return FTPStorageFactory.this; } @Override public Asset<byte[]> load(String path) throws IOException { FTPClient ftp = initConnection(); ByteArrayOutputStream baos = null; byte[] b = null; try { String file = cdPath(ftp, path); baos = new ByteArrayOutputStream(); ftp.retrieveFile(file, baos); b = baos.toByteArray(); if (FTPStorageFactory.this.deleteafterread) try { boolean deleted = ftp.deleteFile(file); FTPFile[] remaining = ftp.listFiles(); if (remaining.length == 0) { ftp.cwd("/"); if (path.startsWith("/")) path = path.substring(1); int p = path.indexOf('/'); if (p > 0) path = path.substring(0, p); ftp.removeDirectory(path); } } catch (Throwable e) { Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e); } } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return new Asset<byte[]>(FTPStorageFactory.this, b); } @Override public void close() { } private String cdPath(FTPClient ftp, String path) throws IOException { int success_code = ftp.cwd("/"); if (success_code >= 300) throw new IOException("cannot cd into " + path + ": " + success_code); if (path.length() == 0 || path.equals("/")) return ""; if (path.charAt(0) == '/') path = path.substring(1); // we consider that all paths are absolute to / (home) int p; while ((p = path.indexOf('/')) > 0) { String dir = path.substring(0, p); int code = ftp.cwd(dir); if (code >= 300) { // path may not exist, try to create the path boolean success = ftp.makeDirectory(dir); if (!success) throw new IOException("unable to create directory " + dir + " for path " + path); code = ftp.cwd(dir); if (code >= 300) throw new IOException("unable to cwd into directory " + dir + " for path " + path); } path = path.substring(p + 1); } return path; } }; }