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:com.ephesoft.dcma.util.FTPUtil.java
/** * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure. * //w w w . j a v a 2s.c o m * @param sourceDirectoryPath the directory to be uploaded * @param destDirName the path on ftp where directory will be uploaded * @param numberOfRetryCounter number of attempts to be made for uploading the directory * @throws FTPDataUploadException if an error occurs while uploading the file * @throws IOException if an error occurs while making the ftp connection * @throws SocketException if an error occurs while making the ftp connection */ public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData) throws FTPDataUploadException, SocketException, IOException { boolean isValid = true; if (ftpInformation.getSourceDirectoryPath() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DIR); throw new FTPDataUploadException(VAR_SOURCE_DIR); } if (ftpInformation.getDestDirName() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DES); throw new FTPDataUploadException(VAR_SOURCE_DES); } if (isValid) { FTPClient client = new FTPClient(); String destDirName = ftpInformation.getDestDirName(); String destinationDirectory = ftpInformation.getUploadBaseDir(); if (destDirName != null && !destDirName.isEmpty()) { String uploadBaseDir = ftpInformation.getUploadBaseDir(); if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) { destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator, destDirName); } else { destinationDirectory = destDirName; } } FileInputStream fis = null; try { createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(), ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut()); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOGGER.info("Starting File Upload..."); } else { LOGGER.info("Invalid Connection to FTP server. Disconnecting Client"); client.disconnect(); isValid = false; throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client"); } if (isValid) { // code changed for keeping the control connection busy. client.setControlKeepAliveTimeout(300); client.setFileType(FTP.BINARY_FILE_TYPE); createFtpDirectoryTree(client, destinationDirectory); // client.makeDirectory(destinationDirectory); if (deleteExistingFTPData) { deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData); } File file = new File(ftpInformation.getSourceDirectoryPath()); if (file.isDirectory()) { String[] fileList = file.list(); for (String fileName : fileList) { String inputFile = EphesoftStringUtil .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName); File checkFile = new File(inputFile); if (checkFile.isFile()) { LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName)); fis = new FileInputStream(inputFile); try { client.storeFile(fileName, fis); } catch (IOException e) { int retryCounter = ftpInformation.getNumberOfRetryCounter(); LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-", (retryCounter + 1))); if (retryCounter < ftpInformation.getNumberOfRetries()) { retryCounter = retryCounter + 1; uploadDirectory(ftpInformation, deleteExistingFTPData); } else { LOGGER.error("Error in uploading the file to FTP server"); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { LOGGER.info(EphesoftStringUtil .concatenate("Could not close stream for file.", inputFile)); } } } } } } } catch (FileNotFoundException e) { LOGGER.error("File does not exist.."); } finally { try { client.disconnect(); } catch (IOException e) { LOGGER.error("Disconnecting from FTP server....", e); } } } }
From source file:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); try {/* ww w . ja v a 2 s .co m*/ //ftpClient.connect("127.0.0.1", 21 ); //ftpClient.login("erpftp", "Tribut@2014"); ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken), Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken))); ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken), Config.getInstance().getProperty(Config.PassFtpToken)); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftpClient.getReplyCode(); System.out.println("Respuesta recibida de conexin FTP:" + reply); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println("Imposible conectarse al servidor"); //return -1; } else { System.out.println("se conecto al servidor"); } //ftpClient.enterLocalPassiveMode(); // crear directorio //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta)); //System.out.println("File #1 has been downloaded successfully. 1"); //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12"); //InputStream is = fis; System.out.println("File rutaqq=" + "1-/" + remote_file_ruta); InputStream is = ftpClient.retrieveFileStream(remote_file_ruta); if (is == null) System.out.println("File #1 es null token"); else System.out.println("File #1 no es null token"); //return ftpClient.retrieveFileStream(remote_file_ruta); return is; } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 222"); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 3"); return null; //ex.printStackTrace(); } } return null; }
From source file:com.recomdata.transmart.data.export.util.FTPUtil.java
public static InputStream downloadFileStream(boolean binaryTransfer, String filename, String location) { InputStream inputStream = null; try {//w w w. j ava 2 s .c om String remote = ((StringUtils.isNotEmpty(location)) ? location : FTP_SERVER_REMOTE_PATH) + filename; connect(); login(); if (binaryTransfer) ftp.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are // behind firewalls these days. ftp.enterLocalPassiveMode(); ftp.setUseEPSVwithIPv4(false); inputStream = ftp.retrieveFileStream(remote); } catch (InvalidFTPParamsException e) { log.error("Invalid FTP Params to connect"); } catch (FTPAuthenticationException e) { log.error(e.getMessage()); } catch (FileNotFoundException e) { log.error("Not able to load/read the localFile"); } catch (IOException e) { log.error("IOException during FTP upload process"); } return inputStream; }
From source file:jenkins.plugins.publish_over_ftp.BapFtpClient.java
private boolean setTransferMode(final BapFtpTransfer transfer) throws IOException { final int fileType = transfer.isAsciiMode() ? FTP.ASCII_FILE_TYPE : FTP.BINARY_FILE_TYPE; return ftpClient.setFileType(fileType); }
From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java
public void fetch(final FtpSubscription ftpSubscription) { if (_log.isDebugEnabled()) { _log.debug("fetching " + ftpSubscription); }/*from ww w .j a va2 s .c o m*/ final FTPClient ftp = new FTPClient(); ftp.setControlKeepAliveTimeout(30); ftp.setControlKeepAliveReplyTimeout(30); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; ftp.connect(ftpSubscription.getFtpHost()); _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (final IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } boolean error = false; __main: try { if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) { ftp.logout(); error = true; break __main; } _log.info("Remote system is " + ftp.getSystemType()); ftp.setFileType(FTP.BINARY_FILE_TYPE); //ftp.enterLocalActiveMode(); ftp.enterLocalPassiveMode(); //final FTPClientConfig config = new FTPClientConfig(); ////config.setLenientFutureDates(true); //ftp.configure(config); if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) { ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder()); } final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile()); if (is == null) { _log.error("FIle not found: " + ftp.getSystemType()); } else { unzip(ftpSubscription, is); is.close(); } ftp.completePendingCommand(); } catch (final FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (final IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (final IOException e) { _log.error(e); } } } }
From source file:com.gdbocom.util.SendFileinFTP.java
/** * ,?FTP?BINASCII?/*from w w w.j av a 2s .c o m*/ * @param local ??(?,"/"?),?? * @param remotePath () * @param remote ??(??),?? * @param filetype ?,BINASCII?? * @param ftptype FTP?,?? * @return ?? */ public boolean getFile(String local, String remotePath, String remote, int filetype, int ftptype) throws IOException { //bin?,ASCII? if (filetype == SendFileinFTP.BINARY_FILE_TYPE) { ftp.setFileType(FTP.BINARY_FILE_TYPE); gzLog.Write("BIN?"); } else if (filetype == SendFileinFTP.ASCII_FILE_TYPE) { ftp.setFileType(FTP.ASCII_FILE_TYPE); gzLog.Write("ASCII?"); } else { gzLog.Write(""); return false; } // FTP??,FTP? if (ftptype == SendFileinFTP.ActiveMode) { ftp.enterLocalActiveMode(); gzLog.Write("FTP?"); } else if (ftptype == SendFileinFTP.PassiveMode) { ftp.enterLocalPassiveMode(); gzLog.Write("FTP?"); } else { ftp.enterLocalPassiveMode(); gzLog.Write("FTP?,FTP?"); return false; } //? ftp.changeWorkingDirectory(remotePath); // try { OutputStream output; output = new FileOutputStream(local); if (ftp.retrieveFile(remote, output)) { gzLog.Write("" + remote + "?,?:./" + local); } else { gzLog.Write(""); } output.close(); } catch (FTPConnectionClosedException e) { gzLog.Write("Server closed connection."); e.printStackTrace(); return false; } return true; }
From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java
/** * API to download a particular directory from FTP Server. * /* w w w . ja v a2 s . c o m*/ * @param sourceDirName {@link String} - Name of the source directory to be copied. * @param destDirectoryPath {@link String} - Full path where directory need to be copied. * @param retryCounter - Start with zero. * @param isDeletedFTPServerSourceContent - set true for deleted the ftp server content. * @throws FTPDataDownloadException if any error occurs while downloading the file. */ @Override public void downloadDirectory(final String sourceDirName, final String destDirectoryPath, final int numberOfRetryCounter, boolean isDeletedFTPServerSourceContent) throws FTPDataDownloadException { boolean isValid = true; if (sourceDirName == null) { isValid = false; LOGGER.error(var_source_dir); throw new FTPDataDownloadException(var_source_dir); } if (destDirectoryPath == null) { isValid = false; LOGGER.error(var_source_des); throw new FTPDataDownloadException(var_source_des); } if (isValid) { FTPClient client = new FTPClient(); String outputFileName = null; File file = new File(destDirectoryPath); if (!file.exists()) { file.mkdir(); } try { createConnection(client); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOGGER.info("Starting File Download..."); } else { LOGGER.error("Invalid Connection to FTP server. Disconnecting from FTP server...."); client.disconnect(); isValid = false; throw new FTPDataDownloadException( "Invalid Connection to FTP server. Disconnecting from FTP server...."); } if (isValid) { client.setFileType(FTP.BINARY_FILE_TYPE); String ftpDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator, sourceDirName); LOGGER.info("Downloading files from FTP server"); try { FTPUtil.retrieveFiles(client, ftpDirectory, destDirectoryPath); } catch (IOException e) { int retryCounter = numberOfRetryCounter; LOGGER.info("Retrying download Attempt#-" + (retryCounter + 1)); if (retryCounter < numberOfRetries) { retryCounter = retryCounter + 1; downloadDirectory(sourceDirName, destDirectoryPath, retryCounter, isDeletedFTPServerSourceContent); } else { LOGGER.error("Error in getting file from FTP server :" + outputFileName); } } if (isDeletedFTPServerSourceContent) { FTPUtil.deleteExistingFTPData(client, ftpDirectory, true); } } } catch (FileNotFoundException e) { LOGGER.error("Error in generating output Stream for file :" + outputFileName); } catch (SocketException e) { LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e); } catch (IOException e) { LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e); } finally { try { client.disconnect(); } catch (IOException e) { LOGGER.error("Error in disconnecting from FTP server." + e); } } } }
From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java
protected InputStream getStreamFromFTPNetwork(String imageUri, Object extra) throws IOException { int indexUrl = imageUri.indexOf("//") + 1; int indexUrlFinal = imageUri.lastIndexOf(":"); int slash = imageUri.lastIndexOf("/"); String ip = imageUri.substring(indexUrl + 1, indexUrlFinal); FTPClient client = new FTPClient(); client.connect(ip, 20000);/*from w w w. j a va2 s . c om*/ client.login("anonymous", ""); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); InputStream imageStream = null; FTPFile[] directories = client.listFiles(); long fileLength = (int) getFile(directories, imageUri.substring(slash + 1)).getSize(); try { imageStream = client.retrieveFileStream(imageUri.substring(slash + 1)); } catch (IOException e) { // Read all data to allow reuse connection (http://bit.ly/1ad35PY) IoUtils.readAndCloseStream(imageStream); throw e; } return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), fileLength); }
From source file:com.cloudhopper.commons.rfs.provider.FtpRemoteFileSystem.java
public void connect() throws FileSystemException { // make sure we don't connect twice if (ftp != null) { throw new FileSystemException("Already connected to FTP(s) server"); }//from w w w. ja v a 2 s . co m // either create an SSL FTP client or normal one if (getProtocol() == Protocol.FTPS) { try { ftp = new FTPSClient(); } catch (Exception e) { //} catch (NoSuchAlgorithmException e) { throw new FileSystemException("Unable to create FTPS client: " + e.getMessage(), e); } } else { ftp = new FTPClient(); } // // connect to ftp(s) server // try { int reply; // either connect to the default port or an overridden one if (getURL().getPort() == null) { ftp.connect(getURL().getHost()); } else { ftp.connect(getURL().getHost(), getURL().getPort().intValue()); } // After connection attempt, check reply code to verify we're connected reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // make sure we're definitely disconnected before we throw exception try { ftp.disconnect(); } catch (Exception e) { } ftp = null; throw new FileSystemException("FTP server refused connection (replyCode=" + reply + ")"); } logger.info("Connected to remote FTP server @ " + getURL().getHost() + " (not authenticated yet)"); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (Exception ex) { } } ftp = null; throw new FileSystemException("Unabled to connect to FTP server @ " + getURL().getHost(), e); } // // login either anonymously or with user/pass combo // try { boolean loggedIn = false; if (getURL().getUsername() == null) { logger.info("Logging in anonymously to FTP server"); loggedIn = ftp.login("anonymous", ""); } else { logger.info("Logging in with username and password to FTP server"); loggedIn = ftp.login(getURL().getUsername(), (getURL().getPassword() == null ? "" : getURL().getPassword())); } // did the login work? if (!loggedIn) { throw new FileSystemException("Login failed with FTP server (reply=" + ftp.getReplyString() + ")"); } // // if we're using a secure protocol, encrypt the data channel // if (getProtocol() == Protocol.FTPS) { logger.info("Requesting FTP data channel to also be encrypted with SSL/TLS"); ((FTPSClient) ftp).execPROT("P"); // ignore if this actually worked or not -- file just fail to copy } // // make sure we're using binary files // ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to binary file mode (reply=" + ftp.getReplyString() + ")"); } // should we go into passive or active mode? if (mode == Mode.ACTIVE) { ftp.enterLocalActiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to active mode (reply=" + ftp.getReplyString() + ")"); } } else if (mode == Mode.PASSIVE) { ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException( "FTP server failed to switch to passive mode (reply=" + ftp.getReplyString() + ")"); } } // // handle making or changing directories // // if the path is not empty if (!StringUtil.isEmpty(getURL().getPath())) { // recursively iterate thru directory path and attempt to create the path StringTokenizer path = new StringTokenizer(getURL().getPath(), "/"); // create an array list of tokens ArrayList<String> pathParts = new ArrayList<String>(); while (path.hasMoreTokens()) { pathParts.add(path.nextToken()); } // index we'll start searching for int i = 0; // determine path of directories we're going to take if (pathParts.size() > 0 && pathParts.get(i).equals("~")) { // stay in home directory once logged in // just increment what we'll search from i = 1; } else { // change to root directory first if (!ftp.changeWorkingDirectory("/")) { throw new FileSystemException("FTP server failed to change to root directory (reply=" + ftp.getReplyString() + ")"); } } for (; i < pathParts.size(); i++) { // try to change to this directory String pathPart = pathParts.get(i); boolean changedDir = ftp.changeWorkingDirectory(pathPart); if (!changedDir) { if (!mkdir) { // now try to change to it again if (!ftp.changeWorkingDirectory(pathPart)) { throw new FileSystemException("Unable to change to directory " + getURL().getPath() + " on FTP server: " + pathPart + " does not exist"); } } else { // try to create it logger.info("Making new directory on FTP server: " + pathPart); if (!ftp.makeDirectory(pathPart)) { throw new FileSystemException( "Unable to make directory '" + pathPart + "' on FTP server"); } // now try to change to it again if (!ftp.changeWorkingDirectory(pathPart)) { throw new FileSystemException( "Unable to change to new directory '" + pathPart + "' on FTP server"); } } } } // just print out our working directory } else { // staying in whatever directory we were assigned by default // for information purposeds, let's try to print out that dir String currentDir = ftp.printWorkingDirectory(); logger.info("Current FTP working directory: " + currentDir); } } catch (FileSystemException e) { // make sure to disconnect, then rethrow error try { ftp.disconnect(); } catch (Exception ex) { } ftp = null; throw e; } catch (IOException e) { // make sure we're definitely disconnected before we throw exception try { ftp.disconnect(); } catch (Exception ex) { } ftp = null; throw new FileSystemException("Underlying IO exception with FTP server during login and setup process", e); } }
From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java
public FTPClient getFtpClient(HashMap<String, String> params) { String urlServer = params.get("urlServer"); String usuario = params.get("user"); String pass = params.get("pass"); // String workingDir = params.get("workingDir"); FTPClient ret = null;/*from w w w . j a v a 2s .c o m*/ try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(InetAddress.getByName(urlServer)); ftpClient.login(usuario, pass); //Verificar conexin con el servidor. int reply = ftpClient.getReplyCode(); System.out.println("Estatus de conexion FTP:" + reply); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("Conectado exitosamente"); } else { System.out.println("No se pudo conectar con el servidor"); } //directorio de trabajo // ftpClient.changeWorkingDirectory(workingDir); System.out.println("Establecer carpeta de trabajo"); //Activar que se envie cualquier tipo de archivo ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ret = ftpClient; } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } return ret; }