/** * Passive mode is OFF by default. The value is taken from the connector settings. In case there * are any overriding properties set on the endpoint, those will be used. * * @see #setPassive(boolean) */ public void enterActiveOrPassiveMode(FTPClient client, UMOImmutableEndpoint endpoint) { // well, no endpoint URI here, as we have to use the most common denominator // in API :( final String passiveString = (String) endpoint.getProperty(FtpConnector.PROPERTY_PASSIVE_MODE); if (passiveString == null) { // try the connector properties then if (isPassive()) { if (logger.isTraceEnabled()) { logger.trace("Entering FTP passive mode"); } client.enterLocalPassiveMode(); } else { if (logger.isTraceEnabled()) { logger.trace("Entering FTP active mode"); } client.enterLocalActiveMode(); } } else { // override with endpoint's definition final boolean passiveMode = Boolean.valueOf(passiveString).booleanValue(); if (passiveMode) { if (logger.isTraceEnabled()) { logger.trace("Entering FTP passive mode (endpoint override)"); } client.enterLocalPassiveMode(); } else { if (logger.isTraceEnabled()) { logger.trace("Entering FTP active mode (endpoint override)"); } client.enterLocalActiveMode(); } } }
public void uploadFile(String name, InputStream input) throws Exception { ftp.enterLocalPassiveMode(); ftp.changeWorkingDirectory(DEFAULT_WORKING_DIR); Logger.log("HCS " + hcs.getLabel() + ": Current directory is " + ftp.printWorkingDirectory()); ftp.enterLocalPassiveMode(); ftp.storeFile(name, input); ftp.logout(); ftp.disconnect(); Logger.log("HCS " + hcs.getLabel() + ": Upload of ppEngine.dat complete!"); }
/** * @param host * @param port * @param ftpUser * @param ftpPassword * @throws FtpException */ private void conn(String host, int port, String ftpUser, String ftpPassword) throws FtpException { try { ftp.connect(host, port); boolean islogin = ftp.login(ftpUser, ftpPassword); if (!islogin) { close(); throw new FtpException("Login Host Fail!"); } String passiveMode = CIAConfig.get("FTPPASSIVEMODE"); if (passiveMode != null && passiveMode.equals("remote")) { ftp.enterRemotePassiveMode(); } if (passiveMode != null && passiveMode.equals("local")) { ftp.enterLocalPassiveMode(); } System.out.println( host + " Login Host Succ,Current Path[ " + ftp.printWorkingDirectory() + "]"); } catch (FtpException ex) { close(); logger.info("FTP server initializtion error." + host); throw new FtpException("ftp init error!!" + ex.getMessage()); } catch (Exception ex) { close(); logger.info("FTP server initializtion error." + host); throw new FtpException("ftp init error!!" + ex.getMessage()); } }
@Deprecated private FTPClient initFtpClientAndLogin() throws SocketException, IOException { if (oFtp != null) { return oFtp; } FTPClient oFtp = new FTPClient(); int iReply; oFtp.connect(_sFtpHost); iReply = oFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(iReply)) { log.setError("Could not connect to ftp host" + _sFtpHost); return null; } if (!oFtp.login(_sFtpUserName, _sFtpPassword)) { log.error( "Could not login with user `" + _sFtpUserName + "` and password `" + _sFtpPassword + "`"); oFtp.disconnect(); return null; } oFtp.enterLocalPassiveMode(); return oFtp; }
private void initFTPFile() { try { String path = getURL().getPath(); // 如果且以"/"结尾,去掉"/" if (path.endsWith("/")) { path = path.substring(0, path.lastIndexOf('/')); } // 资源在服务器中所属目录 String checkPath = path.substring(0, path.lastIndexOf('/')); // 如果所属目录为根目录 if (checkPath.length() == 0) { checkPath = "/"; } String fileName = path.substring(path.lastIndexOf('/')); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); ftpClient.enterLocalPassiveMode(); // 从上级目录的子目录中过滤出当前资源 FTPFile[] files = ftpClient.listFiles(recode(checkPath), new FtpFileFilterByName(fileName)); if (files != null && files.length == 1) { ftpFile = files[0]; } else { throw new TinySysRuntimeException("查找资源失败,url=" + getURL()); } } catch (Exception e) { throw new VFSRuntimeException(e); } }
/** * @param path ex:/upload/2023 * @param filename xxx.jpg * @param input 输入流 * @return */ public static boolean uploadFile(String path, String filename, InputStream input) { boolean success = false; FTPClient ftpClient = null; try { ftpClient = getFTPClient(); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { return success; } // 使用二进制上传 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpCreateDirectoryTree(ftpClient, path); success = ftpClient.storeFile(filename, input); input.close(); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != ftpClient && ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; }
/** * @param host * @param ftpUser * @param ftpPassword * @throws FtpException */ private void conn(String host, String ftpUser, String ftpPassword) throws FtpException { try { ftp.connect(host); boolean islogin = ftp.login(ftpUser, ftpPassword); if (!islogin) { throw new FtpException("login FTP Host Fail!"); } String passiveMode = CIAConfig.get("FTPPASSIVEMODE"); if (passiveMode != null && passiveMode.equals("remote")) { ftp.enterRemotePassiveMode(); } if (passiveMode != null && passiveMode.equals("local")) { ftp.enterLocalPassiveMode(); } } catch (FtpException ex) { close(); logger.info("FTP server initializtion error." + host); throw new FtpException("ftp init error!!" + ex.getMessage()); } catch (Exception ex) { close(); logger.info("FTP server initializtion error." + host); throw new FtpException("ftp init error!!" + ex.getMessage()); } }
public static FTPClient getFTPClient() { FTPClient client = ftpClientThreadLocal.get(); if (client != null && client.isConnected()) { return client; } ftpClientThreadLocal.remove(); FTPClient ftpClient = new FTPClient(); // 创建ftpClient ftpClient.setControlEncoding("UTF-8"); // 设置字符编码 Boolean isConnect = connectFtp(ftpClient); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.setSoTimeout(1000 * 30); } catch (Exception e) { e.printStackTrace(); } // 得到返回答复码 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } else { ftpClientThreadLocal.set(ftpClient); } return ftpClient; }
private void login() throws IOException { if (!isConnected()) { connect(); } ftpClient.login(user, password); if (passiveMode) { ftpClient.enterLocalPassiveMode(); } // PDF transmitted with ASCII file type break the file ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setBufferSize(0); ftpClient.setControlKeepAliveTimeout(timeOutInSeconds); }
public boolean open() { boolean isSuccessful = false; if (isOpen) { throw new IllegalStateException("Is already open, must be closed before!"); } try { int reply; ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new IOException("Can't connect!"); } if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) { ftpClient.logout(); throw new IOException("Can't login!"); } if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) { ftpClient.logout(); throw new IOException("Can't change directory!"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); isSuccessful = true; } catch (Exception e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { // do nothing } } isSuccessful = false; } isOpen = isSuccessful; return isSuccessful; }
public static void main(String[] args) { String server = "localhost"; int port = 16885; String user = "******"; String pass = "******"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); showServerReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Operation failed. Server reply code: " + replyCode); return; } boolean success = ftpClient.login(user, pass); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); showServerReply(ftpClient); if (!success) { System.out.println("Could not login to the server"); return; } else { System.out.println("LOGGED IN SERVER"); ftpClient.changeWorkingDirectory("C:\\Users\\Dileep\\Desktop\\temp"); // File outFile = new File("C:\\Users\\Dileep\\Desktop\\temp\\newFolder","NewFile.txt"); ftpClient.enterLocalPassiveMode(); // FileOutputStream outputStream = new FileOutputStream(outFile); InputStream fileInputStream = ftpClient.retrieveFileStream("Dileep.txt"); manipulateFile(fileInputStream); /*if (ftpClient.retrieveFile("Dileep.txt", outputStream)){ outputStream.close(); }*/ } ftpClient.logout(); } catch (IOException ex) { System.out.println("Oops! Something wrong happened"); ex.printStackTrace(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
public static void main(String[] args) { String server = "192.168.1.72"; int port = 21; String user = "******"; String pass = "******"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #1: uploads first file using an InputStream File firstLocalFile = new File("D:/Shridhar/FolderTest/ItmtuResponsestatus_2012_1_18_15"); String firstRemoteFile = "/home/ftp/"; InputStream inputStream = new FileInputStream(firstLocalFile); System.out.println("Start uploading first file"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { System.out.println("The first file is uploaded successfully."); } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { // ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
private void ftpFile(OrdersDocument ordsDoc, String filename, String warehouse) { // if (ordsDoc.validate()) { // FTP try { FTPClient ftp = new FTPClient(); if (isTest) { ftp.connect(Messages.getString(warehouse + "_testftp")); // $NON-NLS-1$ ftp.login( Messages.getString(warehouse + "_testusername"), Messages.getString(warehouse + "_testpassword")); // $NON-NLS-1$ //$NON-NLS-2$ } else { ftp.connect(Messages.getString(warehouse + "_ftp")); // $NON-NLS-1$ ftp.login( Messages.getString(warehouse + "_username"), Messages.getString(warehouse + "_password")); // $NON-NLS-1$ //$NON-NLS-2$ } System.out.println("Reply Code: " + ftp.getReplyCode()); // $NON-NLS-1$ if ("ACTIVE".equalsIgnoreCase(Messages.getString(warehouse + "_mode"))) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.changeWorkingDirectory("ship"); // $NON-NLS-1$ boolean success = ftp.storeFile( filename, new FileInputStream(Messages.getString("directory") + filename)); // $NON-NLS-1$ System.out.println("FTP Success? " + success); // $NON-NLS-1$ ftp.disconnect(); System.out.println("Complete"); // $NON-NLS-1$ } catch (SocketException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // } }
/** * download file from remote host and display the downloaded percentage * * @param folder remote directory * @param fileName the file you want to download * @param destfolder the destination folder you will store the file */ public void downloadFileInProgress(String folder, String fileName, String destfolder) { try { ftp.enterLocalPassiveMode(); ftp.changeWorkingDirectory(folder); LogUtils.log("Changing to directory:[" + folder + "]"); String realFile = destfolder + File.separator + fileName; File localFile = new File(realFile); FileOutputStream fos = new FileOutputStream(localFile); LogUtils.log("Start downloading.."); FTPFile[] fs = ftp.listFiles(); DecimalFormat df = new DecimalFormat("#.00%"); for (FTPFile f : fs) { if (f.getName().equals(fileName)) { InputStream is = ftp.retrieveFileStream(f.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); long transfered = 0, total = f.getSize(); double ratio = 0.0; while (line != null) { byte[] buff = line.getBytes(); transfered += buff.length; if (transfered * 1.0 / total - ratio >= 0.01) { ratio = transfered * 1.0 / total; LogUtils.log("Download size : " + df.format(ratio)); } fos.write(buff); line = br.readLine(); } is.close(); ftp.logout(); ftp.disconnect(); LogUtils.log("Download done!"); } } fos.close(); } catch (IOException e) { e.printStackTrace(); } }
public static void append( String server, String username, String password, String remotePath, InputStream is) throws IOException { FTPClient mFtp = new FTPClient(); try { mFtp.connect(server, FTP.DEFAULT_PORT); mFtp.login(username, password); mFtp.setFileType(FTP.BINARY_FILE_TYPE); mFtp.enterLocalPassiveMode(); mFtp.appendFile(remotePath, is); } finally { try { if (mFtp.isConnected()) { mFtp.logout(); mFtp.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
public static void main(String[] args) throws IOException { OLAFile olaFile = new OLAFile( 19, 56, 51, "1111333355557777", "P161486", "M", "AG", "Nanninga", "Testweg", "12", "9439 HW", "Achterwoude", "987654", "Flipje Betuwe"); String server = "192.168.55.2"; FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); InputStream inputStream = olaFile.getInputStream(); System.out.println("uploading file"); boolean done = ftp.storeFile("input/" + olaFile.getRef() + ".ola", inputStream); inputStream.close(); if (done) { System.out.println("uploaded file"); } else { System.out.println("upload failed"); } }
private void uploadDir(File directory) throws IOException { try { String[] children = directory.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (String filename : children) { File f = new File(directory, filename); if (f.isDirectory()) { ftpClient.mkd(f.getName()); ftpClient.changeWorkingDirectory(f.getName()); uploadDir(f); ftpClient.changeToParentDirectory(); } else { if (!uploaded.contains(filename)) { LOGGER.debug("uploading file: {}", filename); messageListener.addMessage(new Message("uploading file: " + filename)); ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); InputStream is = new BufferedInputStream(new FileInputStream(directory + "/" + filename)); ftpClient.storeFile(filename, is); uploaded.add(filename); } } } } } catch (IOException e) { LOGGER.error("Upload failure"); throw new IOException(e); } }
private synchronized void connect2Server() throws SocketException, IOException { if (oFtp == null) { this.oFtp = new FTPClient(); } if (log != null) { if (LogLevel.getValue(log.getLogLevel()).ordinal() > LogLevel.DEBUG.ordinal()) { oFtp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.err))); } } if (_port == 0) { oFtp.connect(this._sFtpHost, 21); } else { oFtp.connect(this._sFtpHost, _port); } if (!oFtp.login(this._sFtpUserName, this._sFtpPassword)) { logError("Can't login to server. FTP responce: " + oFtp.getReplyString()); } oFtp.enterLocalPassiveMode(); }
/** * download file from remote host without progress percentage display * * @param folder remote directory * @param fileName the file you want to download * @param destfolder the destination folder you will store the file */ public void downloadFile(String folder, String fileName, String destfolder) { try { ftp.enterLocalPassiveMode(); ftp.changeWorkingDirectory(folder); LogUtils.log("Changing to directory:[" + folder + "]"); String realFile = destfolder + File.separator + fileName; File localFile = new File(realFile); FileOutputStream fos = new FileOutputStream(localFile); FileInputStream fis = new FileInputStream(localFile); LogUtils.log("Start downloading.."); FTPFile[] fs = ftp.listFiles(); for (FTPFile f : fs) { if (f.getName().equals(fileName)) { ftp.retrieveFile(f.getName(), fos); LogUtils.log("Download done!"); break; } } fos.close(); } catch (IOException e) { e.printStackTrace(); } }
public String ftpGet( String remoteAddr, int remotePort, String remotePath, String remoteFileName, String localPath, String username, String password) throws SocketException, IOException { FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); try { ftp.connect(remoteAddr, remotePort); log.debug("Connected to " + remoteAddr + ":" + remotePort + ".\n" + ftp.getReplyString()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("FTP server refused connection."); throw new RuntimeException("FTP server refused connection."); } ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("FTP server refused connection."); throw new RuntimeException("FTP server refused connection."); } if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) { log.error("set BINARY_FILE_TYPE error."); throw new RuntimeException("FTP server refused connection."); } // ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE); ftp.enterLocalPassiveMode(); String remote = remotePath + "/" + remoteFileName; String local = localPath + "/" + remoteFileName; String returnName = genFileName(local); File f = new File(returnName); FileOutputStream fos = FileUtils.openOutputStream(f); try { long startTime = System.currentTimeMillis(); if (!ftp.retrieveFile(remote, fos)) { log.error("get " + remote + " error."); throw new RuntimeException("get " + remote + " error."); } log.debug("get remote file[" + remote + "], local file[" + local + "] ."); long finishedTime = System.currentTimeMillis(); log.debug("remote time :" + (finishedTime - startTime) / 1000f + " sec."); } finally { IOUtils.closeQuietly(fos); } ftp.logout(); return returnName; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
@Override protected Boolean doInBackground(String... arg0) { BiereDB biere = new BiereDB(); String nomBiere = eTnom.getText().toString(); biere.setNomBiere(nomBiere); String paysBiere = eTpays.getText().toString(); biere.setPaysBiere(paysBiere); String degre = eTdegre.getText().toString(); try { if (nomBiere.matches("") || paysBiere.matches("") || degre.matches("")) { throw new Exception( "Exception personnalisée/" + R.string.e218 + "/" + "Tous les champs doivent être remplis !"); } else { float degreBiere = Float.parseFloat(degre); biere.setDegreBiere(degreBiere); } } catch (Exception e) { ex = e; exc = true; } if (bitmap != null && exc != null) { FTPClient mFtp = new FTPClient(); try { mFtp.connect("ftp.alokar.site90.net", 21); // Using port no=21 mFtp.login("a7115779", "projet2013"); mFtp.enterLocalPassiveMode(); mFtp.setFileType(FTPClient.BINARY_FILE_TYPE); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, 100, stream); InputStream is = new ByteArrayInputStream(stream.toByteArray()); String cheminBiere = biere.getNomBiere().replace(' ', '_'); mFtp.storeFile("/public_html/BeerPictures/image_" + cheminBiere + ".jpg", is); biere.setCheminImage("/public_html/BeerPictures/image_" + cheminBiere + ".jpg"); is.close(); mFtp.disconnect(); } catch (Exception e) { ex = e; FTPpbm = true; } } if (!exc) { try { biere.create(); HistoriqueDB histo = new HistoriqueDB(0, user.getIdPersonne(), biere.getIdBiere(), "ajout"); histo.create(); } catch (Exception e) { ex = e; exc = true; } } return true; }
public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try { localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale)); } List<String> errorList = new LinkedList<String>(); FTPClient ftp = new FTPClient(); try { Integer defaultTimeout = (Integer) context.get("defaultTimeout"); if (UtilValidate.isNotEmpty(defaultTimeout)) { Debug.logInfo( "[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module); ftp.setDefaultTimeout(defaultTimeout.intValue()); } Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale)); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo( "[putFile] logging in: username="******", password="******"[putFile] login failed", module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale)); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo( "[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale)); } else { Debug.logInfo("[putFile] store was successful", module); List<String> siteCommands = checkList(context.get("siteCommands"), String.class); if (siteCommands != null) { for (String command : siteCommands) { Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add( UtilProperties.getMessage( resource, "CommonFtpSiteCommandFailed", UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()), locale)); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } finally { try { if (ftp.isConnected()) { ftp.disconnect(); } } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module); } try { localFile.close(); } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem closing local file: ", module); } } if (errorList.size() > 0) { Debug.logError( "[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
public boolean ftpDownload() { boolean status = false; final String username = "******"; final String password = "******"; final String hostname = "ftp.memelab.ca"; final int port = 21; String SFTPWORKINGDIR = "/public_html/jessescott/storage/android"; FTPClient ftp = new FTPClient(); try { ftp.connect(hostname, port); ftp.login(username, password); ftp.changeWorkingDirectory(SFTPWORKINGDIR); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(1024); ftp.enterLocalPassiveMode(); OutputStream output = null; FTPFile[] files = ftp.listFiles(); // Set Log Directory & File File logFile = new File(LOG_DIRECTORY + "logfile.txt"); Log.d("FTP", "LOG should exist at " + logFile.getAbsolutePath()); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } for (FTPFile f : files) { // Log Names Log.d("FTP", f.toFormattedString()); // Set Path String remoteFile = f.getName(); Log.d("FTP", "REMOTE file " + remoteFile); String localFile = MEDIA_DIRECTORY; localFile += remoteFile; Log.d("FTP", " is being put in LOCAL path " + localFile); output = new BufferedOutputStream(new FileOutputStream(localFile)); // Set Time Time now = new Time(Time.getCurrentTimezone()); now.setToNow(); // Set Logger BufferedWriter logger = new BufferedWriter(new FileWriter(logFile, true)); logger.append("Download for " + localFile + " started at " + now.format("%k:%M:%S")); logger.newLine(); Long startTime = System.currentTimeMillis(); // HTTP System.setProperty("http.keepAlive", "false"); // Get Files Boolean success = ftp.retrieveFile(remoteFile, output); status = success; if (success) { Log.d("FTP", "SUCCESS"); now.setToNow(); Long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; logger.append("Download for " + localFile + " finished at " + now.format("%k:%M:%S")); logger.newLine(); logger.append("for an elapsedTime of " + elapsedTime + " seconds"); logger.newLine(); logger.newLine(); } // Close Logger logger.flush(); logger.close(); // Close Buffer if (ftp != null) { output.close(); } } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } return status; }
@Override public Future<Set<File>> download(LayerRequest currentLayer) throws Exception { this.currentLayer = currentLayer; currentLayer.setMetadata(this.includesMetadata()); File directory = getDirectory(); Set<File> fileSet = new HashSet<File>(); List<String> urls = this.getUrls(currentLayer); for (String url : urls) { InputStream inputStream = null; URL currentURL = new URL(url); String ftpServerAddress = currentURL.getHost(); String currentPath = currentURL.getPath(); FTPClient ftp = new FTPClient(); int delimiterIndex = currentPath.lastIndexOf("/"); String remoteDirectory = currentPath.substring(0, delimiterIndex); String fileName = currentPath.substring(delimiterIndex + 1); try { int reply; ftp.connect(ftpServerAddress); // Although they are open FTP servers, in order to access the files, a anonymous login is // necessary. ftp.login("anonymous", "anonymous"); System.out.println("Connected to " + ftpServerAddress + "."); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } reply = ftp.getReplyCode(); // enter passive mode ftp.enterLocalPassiveMode(); // change current directory ftp.changeWorkingDirectory(remoteDirectory); // check if the file with given name exists in ftp server try { FTPFile[] ftpFiles = ftp.listFiles(fileName); if (ftpFiles != null && ftpFiles.length > 0) { for (FTPFile file : ftpFiles) { if (!file.isFile()) continue; System.out.println("Found file:" + file.getName()); // transfer the file inputStream = ftp.retrieveFileStream(file.getName()); // save the file and add to fileset // TODO: ftp file does not contain MIME type. File outputFile = OgpFileUtils.createNewFileFromDownload(fileName, "ZIP", directory); // FileUtils with a BufferedInputStream seems to be the fastest method with a small // sample size. requires more testing BufferedInputStream bufferedIn = null; try { bufferedIn = new BufferedInputStream(inputStream); FileUtils.copyInputStreamToFile(bufferedIn, outputFile); fileSet.add(outputFile); } finally { IOUtils.closeQuietly(bufferedIn); } } } } catch (IOException e) { e.printStackTrace(); } finally { ftp.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } IOUtils.closeQuietly(inputStream); } } return new AsyncResult<Set<File>>(fileSet); };
@Override public void execute(Map<String, InputView> arg0, Map<String, OutputView> arg1) { // get connection cred's and hostname String serverUri = getStringPropertyValue("Connection"); ResDef resdef = this.getLocalResourceObject(serverUri); String sourcedir = getStringPropertyValue("DirSource"); String targetdir = getStringPropertyValue("DirTarget"); FTPClient client = new FTPClient(); // ftps try { FTPSClient ftpsclient = new FTPSClient(); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } FTPFile[] files = null; try { client.connect(resdef.getPropertyValue("Host").toString()); client.login( resdef.getPropertyValue("Username").toString(), resdef.getPropertyValue("Password").toString()); client.enterLocalPassiveMode(); info(Boolean.toString(client.isConnected())); if (sourcedir != null) files = client.listFiles(sourcedir); else files = client.listFiles(); for (FTPFile f : files) { info(f.getName()); } } catch (SocketException e) { // TODO Auto-generated catch block // e.printStackTrace(); info(e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block info(e.getMessage()); } // Process input record InputView inView = arg0.values().iterator().next(); if (inView == null) { info("No input view"); } info("Input View: " + inView.getName()); String file = inView.readRecord().getString("FileName").toString(); info(file); // write files to local FS OutputStream output = null; for (int i = 0; i < files.length; i++) { if (files[i].getName().compareTo(file) == 0 || files[i].getName().compareTo("*") == 0) if (!files[i].getName().startsWith(".") && files[i].getType() != 1) { try { if (targetdir != null) output = new FileOutputStream(new File(targetdir + files[i].getName())); else output = new FileOutputStream(new File(files[i].getName())); client.retrieveFile(files[i].getName(), output); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } try { output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Create output view OutputView outputView = arg1.values().iterator().next(); Record outRec = outputView.createRecord(); for (int i = 0; i < files.length; i++) { outRec.set("Name", files[i].getName()); if (files[i].getType() == 0) outRec.set("Type", "Directory"); else outRec.set("Type", "File"); outRec.set("User", files[i].getUser()); outRec.set("Group", files[i].getGroup()); outRec.set("Size", Long.toString(files[i].getSize())); outRec.set("TimeStamp", files[i].getTimestamp().getTime().toString()); if (files[i].getName().compareTo(file) == 0) outputView.writeRecord(outRec); } outputView.completed(); info(file); }
@Override protected Integer doInBackground(Long... params) { // Log.w("LOGGER", "Starting...doInBackground"); try { actionBar.setProgressBarVisibility(ProgressBar.VISIBLE); con = new FTPClient(); try { String version_actualizar = ""; // set time out con.setConnectTimeout(9000); // Log.v("instalacion", "conectando"); con.connect("62.212.77.173"); // Log.v("instalacion", "conectado"); if (con.login("soda", "pepino")) { // Log.v("instalacion", "login"); con.enterLocalPassiveMode(); // important! Log.v("instalacion", "changeWorkingDirectory - " + con.printWorkingDirectory()); // con.changeWorkingDirectory("" + "tessdata" + ""); Log.v("instalacion", "changeWorkingDirectory - " + con.printWorkingDirectory()); String[] files = con.listNames(); FTPFile[] directories = con.listDirectories(); FTPFile[] archivos = con.listFiles(); for (int i = 0; i < directories.length; i++) { Log.v("instalacion", directories[i].getName().toString()); } for (int i = 0; i < archivos.length; i++) { Log.v("instalacion", archivos[i].getName().toString()); } // DESCARGA System.out.println(" --- Remote system is " + con.getSystemName()); con.setFileType(FTP.BINARY_FILE_TYPE); con.enterLocalPassiveMode(); filename = "tessdata.zip"; for (int i = 0; i < archivos.length; i++) { Log.v("----- instalacion", archivos[i].getName().toString()); if (archivos[i].getName().toString().equals(filename)) { size = archivos[i].getSize(); } } try { fos = new BufferedOutputStream( new FileOutputStream( Environment.getExternalStorageDirectory().toString() + "/" + filename)); // Log.i("instalacion"," FileOutputStream "); InputStream input = con.retrieveFileStream("tessdata.zip"); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... // publishProgress((int) (total * 100 / data.length)); publishProgress( Integer.valueOf((int) (((total * 100 / data.length) * 1000) / size))); // Log.i("instalacion", String.valueOf( (((int) (total * // 100 / data.length))*100)/size )); // publishProgress(count); fos.write(data, 0, count); } fos.flush(); fos.close(); con.logout(); con.disconnect(); } catch (Exception e) { // TODO: handle exception Log.e( "instalacion", "ERROR al obtener la actualizaci—n de Elara : " + e.getMessage() + " "); return -4; } } else { // Log.e("instalacion","Nombre usuario o contrase–a ftp no valido."); Log.e("instalacion", "Nombre usuario o contrase–a ftp no valido. "); return -5; } } catch (Exception e) { Log.e("instalacion", "ERROR de conexion : " + e.getMessage() + " "); return -2; } try { con.logout(); return 0; } catch (IOException e) { // Log.e("instalacion",e.getMessage()); Log.e("instalacion", "ERROR al desconectar del FTP : " + e.getMessage() + " "); return 0; } } catch (Exception e) { // Log.e("instalacion",e.getMessage()); Log.e( "instalacion", "ERROR al buscar actualizaciones de Elara: " + e.getMessage() + " "); return -1; } }