List of usage examples for org.apache.commons.net.ftp FTPClient setFileType
public boolean setFileType(int fileType) throws IOException
From source file:com.microsoft.azuretools.utils.WebAppUtils.java
public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException { FTPClient ftp = new FTPClient(); System.out.println("\t\t" + pp.ftpUrl()); System.out.println("\t\t" + pp.ftpUsername()); System.out.println("\t\t" + pp.ftpPassword()); URI uri = URI.create("ftp://" + pp.ftpUrl()); ftp.connect(uri.getHost(), 21);/*from w w w . j av a 2s . c o m*/ final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); throw new ConnectException("Unable to connect to FTP server"); } if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) { throw new ConnectException("Unable to login to FTP server"); } ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode();//Switch to passive mode return ftp; }
From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java
@Override public void upload(String path, File file, String contentType) { PluginConfig pluginConfig = getPluginConfig(); if (pluginConfig != null) { String host = pluginConfig.getAttribute("host"); Integer port = Integer.valueOf(pluginConfig.getAttribute("port")); String username = pluginConfig.getAttribute("username"); String password = pluginConfig.getAttribute("password"); FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/*from w w w . java 2 s .c o m*/ inputStream = new BufferedInputStream(new FileInputStream(file)); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (SocketException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); try { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } catch (IOException e) { } } } }
From source file:com.globalsight.smartbox.util.FtpHelper.java
private FTPClient initFtpClient() throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port);/*w ww . jav a 2 s. c o m*/ 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.dp2345.plugin.ftp.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { PluginConfig pluginConfig = getPluginConfig(); if (pluginConfig != null) { String host = pluginConfig.getAttribute("host"); Integer port = Integer.valueOf(pluginConfig.getAttribute("port")); String username = pluginConfig.getAttribute("username"); String password = pluginConfig.getAttribute("password"); FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {// w w w .java 2 s . co m inputStream = new FileInputStream(file); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } }
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); }/*from ww w. j av a 2s . co 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.claim.support.FtpUtil.java
public void uploadSingleFileWithFTP(String direcPath, FileTransferController fileTransferController) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {//from w w w.j av a 2 s. c o m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); File secondLocalFile = new File(direcPath); String secondRemoteFile = "WorkshopDay2.docx"; inputStream = new FileInputStream(secondLocalFile); System.out.println("Start uploading second file"); OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) { System.out.println("The second 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(); } } }
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 {/*from w w w . j a v a 2 s .c o m*/ 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:edu.stanford.epad.common.util.FTPUtil.java
public void getFile(String remoteFile, File localFile) throws Exception { FTPClient ftpClient = new FTPClient(); OutputStream outputStream = null; try {//from w ww . j av a 2 s. c o m ftpClient.connect(ftpHost, ftpPort); ftpClient.enterLocalPassiveMode(); if (ftpUser != null && ftpUser.length() > 0) ftpClient.login(ftpUser, ftpPassword); else ftpClient.login("anonymous", ""); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); InputStream inputStream = ftpClient.retrieveFileStream(remoteFile); IOUtils.copy(inputStream, outputStream); outputStream.flush(); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); boolean commandOK = ftpClient.completePendingCommand(); //boolean success = ftpClient.retrieveFile(remoteFile, outputStream); //if (!success) { // throw new Exception("Error retrieving remote file: " + remoteFile); //} } finally { outputStream.close(); ftpClient.disconnect(); } }
From source file:dk.dma.dmiweather.service.FTPLoader.java
/** * Check for files every 10 minutes. New files are given to the gridWeatherService */// w w w . j av a 2 s . 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:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java
/** * // w w w.j av a 2 s.com * * @throws Exception * @throws IOException */ private void setFileType(FTPClient ftpClient) throws Exception { try { if (binaryTransfer) { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); } else { ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE); } } catch (IOException e) { throw new Exception("Could not to set file type.", e); } }