List of usage examples for org.apache.commons.net.ftp FTPClient setFileType
public boolean setFileType(int fileType) throws IOException
From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java
/** * {@inheritDoc}/*from w w w .java 2s. c o m*/ */ @Override public FetchedResourceFtp fetch(final URL targetResource, final long lastModified, final String originalUserAgent) throws IOException, ResourceUnavailableException { final FTPClient ftpClient = new FTPClient(); ftpClient.setSoTimeout(socketTimeout); ftpClient.setDataTimeout(dataTimeout); try { final String host = targetResource.getHost(); final String resourceName = targetResource.getPath(); LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName); ftpClient.connect(host); ftpClient.enterLocalPassiveMode(); if (!ftpClient.login("anonymous", "japt-proxy")) { throw new IOException("Can't login to FTP server"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final FTPFile[] files = ftpClient.listFiles(resourceName); if (files.length == 0) { throw new ResourceUnavailableException("Resource '" + resourceName + "' not found"); } if (files.length > 1) { throw new IOException("Multiple files found"); } final FTPFile file = files[0]; final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file); fetchedResourceFtp .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis()); return fetchedResourceFtp; } catch (final IOException e) { // Closing only in case of an exception - otherwise closed by FetchedResourceFtp if (ftpClient.isConnected()) { ftpClient.disconnect(); } throw e; } }
From source file:com.jsystem.j2autoit.AutoItAgent.java
private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); //connect to the management ftp server int reply = client.getReplyCode(); // check connection if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); }// w w w .j a v a 2 s .co m if (!client.login(user, password)) { //check login throw new Exception("FTP fail to login"); } // FileOutputStream fos = null; try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } }
From source file:com.maxl.java.amikodesk.Emailer.java
private void uploadToFTPServer(Author author, String name, String path) { FTPClient ftp_client = new FTPClient(); try {//from w ww . j a v a 2s. co m ftp_client.connect(author.getS(), 21); ftp_client.login(author.getL(), author.getP()); ftp_client.enterLocalPassiveMode(); ftp_client.changeWorkingDirectory(author.getO()); ftp_client.setFileType(FTP.BINARY_FILE_TYPE); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } File local_file = new File(path); String remote_file = name + ".csv"; InputStream is = new FileInputStream(local_file); System.out.print("Uploading file " + name + " to server " + author.getS() + "... "); boolean done = ftp_client.storeFile(remote_file, is); if (done) System.out.println("file uploaded successfully."); else System.out.println("error."); is.close(); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftp_client.isConnected()) { ftp_client.logout(); ftp_client.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:com.claim.controller.FileTransferController.java
public void readFilesFromServer(String targetDirectory) { FTPClient ftpClient = new FTPClient(); try {//from w ww .j a v a2 s . c om 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); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); FTPFile[] ftpFiles = ftpClient.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { //loop thru files for (FTPFile file : ftpFiles) { if (!file.isFile()) { continue; } System.out.println("File is " + file.getName()); //get output stream OutputStream output; //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName()); output = new FileOutputStream(file.getName()); //get the file from the remote system ftpClient.retrieveFile(file.getName(), output); //close output stream output.close(); //delete the file //ftpClient.deleteFile(file.getName()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java
private FTPClient connectMe() throws IOException { FTPClient ftpclient = new FTPClient(); ftpclient.connect(configurator.host, configurator.port); if (ftpclient.login(configurator.username, configurator.password) == false) { ftpclient.logout();/* w ww .j a v a 2 s. c o m*/ throw new IOException("Can't login to server"); } int reply = ftpclient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply) == false) { ftpclient.disconnect(); throw new IOException("Can't login to server"); } ftpclient.setFileType(FTP.BINARY_FILE_TYPE); if (configurator.passive) { ftpclient.enterLocalPassiveMode(); } else { ftpclient.enterLocalActiveMode(); } ftpclient.changeWorkingDirectory("/" + path); if (ftpclient.printWorkingDirectory().equals("/" + path) == false) { throw new IOException("Can't change working dir : " + "/" + path); } return ftpclient; }
From source file:br.com.atmatech.painel.util.EnviaLogs.java
public void enviarBD(File file, String enderecoFTP, String login, String senha) throws IOException { String nomeArquivo = null;//from w w w.ja v a 2s . co m FTPClient ftp = new FTPClient(); ftp.connect(enderecoFTP); //verifica se conectou com sucesso! if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login(login, senha); } else { //erro ao se conectar ftp.disconnect(); } ftp.changeWorkingDirectory("/atmatech.com.br/ErroLogsPainelFX/"); //abre um stream com o arquivo a ser enviado InputStream is = new FileInputStream(file); //pega apenas o nome do arquivo int idx = file.getName().lastIndexOf(File.separator); if (idx < 0) idx = 0; else idx++; nomeArquivo = file.getName().substring(idx, file.getName().length()); //ajusta o tipo do arquivo a ser enviado ftp.setFileType(FTPClient.BINARY_FILE_TYPE); //faz o envio do arquivo ftp.storeFile(nomeArquivo, is); ftp.disconnect(); }
From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java
/** * _more_//from w w w . ja v a 2 s.com * * @param file * _more_ * @param ignoreErrors * _more_ * * @return _more_ * * @throws Exception * _more_ */ private byte[] readFile(String file, boolean ignoreErrors) throws Exception { if (new File(file).exists()) { return IOUtil.readBytes(IOUtil.getInputStream(file, getClass())); } if (!file.startsWith("ftp:")) { if (ignoreErrors) { return null; } throw new FileNotFoundException("Could not read file: " + file); } URL url = new URL(file); FTPClient ftp = new FTPClient(); try { ftp.connect(url.getHost()); ftp.login("anonymous", "password"); ftp.setFileType(FTP.IMAGE_FILE_TYPE); ftp.enterLocalPassiveMode(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftp.retrieveFile(url.getPath(), bos)) { return bos.toByteArray(); } else { throw new IOException("Unable to retrieve file:" + url); } } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) { System.err.println("ftp error:" + fcce); System.err.println(ftp.getReplyString()); if (!ignoreErrors) { throw fcce; } return null; } catch (Exception exc) { if (!ignoreErrors) { throw exc; } return null; } finally { try { ftp.logout(); } catch (Exception exc) { } try { ftp.disconnect(); } catch (Exception exc) { } } }
From source file:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java
private FTPClient connect() { final FTPClient connection = new FTPClient(); try {//from ww w . jav a 2 s . co m connection.setAutodetectUTF8(true); connection.connect(url.getHost(), port); connection.enterLocalActiveMode(); if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) { throw new SourceException( String.format("Cannot login as anonymous user, reason %s", connection.getReplyString())); } if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) { throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url, connection.getReplyString())); } connection.enterLocalPassiveMode(); connection.setFileType(FTP.BINARY_FILE_TYPE); } catch (final IOException e) { disconnect(connection); throw new SourceException(e); } return connection; }
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. * //from w w w . j a v a 2s .com * @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: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;/* w ww .j av a 2 s. c om*/ 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; }