List of usage examples for org.apache.commons.net.ftp FTPClient disconnect
@Override public void disconnect() throws IOException
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downIBSA() { String fl = ""; String fp = ""; String fs = ""; try {// w ww .ja v a2 s . com FileInputStream glnCodesCsv = new FileInputStream(Constants.DIR_IBSA + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(glnCodesCsv, "UTF-8")); String line; while ((line = br.readLine()) != null) { // Semicolon is used as a separator String[] gln = line.split(";"); if (gln.length > 2) { if (gln[0].equals("IbsaAmiko")) { fl = gln[0]; fp = gln[1]; fs = gln[2]; } } } br.close(); } catch (Exception e) { e.printStackTrace(); } FTPClient ftp_client = new FTPClient(); try { ftp_client.connect(fs, 21); ftp_client.login(fl, fp); ftp_client.enterLocalPassiveMode(); ftp_client.changeWorkingDirectory("data"); 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; } System.out.println("- Connected to server " + fs + "..."); //get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); List<String> list_remote_files = Arrays.asList("Konditionen.csv", "Targeting_diff.csv", "Address.csv"); List<String> list_local_files = Arrays.asList(Constants.FILE_CUST_IBSA, Constants.FILE_TARG_IBSA, Constants.FILE_MOOS_ADDR); if (ftpFiles != null && ftpFiles.length > 0) { int index = 0; for (String remote_file : list_remote_files) { OutputStream os = new FileOutputStream(Constants.DIR_IBSA + "/" + list_local_files.get(index)); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("file downloaded successfully."); else System.out.println("error."); os.close(); index++; } } } 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:boosta.artem.services.FTPResultReader.java
public void readResult() { String server = "62.210.82.210"; int port = 55021; String user = "misha_p"; String pass = "GfhjkM1983"; FTPClient ftpClient = new FTPClient(); try {//from ww w . j a v a 2 s . c o m ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); // APPROACH #1: using retrieveFile(String, OutputStream) String remoteFile = Main.remote_out_path; System.out.println(remoteFile); //String remoteFile = "/results/ttgenerate.txt"; String downlFile = Main.file_name; System.out.println(downlFile); File downloadFile = new File(downlFile); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile)); boolean success = ftpClient.retrieveFile(remoteFile, outputStream); outputStream.close(); if (success) { System.out.println(" ? FTP!!!"); } else { System.out.println(" ? TFP!!!"); } } catch (IOException ex) { System.out.println(" ? FTP !!!"); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { System.out.println(" ? ?? ? FTP!!!"); } } }
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 {// w w w.ja va2 s . com 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:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve the content of a result feed URL. * // w ww . j av a 2s. co m * @param uri * @param encodingOverride * @param userAgent * @param resultHeaders * @return Reader */ private Reader getContent(final URI uri, final String encodingOverride, final String userAgent, final Map<String, String> resultHeaders) { Reader result = null; String contentType = null; // Retrieve the feed try { InputStream inputStream = null; if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) { FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); inputStream = ftpClient.retrieveFileStream(uri.getPath()); } } finally { ftpClient.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("file")) { File file = new File(uri); if (!file.isDirectory()) inputStream = new FileInputStream(uri.getPath()); else inputStream = RSSDirectoryBuilder.build(file); } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { try { HttpGet method = new HttpGet(uri.toString()); if (resultHeaders != null) for (Entry<String, String> resultHeader : resultHeaders.entrySet()) method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue())); if (userAgent != null) method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent); SizeRestrictedHttpResponse response = httpClient.execute(method, new SizeRestrictedResponseHandler(maximumContentLength, uri)); try { if (response != null) { inputStream = new ByteArrayInputStream(response.getResponse()); contentType = response.getContentType() != null ? response.getContentType().getValue() : null; } else return null; } catch (RuntimeException e) { method.abort(); throw e; } } catch (IllegalArgumentException e) { logger.error("Invalid URL " + uri.toString() + " - not returning content", e); return null; } } else { logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed."); return null; } // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection) InputStream readerInputStream = new BufferedInputStream(inputStream); MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata()); try { Reader reader = null; if (mediaType.getType().equals("application")) { if (mediaType.getSubtype().equals("x-gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader(gzipInputStream, encodingOverride), false); else reader = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true) : new XmlReader(gzipInputStream, true), false); gzipInputStream.close(); } else if (mediaType.getSubtype().equals("zip")) { ZipFile zipFile = null; // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead File temporaryFile = File.createTempFile("profiler-", ".zip"); try { FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile); IOUtils.copy(readerInputStream, zipOutputStream); readerInputStream.close(); zipOutputStream.flush(); zipOutputStream.close(); // Create a new entry and process it zipFile = new ZipFile(temporaryFile); Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries(); ZipEntry zipEntry = zipEnumeration.nextElement(); if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) { logger.error( "ZIP files are currently expected to contain one and only one entry, which is to be a file"); return null; } // We currently only perform prolog stripping for ZIP files InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry)); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader( new BufferedInputStream(zipInputStream), encodingOverride), true); else result = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(new BufferedInputStream(zipInputStream), contentType, true) : new XmlReader(new BufferedInputStream(zipInputStream), true), true); } catch (Exception e) { logger.error("An error occurred during ZIP file processing", e); return null; } finally { if (zipFile != null) zipFile.close(); if (!temporaryFile.delete()) logger.error("Unable to delete temporary file"); } } } if (result == null) { if (encodingOverride != null) result = readerToBuffer(new StringBuffer(), reader != null ? reader : new InputStreamReader(readerInputStream, encodingOverride), false); else result = readerToBuffer(new StringBuffer(), reader != null ? reader : contentType != null ? new XmlHtmlReader(readerInputStream, contentType, true) : new XmlReader(readerInputStream, true), false); } } catch (Exception e) { logger.error("An error occurred during stream processing", e); return null; } finally { inputStream.close(); } } catch (IOException e) { logger.error("Could not retrieve the given feed: " + e.getMessage(), e); return null; } return result; }
From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java
public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName, String originalFileName) { if (logger.isDebugEnabled()) { logger.debug("SampleUploadCluster.process called"); }//from w w w . j av a2 s .c om FTPClient ftp = new FTPClient(); OutputStream out = null; File file = new File(sourceRepositoryPath + "/" + maskingFileName); FileInputStream fin = null; BufferedInputStream bin = null; String storeFileName = null; String server = "?IP";//?? ? . ex) 210.25.3.21 try { ftp.connect(server); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); storeFileName = maskingFileName + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); ftp.login("testId", "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length())); if (logger.isDebugEnabled()) { logger.debug(server + " connect success !!! "); } ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/"); out = ftp.storeFileStream(storeFileName); FileCopyUtils.copy(fin, out); if (logger.isDebugEnabled()) { logger.debug(" cluster success !!! "); } } else { ftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (bin != null) bin.close(); ftp.logout(); out = null; bin = null; } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java
public void receive(List<String> fileNames) { try {/* w w w. j a va2 s . co m*/ HashMap<String, String> params = getFtpParams(); FTPClient ftpClient = getFtpClient(params); BufferedInputStream buffIn; ftpClient.enterLocalPassiveMode(); for (String nombre : fileNames) { buffIn = new BufferedInputStream(ftpClient .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP if (ftpClient.getReplyCode() == 150) { System.out.println("Archivo obtenido exitosamente"); // write the inputStream to a FileOutputStream OutputStream outputStream = new FileOutputStream( new File(params.get("localStoreFiles") + File.separator + nombre)); int read = 0; byte[] bytes = new byte[1024]; while ((read = buffIn.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } buffIn.close(); //Cerrar envio de arcivos al FTP outputStream.close(); } else { System.out.println( "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode()); } } ftpClient.logout(); //Cerrar sesin ftpClient.disconnect();//Desconectarse del servidor } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
From source file:FTP.Uploader.java
public void uploadFile(String filename) throws IOException { FTPClient ftpclient = new FTPClient(); FileInputStream fis = null;/*from w ww .ja v a 2s. com*/ 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.maxl.java.aips2sqlite.AllDown.java
public void downDesitin() { String fl = ""; String fp = ""; String fs = ""; try {/* ww w . j a v a2 s . c o m*/ FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8")); String line; while ((line = br.readLine()) != null) { // Semicolon is used as a separator String[] gln = line.split(";"); if (gln.length > 2) { if (gln[0].equals("ftp_amiko")) { fl = gln[0]; fp = gln[1]; fs = gln[2]; } } } br.close(); } catch (Exception e) { e.printStackTrace(); } FTPClient ftp_client = new FTPClient(); try { ftp_client.connect(fs, 21); ftp_client.login(fl, fp); ftp_client.enterLocalPassiveMode(); ftp_client.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("- Connected to server " + fs + "..."); // Set working directory String working_dir = "ywesee_in"; ftp_client.changeWorkingDirectory(working_dir); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } // Get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { // ... then download all csv files for (FTPFile f : ftpFiles) { String remote_file = f.getName(); if (remote_file.endsWith("csv")) { String local_file = remote_file; if (remote_file.startsWith("Kunden")) local_file = Constants.FILE_CUST_DESITIN; if (remote_file.startsWith("Artikel")) local_file = Constants.FILE_ARTICLES_DESITIN; OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("success."); else System.out.println("error."); os.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:ServeurFTP.java
public ServeurFTP(String server10, String username10, String password10, String file10, String server20, String username20, String password20, String file20) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;//from w ww . j av a2 s .co m int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; server1 = server10; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = username10; password1 = password10; file1 = file10; server2 = server20; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = username20; password2 = password20; file2 = file20; listener = new PrintCommandListener(new PrintWriter(System.out), true); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } try { int reply; if (port2 > 0) { ftp2.connect(server2, port2); } else { ftp2.connect(server2); } System.out.println("Connected to " + server2 + "."); reply = ftp2.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp2.disconnect(); System.err.println("FTP server2 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp2.isConnected()) { try { ftp2.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server2."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp1.login(username1, password1)) { System.err.println("Could not login to " + server1); break __main; } if (!ftp2.login(username2, password2)) { System.err.println("Could not login to " + server2); break __main; } // Let's just assume success for now. ftp2.enterRemotePassiveMode(); ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort()); // Although you would think the store command should be sent to server2 // first, in reality, ftp servers like wu-ftpd start accepting data // connections right after entering passive mode. Additionally, they // don't even send the positive preliminary reply until after the // transfer is completed (in the case of passive mode transfers). // Therefore, calling store first would hang waiting for a preliminary // reply. if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) { // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) { // We have to fetch the positive completion reply. ftp1.completePendingCommand(); ftp2.completePendingCommand(); } else { System.err.println("Couldn't initiate transfer. Check that filenames are valid."); break __main; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (ftp1.isConnected()) { ftp1.logout(); ftp1.disconnect(); } } catch (IOException e) { // do nothing } try { if (ftp2.isConnected()) { ftp2.logout(); ftp2.disconnect(); } } catch (IOException e) { // do nothing } } }
From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java
/** * {@inheritDoc}/*from w w w . j ava 2s . co 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; } }