List of usage examples for org.apache.commons.net.ftp FTPClient enterLocalPassiveMode
public void enterLocalPassiveMode()
PASSIVE_LOCAL_DATA_CONNECTION_MODE
. 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:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java
public void send(File[] archivos) { try {// w w w. java 2 s .c o m HashMap<String, String> params = getFtpParams(); FTPClient ftpClient = getFtpClient(params); BufferedInputStream buffIn = null; for (File actual : archivos) { // String fileName = "PROCESOS_PARA_EL_IVA_VENTAS_UNICOMER.xlsx"; buffIn = new BufferedInputStream(new FileInputStream(actual.getAbsolutePath()));//Ruta del archivo para enviar ftpClient.enterLocalPassiveMode(); ftpClient.storeFile(params.get("remoteStoreFiles") + REMOTE_SEPARATOR + actual.getName(), buffIn);//Ruta completa de alojamiento en el FTP if (ftpClient.getReplyCode() == 226) { System.out.println("Archivo guardado exitosamente"); } else { System.out.println("No se pudo guardar el archivo: " + actual.getName() + ", codigo:" + ftpClient.getReplyCode()); } } buffIn.close(); //Cerrar envio de archivos al FTP ftpClient.logout(); //Cerrar sesin ftpClient.disconnect();//Desconectarse del servidor } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
From source file:be.thomasmore.controller.FileController.java
public String uploadFile() throws IOException { String server = "logic.sinners.be"; int port = 21; String user = "logic_java"; String pass = "scoretracker"; FTPClient ftpClient = new FTPClient(); try {//from w w w .j a v a 2 s . c o m ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String firstRemoteFile = getFileName(part); InputStream inputStream = part.getInputStream(); System.out.println("Bestand uploaden"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { System.out.println("Het bestand is succesvol upgeload."); statusMessage = "De gegevens werden succesvol ingeladen."; } } catch (IOException ex) { System.out.println("Fout: " + ex.getMessage()); statusMessage = "Er is een fout opgetreden: " + ex.getMessage(); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } /* //De bestandsnaam uit het bestand (part) halen String fileName = getFileName(part); System.out.println("***** fileName: " + fileName); String basePath = "C:" + File.separator + "data" + File.separator; File outputFilePath = new File(basePath + fileName); //Streams aanmaken om het upgeloade bestand naar de destination te kopiren InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = part.getInputStream(); outputStream = new FileOutputStream(outputFilePath); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } statusMessage = "De gegevens werden succesvol ingeladen."; } catch (IOException e) { e.printStackTrace(); statusMessage = "Er is een fout opgetreden."; } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } }*/ leesExcel(); return null; }
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 www .jav a 2s .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.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 {//from w w w. j a v a2 s . c om 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 a v a 2s.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:hydrograph.engine.spark.datasource.utils.FTPUtil.java
public void upload(RunFileTransferEntity runFileTransferEntity) { log.debug("Start FTPUtil upload"); FTPClient ftpClient = new FTPClient(); ftpClient.enterLocalPassiveMode(); ftpClient.setBufferSize(1024000);/*from w w w .j av a 2s .c om*/ 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:FTP.Uploader.java
public void uploadFile(String filename) throws IOException { FTPClient ftpclient = new FTPClient(); FileInputStream fis = null;//from ww w.j av a 2 s. co m boolean result; String ftpServerAddress = "shamalmahesh.net78.net"; String userName = "a9959679"; String password = "9P3IckDo"; try { ftpclient.connect(ftpServerAddress); result = ftpclient.login(userName, password); if (result == true) { System.out.println("Logged in Successfully !"); } else { System.out.println("Login Fail!"); return; } ftpclient.enterLocalPassiveMode(); ftpclient.setFileType(FTP.BINARY_FILE_TYPE); ftpclient.changeWorkingDirectory("/public_html/testing"); // File file = new File("D:/jpg/wq.jpg"); File file = new File(filename); String testName = file.getName(); fis = new FileInputStream(file); System.out.println(ftpclient.getBufferSize()); // Upload file to the ftp server result = ftpclient.storeFile(testName, fis); if (result == true) { System.out.println("File is uploaded successfully"); } else { System.out.println("File uploading failed"); } ftpclient.logout(); } catch (FTPConnectionClosedException e) { e.printStackTrace(); } finally { try { ftpclient.disconnect(); } catch (FTPConnectionClosedException e) { System.out.println(e); } } }
From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { Map<String, String> ftpInfo = getFtpInfo(contentType); if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username")) && !"".equals(ftpInfo.get("password"))) { FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {/*from ww w. j ava 2 s . co m*/ inputStream = new FileInputStream(file); ftpClient.connect(ftpInfo.get("host"), 21); ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password")); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); path = ftpInfo.get("path") + path; 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:it.zero11.acme.example.FTPChallengeListener.java
private boolean createChallengeFiles(String token, String challengeBody) { boolean success = false; FTPClient ftp = new FTPClient(); try {/*from www .j a v a 2 s . c o m*/ ftp.connect(host); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); return false; } ftp.login(username, password); ftp.changeWorkingDirectory(webroot); ftp.makeDirectory(".well-known"); ftp.changeWorkingDirectory(".well-known"); ftp.makeDirectory("acme-challenge"); ftp.changeWorkingDirectory("acme-challenge"); ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE); ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes())); if (!success) System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString()); ftp.logout(); } catch (IOException e) { throw new AcmeException(e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }