List of usage examples for org.apache.commons.net.ftp FTPClient setBufferSize
public void setBufferSize(int bufSize)
From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java
public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) { Log.v(TAG, "upload " + uploadConfig); // Make sure we have a file to upload if (!uploadConfig.file.exists()) return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE); FTPClient ftp = new FTPClient(); // For debugging, we'll log all the ftp commands if (BuildConfig.DEBUG) { PrintCommandListener printCommandListener = new PrintCommandListener(System.out); ftp.addProtocolCommandListener(printCommandListener); }//w ww .j ava 2 s . c o m InputStream is = null; try { // Set buffer size of FTP client ftp.setBufferSize(1048576); // Open a connection to the FTP server ftp.connect(uploadConfig.server, uploadConfig.port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } // Login to the FTP server if (!ftp.login(uploadConfig.user, uploadConfig.password)) { ftp.disconnect(); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE); } // Try to change directories if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) { Log.v(TAG, "Upload: could not change path to " + uploadConfig.path); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE); } // set the file type to be read as a binary file ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); // Upload the file is = new FileInputStream(uploadConfig.file); long before = System.currentTimeMillis(); long txBytesBefore = TrafficStats.getTotalTxBytes(); if (!ftp.storeFile(uploadConfig.file.getName(), is)) { ftp.disconnect(); Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: " + ftp.getReplyCode() + ", error string: " + ftp.getReplyString()); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } // Calculate stats long after = System.currentTimeMillis(); long txBytesAfter = TrafficStats.getTotalTxBytes(); ftp.logout(); ftp.disconnect(); Log.v(TAG, "Upload complete"); return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before, SpeedTestStatus.SUCCESS); } catch (SocketException e) { Log.e(TAG, "upload " + e.getMessage(), e); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } catch (IOException e) { Log.e(TAG, "upload " + e.getMessage(), e); return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE); } finally { IoUtil.closeSilently(is); } }
From source file:com.alexkasko.netty.ftp.FtpServerTest.java
@Test public void test() throws IOException, InterruptedException { final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate( new ConsoleReceiver()); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from ww w . j a va2s. c o m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipe = ch.pipeline(); pipe.addLast("decoder", new CrlfStringDecoder()); pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate)); } }); b.localAddress(2121).bind(); FTPClient client = new FTPClient(); // https://issues.apache.org/jira/browse/NET-493 client.setBufferSize(0); client.connect("127.0.0.1", 2121); assertEquals(230, client.user("anonymous")); // active assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); assertEquals("/", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.listFiles("/foo").length == 0); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // assertTrue(client.deleteFile("baz")); // passive assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE)); client.enterLocalPassiveMode(); assertEquals("/foo", client.printWorkingDirectory()); assertTrue(client.changeWorkingDirectory("/foo")); assertEquals("/foo", client.printWorkingDirectory()); //TODO make a virtual filesystem that would work with directory //assertTrue(client.listFiles("/foo").length==1); assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes()))); assertTrue(client.rename("bar", "baz")); // client.deleteFile("baz"); assertEquals(221, client.quit()); try { client.noop(); fail("Should throw exception"); } catch (IOException e) { //expected; } }
From source file:com.haha01haha01.harail.DatabaseDownloader.java
private Boolean downloadFile(String server, int portNumber, String user, String password, String filename, File localFile) throws IOException { FTPClient ftp = null; try {//w w w . j ava 2 s. com ftp = new FTPClient(); ftp.setBufferSize(1024 * 1024); ftp.connect(server, portNumber); Log.d(NAME, "Connected. Reply: " + ftp.getReplyString()); if (!ftp.login(user, password)) { return false; } Log.d(NAME, "Logged in"); if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) { return false; } Log.d(NAME, "Downloading"); ftp.enterLocalPassiveMode(); OutputStream outputStream = null; boolean success = false; try { outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); success = ftp.retrieveFile(filename, outputStream); } finally { if (outputStream != null) { outputStream.close(); } } return success; } finally { if (ftp != null) { ftp.logout(); ftp.disconnect(); } } }
From source file:dk.dma.dmiweather.service.FTPLoader.java
/** * Check for files every 10 minutes. New files are given to the gridWeatherService *///from w ww . ja v a2s .c om @Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000) public void checkFiles() { log.info("Checking FTP files at DMI."); FTPClient client = new FTPClient(); try { client.setDataTimeout(20 * 1000); client.setBufferSize(1024 * 1024); client.connect(hostname); if (client.login("anonymous", "")) { try { client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); for (ForecastConfiguration configuration : configurations) { // DMI creates a Newest link once all files have been created if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) { if (client.getReplyCode() != 250) { log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode()); } String workingDirectory = new File(client.printWorkingDirectory()).getName(); String previousNewest = newestDirectories.get(configuration); if (!workingDirectory.equals(previousNewest)) { // a new directory for this configuration is available on the server FTPFile[] listFiles = client.listFiles(); List<FTPFile> files = Arrays.stream(listFiles) .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches()) .collect(Collectors.toList()); try { Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory, files); gridWeatherService.newFiles(localFiles, configuration); } catch (IOException e) { log.warn("Unable to get new weather files from DMI", e); } if (previousNewest != null) { File previous = new File(tempDirLocation, previousNewest); deleteRecursively(previous); } newestDirectories.put(configuration, workingDirectory); } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to change ftp directory to {}", configuration.getFolder()); } } } finally { try { client.logout(); } catch (IOException e) { log.info("Failed to logout", e); } } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to login to {}", hostname); } } catch (IOException e) { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to update weather files from DMI", e); } finally { try { client.disconnect(); } catch (IOException e) { log.info("Failed to disconnect", e); } } log.info("Check completed."); }
From source file:com.globalsight.smartbox.util.FtpHelper.java
private FTPClient initFtpClient() throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port);//ww w .j av a 2 s . com ftpClient.login(username, password); // Sets Binary File Type for ZIP File. ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // Set Buffer Size to speed up download/upload file. ftpClient.setBufferSize(102400); return ftpClient; }
From source file:com.eryansky.common.utils.ftp.FtpFactory.java
/** * ?FTP?.// ww w . ja v a 2 s. c om * * @param path * FTP?? * @param filename * FTP??? * @param input * ? * @return ?true?false */ public boolean ftpUploadFile(String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); ftp.setControlEncoding("UTF-8"); try { int reply; ftp.connect(url, port); ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } // ftp.changeWorkingDirectory(path); ftp.setBufferSize(1024); ftp.setFileType(FTPClient.ASCII_FILE_TYPE); // ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return success; }
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();/*from w w w .j a va 2 s .co 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:com.tumblr.maximopro.iface.router.FTPHandler.java
@Override public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException { byte[] encodedData = super.invoke(metaData, data); this.metaData = metaData; FTPClient ftp; if (enableSSL()) { FTPSClient ftps = new FTPSClient(isImplicit()); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); ftp = ftps;//w ww . jav a 2 s. c om } else { ftp = new FTPClient(); } InputStream is = null; try { if (getTimeout() > 0) { ftp.setDefaultTimeout(getTimeout()); } if (getBufferSize() > 0) { ftp.setBufferSize(getBufferSize()); } if (getNoDelay()) { ftp.setTcpNoDelay(getNoDelay()); } ftp.connect(getHostname(), getPort()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } if (!ftp.login(getUsername(), getPassword())) { ftp.logout(); ftp.disconnect(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (enableActive()) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } is = new ByteArrayInputStream(encodedData); String remoteFileName = getFileName(metaData); ftp.changeWorkingDirectory("/"); if (createDirectoryStructure(ftp, getDirName().split("/"))) { ftp.storeFile(remoteFileName, is); } else { throw new MXApplicationException("iface", "cannotcreatedir"); } ftp.logout(); } catch (MXException e) { throw e; } catch (SocketException e) { throw new MXApplicationException("iface", "ftpsocketerror", e); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } } return null; }
From source file:ch.cyberduck.core.ftp.FTPSession.java
protected void configure(final FTPClient client) throws IOException { client.setProtocol(host.getProtocol()); client.setSocketFactory(socketFactory); client.setControlEncoding(host.getEncoding()); final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000; client.setConnectTimeout(timeout);//from w w w. j av a 2s . co m client.setDefaultTimeout(timeout); client.setDataTimeout(timeout); client.setDefaultPort(host.getProtocol().getDefaultPort()); client.setParserFactory(new FTPParserFactory()); client.setRemoteVerificationEnabled(preferences.getBoolean("ftp.datachannel.verify")); final int buffer = preferences.getInteger("ftp.socket.buffer"); client.setBufferSize(buffer); if (preferences.getInteger("connection.buffer.receive") > 0) { client.setReceiveBufferSize(preferences.getInteger("connection.buffer.receive")); } if (preferences.getInteger("connection.buffer.send") > 0) { client.setSendBufferSize(preferences.getInteger("connection.buffer.send")); } if (preferences.getInteger("connection.buffer.receive") > 0) { client.setReceieveDataSocketBufferSize(preferences.getInteger("connection.buffer.receive")); } if (preferences.getInteger("connection.buffer.send") > 0) { client.setSendDataSocketBufferSize(preferences.getInteger("connection.buffer.send")); } client.setStrictMultilineParsing(preferences.getBoolean("ftp.parser.multiline.strict")); client.setStrictReplyParsing(preferences.getBoolean("ftp.parser.reply.strict")); }
From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java
public FTPClient getFtpClient() throws IOException { FTPClient aClient = new FTPClient(); // Debug output // aClient.addProtocolCommandListener(new PrintCommandListener(new // PrintWriter(System.out), true)); if (activeExternalIPAddress != null) { aClient.setActiveExternalIPAddress(activeExternalIPAddress); }/* w w w . j a v a 2s .c om*/ if (activeMinPort != null && activeMaxPort != null) { aClient.setActivePortRange(activeMinPort, activeMaxPort); } if (autodetectUTF8 != null) { aClient.setAutodetectUTF8(autodetectUTF8); } if (bufferSize != null) { aClient.setBufferSize(bufferSize); } if (charset != null) { aClient.setCharset(charset); } if (connectTimeout != null) { aClient.setConnectTimeout(connectTimeout); } if (controlEncoding != null) { aClient.setControlEncoding(controlEncoding); } if (controlKeepAliveReplyTimeout != null) { aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } if (controlKeepAliveTimeout != null) { aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout); } if (dataTimeout != null) { aClient.setDataTimeout(dataTimeout); } if (defaultPort != null) { aClient.setDefaultPort(defaultPort); } if (defaultTimeout != null) { aClient.setDefaultTimeout(defaultTimeout); } if (fileStructure != null) { aClient.setFileStructure(fileStructure); } if (keepAlive != null) { aClient.setKeepAlive(keepAlive); } if (listHiddenFiles != null) { aClient.setListHiddenFiles(listHiddenFiles); } if (parserFactory != null) { aClient.setParserFactory(parserFactory); } if (passiveLocalIPAddress != null) { aClient.setPassiveLocalIPAddress(passiveLocalIPAddress); } if (passiveNatWorkaround != null) { aClient.setPassiveNatWorkaround(passiveNatWorkaround); } if (proxy != null) { aClient.setProxy(proxy); } if (receieveDataSocketBufferSize != null) { aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize); } if (receiveBufferSize != null) { aClient.setReceiveBufferSize(receiveBufferSize); } if (remoteVerificationEnabled != null) { aClient.setRemoteVerificationEnabled(remoteVerificationEnabled); } if (reportActiveExternalIPAddress != null) { aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress); } if (sendBufferSize != null) { aClient.setSendBufferSize(sendBufferSize); } if (sendDataSocketBufferSize != null) { aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize); } if (strictMultilineParsing != null) { aClient.setStrictMultilineParsing(strictMultilineParsing); } if (tcpNoDelay != null) { aClient.setTcpNoDelay(tcpNoDelay); } if (useEPSVwithIPv4 != null) { aClient.setUseEPSVwithIPv4(useEPSVwithIPv4); } if (systemKey != null) { FTPClientConfig aClientConfig = new FTPClientConfig(systemKey); if (defaultDateFormat != null) { aClientConfig.setDefaultDateFormatStr(defaultDateFormat); } if (recentDateFormat != null) { aClientConfig.setRecentDateFormatStr(recentDateFormat); } if (serverLanguageCode != null) { aClientConfig.setServerLanguageCode(serverLanguageCode); } if (shortMonthNames != null) { aClientConfig.setShortMonthNames(shortMonthNames); } if (serverTimeZoneId != null) { aClientConfig.setServerTimeZoneId(serverTimeZoneId); } aClient.configure(aClientConfig); } if (LOGGER.isInfoEnabled()) { LOGGER.info("Connecting to : {}", host); } if (port == null) { aClient.connect(host); } else { aClient.connect(host, port); } int aReplyCode = aClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(aReplyCode)) { aClient.disconnect(); throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode); } try { if (localPassiveMode) { aClient.enterLocalPassiveMode(); } boolean aIsLoggedIn = false; if (account == null) { aIsLoggedIn = aClient.login(username, password); } else { aIsLoggedIn = aClient.login(username, password, account); } if (!aIsLoggedIn) { throw new IOException(aClient.getReplyString()); } } catch (IOException e) { aClient.disconnect(); throw e; } if (fileTransferMode != null) { aClient.setFileTransferMode(fileTransferMode); } if (fileType != null) { aClient.setFileType(fileType); } return aClient; }