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:ch.sdi.core.impl.ftp.FTPClientExample.java
/** * *//* w w w . j a v a2 s.co m*/ private void run() throws Throwable { if (myProtocol == null) { if (myProxyHost != null) { myLog.debug("Using HTTP proxy server: " + myProxyHost); myFtp = new FTPHTTPClient(myProxyHost, myProxyPort, myProxyUser, myProxyPassword); } else { myFtp = new FTPClient(); } } else { FTPSClient ftps; if (myProtocol.equals("true")) { ftps = new FTPSClient(true); } else if (myProtocol.equals("false")) { ftps = new FTPSClient(false); } else { String prot[] = myProtocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(myProtocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } myFtp = ftps; if ("all".equals(myTrustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(myTrustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(myTrustmgr)) { ftps.setTrustManager(null); } } if (myPrintHash) { myFtp.setCopyStreamListener(createListener()); } if (myKeepAliveTimeout >= 0) { myFtp.setControlKeepAliveTimeout(myKeepAliveTimeout); } if (myControlKeepAliveReplyTimeout >= 0) { myFtp.setControlKeepAliveReplyTimeout(myControlKeepAliveReplyTimeout); } myFtp.setListHiddenFiles(myHidden); // intercept commands and write it to our logger myPrintCommandToLoggerListener = new PrintCommandToLoggerListener(myLog); PrintWriter writer = myPrintCommandToLoggerListener.getPrintWriter(); myFtp.addProtocolCommandListener(new PrintCommandListener(writer, true, '\n', true)); // myFtp.addProtocolCommandListener( new PrintCommandListener( new PrintWriter( System.out ), true ) ); try { int reply; if (myPort > 0) { myFtp.connect(myServer, myPort); } else { myFtp.connect(myServer); } myLog.debug("Connected to " + myServer + " on " + (myPort > 0 ? myPort : myFtp.getDefaultPort())); // After connection attempt, you should check the reply code to verify // success. reply = myFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { myFtp.disconnect(); throw new Exception("FTP server refused connection."); } } catch (IOException e) { if (myFtp.isConnected()) { try { myFtp.disconnect(); } catch (IOException f) { // do nothing } } throw new Exception("Could not connect to server.", e); } try { if (!myFtp.login(myUsername, myPassword)) { myFtp.logout(); throw createFtpException("Problems on login"); } myLog.debug("Remote system is " + myFtp.getSystemType()); if (myBinaryTransfer) { myFtp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should default to ASCII // but they don't all do so - see NET-500 myFtp.setFileType(FTP.ASCII_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (myLocalActive) { myFtp.enterLocalActiveMode(); } else { myFtp.enterLocalPassiveMode(); } myFtp.setUseEPSVwithIPv4(myUseEpsvWithIPv4); if (myStoreFile) { InputStream input; input = new FileInputStream(myLocal); myFtp.storeFile(myRemote, input); input.close(); } else if (myListFiles) { if (myLenient) { FTPClientConfig config = new FTPClientConfig(); config.setLenientFutureDates(true); myFtp.configure(config); } for (FTPFile f : myFtp.listFiles(myRemote)) { myLog.debug(f.getRawListing()); myLog.debug(f.toFormattedString()); } } else if (myMlsd) { for (FTPFile f : myFtp.mlistDir(myRemote)) { myLog.debug(f.getRawListing()); myLog.debug(f.toFormattedString()); } } else if (myMlst) { FTPFile f = myFtp.mlistFile(myRemote); if (f != null) { myLog.debug(f.toFormattedString()); } } else if (myListNames) { for (String s : myFtp.listNames(myRemote)) { myLog.debug(s); } } else if (myFeat) { // boolean feature check if (myRemote != null) { // See if the command is present if (myFtp.hasFeature(myRemote)) { myLog.debug("Has feature: " + myRemote); } else { if (FTPReply.isPositiveCompletion(myFtp.getReplyCode())) { myLog.debug("FEAT " + myRemote + " was not detected"); } else { throw createFtpException("Command failed"); } } // Strings feature check String[] features = myFtp.featureValues(myRemote); if (features != null) { for (String f : features) { myLog.debug("FEAT " + myRemote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(myFtp.getReplyCode())) { myLog.warn("FEAT " + myRemote + " is not present"); } else { throw createFtpException("Command failed"); } } } else { if (myFtp.features()) { // Command listener has already printed the output } else { throw createFtpException("Command failed"); } } } else if (myDoCommand != null) { if (myFtp.doCommand(myDoCommand, myRemote)) { // Command listener has already printed the output } else { throw createFtpException("Command failed"); } } else { OutputStream output; output = new FileOutputStream(myLocal); myFtp.retrieveFile(myRemote, output); output.close(); } myFtp.noop(); // check that control connection is working OK myFtp.logout(); } catch (FTPConnectionClosedException e) { throw createFtpException("Server closed connection."); } catch (IOException e) { throw createFtpException("IOException caught"); } finally { myPrintCommandToLoggerListener.flushRest(); if (myFtp.isConnected()) { try { myFtp.disconnect(); } catch (IOException f) { // do nothing } } } }
From source file:com.glaf.core.util.FtpUtils.java
/** * ?//from w w w .j a va2 s. c o m * * @param remoteFile * FTP"/" * @param input * ? */ public static boolean upload(String remoteFile, byte[] bytes) { if (!remoteFile.startsWith("/")) { throw new RuntimeException(" path must start with '/'"); } ByteArrayInputStream bais = null; BufferedInputStream bis = null; try { mkdirs(remoteFile.substring(0, remoteFile.lastIndexOf("/"))); if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) { changeToDirectory(remoteFile); remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length()); } getFtpClient().setFileType(FTP.BINARY_FILE_TYPE); getFtpClient().enterLocalPassiveMode(); getFtpClient().setFileTransferMode(FTP.STREAM_TRANSFER_MODE); bais = new ByteArrayInputStream(bytes); bis = new BufferedInputStream(bais); boolean flag = getFtpClient().storeFile(remoteFile, bis); if (flag) { logger.info("upload success"); } else { logger.info("upload failure"); } return flag; } catch (IOException ex) { ex.printStackTrace(); logger.error("upload error", ex); throw new RuntimeException(ex); } finally { IOUtils.closeStream(bis); IOUtils.closeStream(bais); } }
From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java
public void download(RunFileTransferEntity runFileTransferEntity) { log.debug("Start FTPUtil download"); File filecheck = new File(runFileTransferEntity.getOutFilePath()); if (!(filecheck.exists() && filecheck.isDirectory()) && !(runFileTransferEntity.getOutFilePath().contains("hdfs://"))) { log.error("Invalid output file path. Please provide valid output file path."); throw new RuntimeException("Invalid output path"); }//w ww .j a va2 s . c o m boolean fail_if_exist = false; FTPClient ftpClient = new FTPClient(); int retryAttempt = runFileTransferEntity.getRetryAttempt(); int attemptCount = 1; int i = 0; boolean login = false; boolean done = false; for (i = 0; i < retryAttempt; i++) { try { log.info("Connection attempt: " + (i + 1)); if (runFileTransferEntity.getTimeOut() != 0) 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(); if (runFileTransferEntity.getEncoding() != null) ftpClient.setControlEncoding(runFileTransferEntity.getEncoding()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (runFileTransferEntity.getOutFilePath().contains("hdfs://")) { log.debug("Processing for HDFS output path"); String outputPath = runFileTransferEntity.getOutFilePath(); String s1 = outputPath.substring(7, outputPath.length()); String s2 = s1.substring(0, s1.indexOf("/")); File f = new File("/tmp"); if (!f.exists()) { f.mkdir(); } int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); File isfile = new File(runFileTransferEntity.getOutFilePath() + "\\" + file_name); if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) { OutputStream outputStream = new FileOutputStream("/tmp/" + file_name); done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream); outputStream.close(); } else { if (!(isfile.exists() && !isfile.isDirectory())) { OutputStream outputStream = new FileOutputStream("/tmp/" + file_name); done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream); outputStream.close(); } else { fail_if_exist = true; throw new RuntimeException("File already exists"); } } Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://" + s2); FileSystem hdfsFileSystem = FileSystem.get(conf); String s = outputPath.substring(7, outputPath.length()); String hdfspath = s.substring(s.indexOf("/"), s.length()); Path local = new Path("/tmp/" + file_name); Path hdfs = new Path(hdfspath); hdfsFileSystem.copyFromLocalFile(local, hdfs); } else { int index = runFileTransferEntity.getInputFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/'); String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1); File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name); if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) { OutputStream outputStream = new FileOutputStream(runFileTransferEntity.getOutFilePath() .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + file_name); done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), (outputStream)); outputStream.close(); } else { if (!(isfile.exists() && !isfile.isDirectory())) { OutputStream outputStream = new FileOutputStream( runFileTransferEntity.getOutFilePath().replaceAll( Matcher.quoteReplacement("\\"), "/") + File.separatorChar + file_name); done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream); outputStream.close(); } else { fail_if_exist = true; Log.error("File already exits"); throw new FTPUtilException("File already exists"); } } } } catch (Exception e) { log.error("error while transferring the file", e); if (!login) { log.error("Login "); throw new FTPUtilException("Invalid FTP details"); } if (fail_if_exist) { log.error("File already exists "); throw new FTPUtilException("File already exists"); } try { Thread.sleep(runFileTransferEntity.getRetryAfterDuration()); } catch (Exception e1) { Log.error("Exception occured during sleep"); } catch (Error err) { log.error("fatal error", e); throw new FTPUtilException(err); } continue; } break; } if (i == runFileTransferEntity.getRetryAttempt()) { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception e) { Log.error("Exception while closing the ftp client", e); } if (runFileTransferEntity.getFailOnError()) throw new FTPUtilException("File transfer failed "); } log.debug("Finished FTPUtil download"); }
From source file:ch.sdi.core.impl.ftp.FtpExecutor.java
/** * @throws SdiException/*www. j av a 2s .c om*/ * @throws IOException */ public void connectAndLogin() throws SdiException, IOException { if (!myInitialized) { initBySpringContext(); } // if !initialized try { if (myProtocol == null) { if (myProxyHost != null) { myLog.debug("Using HTTP proxy server: " + myProxyHost); myFtp = new FTPHTTPClient(myProxyHost, myProxyPort, myProxyUser, myProxyPassword); } else { myLog.debug("Using simple FTPClient"); myFtp = new FTPClient(); } } else { FTPSClient ftps; if (myProtocol.equals("true")) { myLog.debug("Using FTPSClient with implicite SSL"); ftps = new FTPSClient(true); } else if (myProtocol.equals("false")) { myLog.debug("Using FTPSClient with no implicite SSL"); ftps = new FTPSClient(false); } else { String prot[] = myProtocol.split(","); if (prot.length == 1) { // Just protocol myLog.debug("Using FTPSClient with protocol " + myProtocol); ftps = new FTPSClient(myProtocol); } else { // protocol,true|false myLog.debug("Using FTPSClient with " + prot[0] + " and " + prot[1]); ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } myFtp = ftps; if ("all".equals(myTrustmgr)) { myLog.debug("Using AcceptAllTrustManager"); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(myTrustmgr)) { myLog.debug("Using ValidateServerCertificateTrustManager"); ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(myTrustmgr)) { myLog.debug("Setting TrustManager to null"); ftps.setTrustManager(null); } else { myLog.debug("Using no TrustManager at all"); } } if (myKeepAliveTimeout >= 0) { myLog.debug("Setting KeepAliveTimeout to " + myKeepAliveTimeout); myFtp.setControlKeepAliveTimeout(myKeepAliveTimeout); } if (myControlKeepAliveReplyTimeout >= 0) { myLog.debug("Setting ControlKeepAliveReplyTimeout to " + myControlKeepAliveReplyTimeout); myFtp.setControlKeepAliveReplyTimeout(myControlKeepAliveReplyTimeout); } // intercept commands and write it to our logger myPrintCommandToLoggerListener = new PrintCommandToLoggerListener(myLog); PrintWriter writer = myPrintCommandToLoggerListener.getPrintWriter(); myFtp.addProtocolCommandListener(new PrintCommandListener(writer, true, '\n', true)); // myFtp.addProtocolCommandListener( new PrintCommandListener( new PrintWriter( System.out ), true ) ); try { int reply; if (myPort > 0) { myLog.debug("Connecting to " + myServer + ":" + myPort); myFtp.connect(myServer, myPort); } else { myLog.debug("Connecting to " + myServer + " (default port)"); myFtp.connect(myServer); } myLog.debug("Connected to " + myServer + " on " + (myPort > 0 ? myPort : myFtp.getDefaultPort())); // After connection attempt, you should check the reply code to verify success. reply = myFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { myFtp.disconnect(); throw createFtpException("FTP server refused connection."); } } catch (IOException e) { throw createFtpException("Could not connect to server.", e); } if (!myFtp.login(myUsername, myPassword)) { myFtp.logout(); throw createFtpException("Problems on login"); } myLog.debug("Remote system is " + myFtp.getSystemType()); myFtp.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are behind firewalls these days. if (myLocalActive) { myFtp.enterLocalActiveMode(); } else { myFtp.enterLocalPassiveMode(); } myFtp.setUseEPSVwithIPv4(myUseEpsvWithIPv4); } finally { myPrintCommandToLoggerListener.flushRest(); } }
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
public boolean ftpConnect(String host, String username, String password, int port) { try {/*from ww w . ja v a 2 s .c o m*/ mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // login using username & password boolean status = mFTPClient.login(username, password); /* Set File Transfer Mode * * To avoid corruption issue you must specified a correct * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE, * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE * for transferring text, image, and compressed files. */ mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); return status; } } catch (Exception e) { String errMsg = parentActivity.getString(R.string.error_message_general); Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR_FTP_CONNECT, 0, 0, errMsg); activityHandler.sendMessage(msg); } return false; }
From source file:lucee.commons.io.res.type.ftp.FTPResource.java
@Override public OutputStream getOutputStream(boolean append) throws IOException { ResourceUtil.checkGetOutputStreamOK(this); FTPResourceClient client = null;/*from w w w . j a v a 2 s . c o m*/ try { provider.lock(this); client = provider.getClient(data); client.unregisterFTPFile(this); client.setFileType(FTP.BINARY_FILE_TYPE); OutputStream os = append ? client.appendFileStream(getInnerPath()) : client.storeFileStream(getInnerPath()); if (os == null) throw new IOException("can not open stream to file [" + this + "]"); return IOUtil.toBufferedOutputStream(new FTPResourceOutputStream(client, this, os)); } catch (IOException e) { provider.returnClient(client); provider.unlock(this); throw e; } }
From source file:com.glaf.core.util.FtpUtils.java
/** * ?/*from w ww . j a v a2 s . co m*/ * * @param remoteFile * FTP"/" * @param input * ? */ public static boolean upload(String remoteFile, InputStream input) { if (!remoteFile.startsWith("/")) { throw new RuntimeException(" path must start with '/'"); } try { mkdirs(remoteFile.substring(0, remoteFile.lastIndexOf("/"))); if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) { changeToDirectory(remoteFile); remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length()); } getFtpClient().setFileType(FTP.BINARY_FILE_TYPE); getFtpClient().enterLocalPassiveMode(); getFtpClient().setFileTransferMode(FTP.STREAM_TRANSFER_MODE); boolean flag = getFtpClient().storeFile(remoteFile, input); if (flag) { logger.info("upload success"); } else { logger.info("upload failure"); } return flag; } catch (IOException ex) { ex.printStackTrace(); logger.error("upload error", ex); throw new RuntimeException(ex); } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#get(String, String, * String, String, java.util.Map)/*from w w w. j a v a 2 s .c om*/ */ @Override public boolean get(String remoteDirectory, String remoteFile, String localDirectory, String localFile, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean result = false; OutputStream output = null; try { logger.debug("Downloading remote file " + remoteFile + " from " + (remoteDirectory != null ? " remote directory " + remoteDirectory : " current remote working directory") + "..."); File localPathname = new File(localDirectory, (localFile != null ? localFile : remoteFile)); if (!localPathname.isAbsolute()) { throw new RemoteManagerException("Local pathname (" + localPathname + ") is NOT absolute."); } logger.debug("Saving to " + localPathname); output = new FileOutputStream(localPathname); if (remoteDirectory != null) { changeWorkingDirectory(remoteDirectory); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.retrieveFile(remoteFile, output); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote file " + remoteFile + " saved to " + localPathname); result = true; } else { logger.warn("FTP Server NEGATIVE response: "); logServerReply(Level.WARN); } return result; } catch (IOException exc) { throw new RemoteManagerException("I/O error", exc); } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { if (output != null) { try { output.close(); } catch (IOException exc) { logger.warn("Error while closing local file output stream"); } } if (isAutoconnect()) { disconnect(); } } }
From source file:IHM.FenetreAjoutPhoto.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try {//from w w w .j a v a 2s .c o m FileInputStream input = null; try { input = new FileInputStream(nomF); } catch (FileNotFoundException ex) { Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex); } FTPSClient ftpClient = new FTPSClient(); ftpClient.connect("iutdoua-samba.univ-lyon1.fr", 990); Properties props = new Properties(); FileInputStream fichier = new FileInputStream("src/info.properties"); props.load(fichier); ftpClient.login(props.getProperty("login"), props.getProperty("password")); // on tablit les paramtre de connexion et on fournit les identifiants System.out.println(ftpClient.getReplyString()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String remote = null; if (this.radioBtnPhoto.isSelected()) //si l'utilisateur beut choisir une photo classique on choisit le bon rpertoire d'arriver { remote = "public_html/CPOA/Site/assets/photos/" + txtNomPhoto.getText(); this.laPhoto.setTypePhoto(1); } else if ((this.radioBtnPhotoP.isSelected())) // de mme si c'est une photo de profil { remote = "public_html/CPOA/Site/assets/photoProfil/" + txtNomPhoto.getText(); this.laPhoto.setTypePhoto(2); } boolean done = ftpClient.storeFile(remote, input); // on upload la photo input.close(); if (done) // on teste si le transfert est russi { System.out.println("reussi"); this.laPhoto.setNomPhoto(txtNomPhoto.getText()); this.laPhoto.setLieu(txtLieu.getText()); String dateD = txtAnneeD.getText() + "-" + txtMoisD.getText() + "-" + txtJourD.getText(); this.laPhoto.setDatePhoto(dateD); etat = true; this.dispose(); } else { System.out.println(ftpClient.getReplyString()); // on affiche la rponse du serveur si le transfert est rat this.dispose(); } } catch (IOException ex) { Logger.getLogger(FenetreAjoutPhoto.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aliasi.lingmed.medline.DownloadMedline.java
private void setFTPPath(String path) throws IOException { if (!mFTPClient.changeWorkingDirectory(path)) { raiseIOException("Server error changing directory to path=" + path); }//from ww w .j a v a 2s . c o m if (!mFTPClient.setFileType(FTP.BINARY_FILE_TYPE)) { raiseIOException("Server error changing type to binary."); } }