List of usage examples for org.apache.commons.net.ftp FTPClient setFileType
public boolean setFileType(int fileType) throws IOException
From source file:com.dinochiesa.edgecallouts.FtpPut.java
public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) { FtpCalloutResult info = new FtpCalloutResult(); try {/* w ww . j av a 2s . c om*/ // 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:ddf.test.itests.catalog.TestFtp.java
private FTPClient createInsecureClient() throws Exception { FTPClient ftp = new FTPClient(); int attempts = 0; while (true) { try {/*from w ww .ja va 2 s . c o m*/ ftp.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort())); break; } catch (SocketException e) { // a socket exception can be thrown if the ftp server is still in the process of coming up // or down Thread.sleep(1000); if (attempts++ > 30) { throw e; } } } showServerReply(ftp); int connectionReply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftp.login(USERNAME, PASSWORD); showServerReply(ftp); if (!success) { fail("Could not log in to the FTP server."); } ftp.enterLocalPassiveMode(); ftp.setControlKeepAliveTimeout(300); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; }
From source file:com.savy3.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null; try {/*ww w . j a va2s .c o m*/ String username = conf.get(DBConfiguration.USERNAME_PROPERTY); String password; if (username == null) { username = "anonymous"; password = ""; } else { password = DBConfiguration.getPassword((JobConf) conf); } String connectString = conf.get(DBConfiguration.URL_PROPERTY); String server = connectString; int port = 0; String[] parts = connectString.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { LOG.warn("Invalid port number: " + e.toString()); } } if (null != mockFTPClient) { ftp = mockFTPClient; } else { ftp = new FTPClient(); } FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS); ftp.configure(config); if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } } catch (IOException ioexp) { throw new IOException("Could not connect to server " + server, ioexp); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString()); } LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set Binary transfer mode ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.featureValue("LITERAL SITE RDW"); ftp.doCommand("SITE", "RDW"); System.out.println("reply for LITERAL" + ftp.getReplyString()); // Use passive mode as default. ftp.enterLocalPassiveMode(); } catch (IOException ioe) { if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } ftp = null; throw ioe; } return ftp; }
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
/** * Login into a account/* w w w . java 2 s . c o m*/ * * @return FTPClient object or null * @throws IOException */ public FTPClient login() throws IOException { int reply = 0; FTPClient ftp = new FTPClient(); try { if (port != 0) ftp.connect(getHost(), getPort()); else ftp.connect(getHost()); if (isAnonymous()) ftp.login(ANONYMOUS, GUEST); else if (getSubAccount() != null && !getSubAccount().isEmpty()) ftp.login(getLogin(), getPassword(), getSubAccount()); else ftp.login(getLogin(), getPassword()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString())); if (isPassiveMode()) ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } throw e; } return ftp; }
From source file:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {/*from w ww . j ava 2s . 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.microsoft.intellij.forms.CreateWebSiteForm.java
private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException { if (config != null) { AzureManager manager = AzureManagerImpl.getManager(project); WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings( config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName()); // retrieve ftp publish profile WebSitePublishSettings.FTPPublishProfile ftpProfile = null; for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof WebSitePublishSettings.FTPPublishProfile) { ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp; break; }/*from w w w .jav a 2s . c o m*/ } if (ftpProfile != null) { FTPClient ftp = new FTPClient(); try { URI uri = null; uri = new URI(ftpProfile.getPublishUrl()); ftp.connect(uri.getHost()); final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); } if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) { ftp.logout(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (ftpProfile.isFtpPassiveMode()) { ftp.enterLocalPassiveMode(); } ftp.deleteFile(ftpPath + message("configName")); String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator, message("configName")); File file = new File(tmpPath); if (file.exists()) { file.delete(); } WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath); String jdkFolderName = ""; if (customJDKUser.isSelected()) { String url = customUrl.getText(); jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length()); jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip")); } else { String cloudVal = WindowsAzureProjectManager .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile); jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length()); } String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName; String serverPath = "%programfiles(x86)%\\" + WAHelper .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion()); WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath); InputStream input = new FileInputStream(tmpPath); ftp.storeFile(ftpPath + message("configName"), input); cleanup(ftp); ftp.logout(); } catch (Exception e) { AzurePlugin.log(e.getMessage(), e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } } } }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static InputStream open(URL url) throws IOException { // System.out.println( "URLUtilities.open( "+url+")"); InputStream stream = null;//from ww w .ja va2 s .co m String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { try { DefaultAuthenticator authenticator = Main.getDefaultAuthenticator(); URL newURL = new URL(URLUtilities.toString(url)); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication( new PasswordAuthentication(username, password.toCharArray())); } stream = newURL.openStream(); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication(null); } } catch (Exception e) { // System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage()); // try it with webdav WebdavResource webdav = createWebdavResource(toString(url), username, password); stream = webdav.getMethodData(toString(url)); webdav.close(); } } else if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); try { // System.out.println( "Connecting to: "+host+" ..."); client = new FTPClient(); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Could not connect."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in using: "+username+", "+password+" ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Opening file \""+url.getFile()+"\" ..."); stream = client.retrieveFileStream(url.getFile()); // System.out.println( "File opened."); // System.out.println( "Disconnecting ..."); client.disconnect(); // System.out.println( "Disconnected."); } catch (IOException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException f) { // do nothing e.printStackTrace(); } } throw new IOException("Could not connect to FTP Server \"" + host + "\"."); } } else if (protocol.equals("file")) { stream = url.openStream(); } else { //unknown protocol but try anyways try { stream = url.openStream(); } catch (IOException ioe) { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } } return stream; }
From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java
/** * Retrieve the FTP client belonging to the given URI. * /* w w w .java 2 s . c o m*/ * @param uri * @return FTPClient */ protected FTPClient retrieveFtpClient(final URI uri) { // Create the FTP client FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not connect to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not login to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } // Switch to PASV and BINARY mode ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return ftpClient; } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } return null; }
From source file:fr.bmartel.speedtest.SpeedTestTask.java
/** * Start FTP upload.//from www .j a v a 2s . c om * * @param hostname ftp host * @param port ftp port * @param uri upload uri * @param fileSizeOctet file size in octet * @param user username * @param password password */ public void startFtpUpload(final String hostname, final int port, final String uri, final int fileSizeOctet, final String user, final String password) { mSpeedTestMode = SpeedTestMode.UPLOAD; mUploadFileSize = new BigDecimal(fileSizeOctet); mForceCloseSocket = false; mErrorDispatched = false; if (mWriteExecutorService == null || mWriteExecutorService.isShutdown()) { mWriteExecutorService = Executors.newSingleThreadExecutor(); } mWriteExecutorService.execute(new Runnable() { @Override public void run() { final FTPClient ftpClient = new FTPClient(); final RandomGen randomGen = new RandomGen(); RandomAccessFile uploadFile = null; try { ftpClient.connect(hostname, port); ftpClient.login(user, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); byte[] fileContent = new byte[] {}; if (mSocketInterface.getUploadStorageType() == UploadStorageType.RAM_STORAGE) { /* generate a file with size of fileSizeOctet octet */ fileContent = randomGen.generateRandomArray(fileSizeOctet); } else { uploadFile = randomGen.generateRandomFile(fileSizeOctet); uploadFile.seek(0); } mFtpOutputstream = ftpClient.storeFileStream(uri); if (mFtpOutputstream != null) { mUploadTempFileSize = 0; final int uploadChunkSize = mSocketInterface.getUploadChunkSize(); final int step = fileSizeOctet / uploadChunkSize; final int remain = fileSizeOctet % uploadChunkSize; mTimeStart = System.currentTimeMillis(); mTimeEnd = 0; if (mRepeatWrapper.isFirstUpload()) { mRepeatWrapper.setFirstUploadRepeat(false); mRepeatWrapper.setStartDate(mTimeStart); } if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updatePacketSize(mUploadFileSize); } if (mForceCloseSocket) { SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, ""); } else { for (int i = 0; i < step; i++) { final byte[] chunk = SpeedTestUtils.readUploadData( mSocketInterface.getUploadStorageType(), fileContent, uploadFile, mUploadTempFileSize, uploadChunkSize); mFtpOutputstream.write(chunk, 0, uploadChunkSize); mUploadTempFileSize += uploadChunkSize; if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updateTempPacketSize(uploadChunkSize); } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int j = 0; j < mListenerList.size(); j++) { mListenerList.get(j).onUploadProgress(report.getProgressPercent(), report); } } } if (remain != 0) { final byte[] chunk = SpeedTestUtils.readUploadData( mSocketInterface.getUploadStorageType(), fileContent, uploadFile, mUploadTempFileSize, remain); mFtpOutputstream.write(chunk, 0, remain); mUploadTempFileSize += remain; if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updateTempPacketSize(remain); } } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int j = 0; j < mListenerList.size(); j++) { mListenerList.get(j).onUploadProgress(SpeedTestConst.PERCENT_MAX.floatValue(), report); } } mTimeEnd = System.currentTimeMillis(); } mFtpOutputstream.close(); mReportInterval = false; final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onUploadFinished(report); } if (!mRepeatWrapper.isRepeatUpload()) { closeExecutors(); } } else { mReportInterval = false; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "cant create stream " + "from uri " + uri + " with reply code : " + ftpClient.getReplyCode()); } } catch (SocketTimeoutException e) { //e.printStackTrace(); mReportInterval = false; mErrorDispatched = true; if (!mForceCloseSocket) { SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, false, SpeedTestConst.SOCKET_WRITE_ERROR); } else { SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage()); } closeSocket(); closeExecutors(); } catch (IOException e) { //e.printStackTrace(); mReportInterval = false; mErrorDispatched = true; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage()); closeExecutors(); } finally { mErrorDispatched = false; mSpeedTestMode = SpeedTestMode.NONE; disconnectFtp(ftpClient); if (uploadFile != null) { try { uploadFile.close(); randomGen.deleteFile(); } catch (IOException e) { //e.printStackTrace(); } } } } }); }
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 . ja v a 2s . 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; }