List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE
int BINARY_FILE_TYPE
To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.
Click Source Link
From source file:com.unispezi.cpanelremotebackup.ftp.FTPClient.java
/** * Will download the given file/* w ww .ja v a2 s. c o m*/ * @param filePath path on server * @param stream stream to write file data to * @param progressListener optional progress listener * @param totalFileBytes total file size in bytes, option if no progressListener is given */ public void downloadFile(String filePath, OutputStream stream, final ProgressListener progressListener, final long totalFileBytes) { String logString = "Downloading \"" + filePath + "\""; assertLoggedIn(logString); try { String origLogString = logString; logString = "Setting file type to binary"; //Patch over for handleException below Log.debug(logString); ftp.setFileType(FTP.BINARY_FILE_TYPE); Log.debug("Reply string was:" + ftp.getReplyString()); checkResult(ftp.getReplyCode(), logString); logString = origLogString; //Logout Log.debug(logString); if (progressListener != null) { ftp.setCopyStreamListener(new CopyStreamListener() { int lastPercentage = 0; @Override public void bytesTransferred(CopyStreamEvent event) { bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize()); } @Override public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { int currentPercentage = (int) (totalBytesTransferred * 100 / totalFileBytes); if (currentPercentage > lastPercentage) { lastPercentage = currentPercentage; progressListener.progressPercentageReached(currentPercentage); } } }); } ftp.retrieveFile(filePath, stream); Log.debug("Reply string was:" + ftp.getReplyString()); stream.close(); // Check for errors checkResult(ftp.getReplyCode(), logString); } catch (IOException e) { throw handleException(e, logString); } }
From source file:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {//from ww w . j a v a 2 s . c o m final DatabaseHelper db = new DatabaseHelper(context); SQLiteDatabase database = db.getWritableDatabase(); if (database == null) throw new IllegalStateException("Unable to open database!"); database.beginTransaction(); try { // Clear out the old data. database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null); // Connect to the web server and locate the FTP download link. Log.v(TAG, "Finding update: " + urls[0]); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Locating update..."); progress.setIndeterminate(true); } }); Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get(); URL dataURL = null; for (Element element : doc.select("a")) { if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) { dataURL = new URL(element.attr("href")); } } // Make sure the download URL was fund. if (dataURL == null) throw new FileNotFoundException("Unable to locate data URL."); // Connect to the FTP server and download the update. Log.v(TAG, "Downloading update: " + dataURL); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Downloading update..."); progress.setIndeterminate(true); } }); FTPClient ftp = new FTPClient(); try { ftp.setConnectTimeout(timeout * 1000); ftp.setDefaultTimeout(timeout * 1000); ftp.connect(dataURL.getHost()); ftp.enterLocalPassiveMode(); // After connection attempt, you should check the reply code // to verify success. if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new IOException("FTP server refused connection: " + ftp.getReplyString()); } // Login using the standard anonymous credentials. if (!ftp.login("anonymous", "anonymous")) { ftp.disconnect(); throw new IOException("FTP Error: " + ftp.getReplyString()); } Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream in = ftp.retrieveFileStream(dataURL.getFile()); if (in == null) throw new FileNotFoundException(dataURL.getFile() + " was not found!"); try { ZipInputStream zin = new ZipInputStream(in); try { // Locate the .dbf entry in the ZIP archive. ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().endsWith(entryName)) { readDBaseFile(zin, database); } else if (entry.getName().endsWith(shapeEntryName)) { locations = readShapeFile(zin); } } } finally { try { zin.close(); } catch (Exception e) { // Ignore this error. } } } finally { in.close(); } if (locations != null) { final int recordCount = locations.size(); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setIndeterminate(false); progress.setMessage("Updating locations..."); progress.setMax(recordCount); } }); int progress = 0; for (int recordNumber : locations.keySet()) { PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber); Location loc = locations.get(recordNumber); access.setLatitude(loc.getLatitude()); access.setLongitude(loc.getLongitude()); db.updatePublicAccess(access); publishProgress(++progress); } } } finally { if (ftp.isConnected()) ftp.disconnect(); } database.setTransactionSuccessful(); return db.getPublicAccessesCount(); } finally { database.endTransaction(); } } catch (Exception e) { error = e; Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e); return -1; } }
From source file:com.dinochiesa.edgecallouts.FtpPut.java
public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) { FtpCalloutResult info = new FtpCalloutResult(); try {//w ww . j a v a 2 s. c o m // The executes in the IO thread! String sourceVar = getSourceVar(messageContext); InputStream src = null; boolean wantBase64Decode = getWantBase64Decode(messageContext); if (sourceVar == null) { src = messageContext.getMessage().getContentAsStream(); // conditionally wrap a decoder around it if (wantBase64Decode) { src = new Base64InputStream(src); } } else { info.addMessage("Retrieving data from " + sourceVar); String sourceData = messageContext.getVariable(sourceVar); byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData) : sourceData.getBytes(StandardCharsets.UTF_8); src = new ByteArrayInputStream(b); } String remoteName = getRemoteFileName(messageContext); remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-"); String ftpServer = getFtpServer(messageContext); int ftpPort = getFtpPort(messageContext); String user = getFtpUser(messageContext); String password = getFtpPassword(messageContext); info.addMessage("connecting to server " + ftpServer); FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new FtpCommandListener(info)); ftp.connect(ftpServer, ftpPort); ftp.enterLocalPassiveMode(); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("The FTP server refused the connection."); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } if (!ftp.login(user, password)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("Login failure"); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } info.addMessage("logged in as " + user); String initialDirectory = getInitialDirectory(messageContext); if ((initialDirectory != null) && (!initialDirectory.equals(""))) { ftp.changeWorkingDirectory(initialDirectory); } ftp.setFileType(FTP.BINARY_FILE_TYPE); OutputStream os = ftp.storeFileStream(remoteName); if (os == null) { // cannot open output stream info.addMessage("cannot open output stream to " + remoteName); info.setStatus("FAIL"); } else { byte[] buf = new byte[2048]; int n; while ((n = src.read(buf)) > 0) { os.write(buf, 0, n); } os.close(); src.close(); boolean completed = ftp.completePendingCommand(); info.addMessage("transfer completed: " + completed); info.setStatus("OK"); } ftp.disconnect(); info.addMessage("All done."); messageContext.setVariable(varName("result"), info.toJsonString()); } catch (java.lang.Exception exc1) { if (getDebug()) { System.out.println(ExceptionUtils.getStackTrace(exc1)); } String error = exc1.toString(); messageContext.setVariable(varName("exception"), error); info.setStatus("FAIL"); info.addMessage(error); messageContext.setVariable(varName("result"), info.toJsonString()); int ch = error.lastIndexOf(':'); if (ch >= 0) { messageContext.setVariable(varName("error"), error.substring(ch + 2).trim()); } else { messageContext.setVariable(varName("error"), error); } messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1)); return ExecutionResult.ABORT; } return ExecutionResult.SUCCESS; }
From source file:hd3gtv.storage.AbstractFileBridgeFtp.java
public BufferedInputStream getInputStream(int buffersize) { try {//from w w w . j a v a 2 s . com ftpclient.setFileType(FTP.BINARY_FILE_TYPE); String fullpath = root_path + path; if (root_path.equals("/")) { fullpath = path; } InputStream is = ftpclient.retrieveFileStream(fullpath); if (is == null) { throw new NullPointerException("Retrieve File Stream is null"); } return new FTPClosableInputStream(is, buffersize); } catch (IOException e) { Log2.log.error("Can't access to file", e, this); } return null; }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
@Override public InputStream getInputStream() throws IOException { FTPClient f = null;//from ww w.j a v a 2s .c om try { f = ftpConnect(); f.setFileType(FTP.BINARY_FILE_TYPE); return f.retrieveFileStream(getPath()); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } finally { ftpQuietDisconnect(f); } }
From source file:facturacion.ftp.FtpServer.java
public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) { FTPClient ftpClient = new FTPClient(); boolean success = false; BufferedInputStream buffIn = null; try {/*from w ww .j ava 2 s.co m*/ ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken), Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken))); ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken), Config.getInstance().getProperty(Config.PassFtpToken)); ftpClient.enterLocalPassiveMode(); /*ftpClient.connect("127.0.0.1", 21); ftpClient.login("erpftp", "Tribut@2014");*/ ftpClient.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftpClient.getReplyCode(); System.out.println("Respuesta recibida de conexin FTP:" + reply); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println("Imposible conectarse al servidor"); return -1; } buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar ftpClient.enterLocalPassiveMode(); //crear directorio success = ftpClient.makeDirectory(hostDirServer); System.out.println("sucess 1 = " + success); success = ftpClient.makeDirectory(hostDirServer + "/img"); System.out.println("sucess 233 = " + success); success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn); System.out.println("sucess 3 = " + success); } catch (IOException ex) { } finally { try { if (ftpClient.isConnected()) { buffIn.close(); //Cerrar envio de arcivos al FTP ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { return -1; //ex.printStackTrace(); } } return (success) ? 1 : 0; }
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 {//from w w w .j a 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.symbian.driver.plugins.ftptelnet.FtpTransfer.java
/** * connectFTP : connects to ftp server/*from w w w . j a v a 2 s . c o m*/ * * @return boolean success/fail */ public boolean connectFTP() { if (isFTPConnected()) { return true; } // Connect to FTP try { // 1. create an apache client iFTP = new FTPClient(); iFTP.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent aProtocolCommandEvent) { LOGGER.fine("FTP Command Send: (" + aProtocolCommandEvent.getCommand() + ") " + aProtocolCommandEvent.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent aProtocolCommandEvent) { LOGGER.fine("FTP Command Recieved: (" + aProtocolCommandEvent.getMessage() + ") Returned Code " + aProtocolCommandEvent.getReplyCode()); } }); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); iFTP.configure(conf); // 2. connect iFTP.connect(iIP, iPort); // 3. check connection done. int reply = iFTP.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectFTP(); LOGGER.log(Level.SEVERE, "FTP error: " + reply); return false; } // 4. Login if (!iFTP.login(iUserName, iPassword)) { LOGGER.log(Level.SEVERE, "FTP failed to login, Username: " + iUserName + " Password: " + iPassword); disconnectFTP(); return false; } else { if (iPassive.equalsIgnoreCase("true")) { iFTP.enterLocalPassiveMode(); } iFTP.setFileType(FTP.BINARY_FILE_TYPE); iFTP.setBufferSize(iBufferSize); } } catch (SocketException lSocketException) { LOGGER.log(Level.SEVERE, "Socket exception ", lSocketException); return false; } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Socket exception ", lIOException); return false; } LOGGER.info("FTP connection established with transport : " + iIP + ":" + iPort); return true; }
From source file:com.jmeter.alfresco.utils.FtpUtils.java
/** * Upload file./* www. ja v a 2 s. c o m*/ * * @param ftpClient the ftp client * @param frmLocalFilePath the frm local file path * @param toRemoteFilePath the to remote file path * @return true, if successful * @throws IOException Signals that an I/O exception has occurred. */ private boolean uploadFile(final FTPClient ftpClient, final String frmLocalFilePath, final String toRemoteFilePath) throws IOException { final File localFile = new File(frmLocalFilePath); final InputStream inputStream = new FileInputStream(localFile); try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final boolean isFileUploaded = ftpClient.storeFile(toRemoteFilePath, inputStream); final int replyCode = ftpClient.getReplyCode(); //If reply code is 550 then,Requested action not taken. File unavailable (e.g., file not found, no access). //If reply code is 150 then,File status okay (e.g., File found) //If reply code is 226 then,Closing data connection. //If reply code is 426 then,Connection closed; transfer aborted. LOG.debug("Reply code from remote host after storeFile(..) call: " + replyCode); return isFileUploaded; } finally { inputStream.close(); } }
From source file:jenkins.plugins.publish_over_ftp.BapFtpClientTest.java
@Test public void testBeginTransfersBinary() throws Exception { expect(mockFTPClient.setFileType(FTP.BINARY_FILE_TYPE)).andReturn(true); mockControl.replay();/*from w w w . j a v a2 s. c om*/ bapFtpClient.beginTransfers(new BapFtpTransfer("*", "", "", false, false, false)); mockControl.verify(); }