List of usage examples for org.apache.commons.net.ftp FTPClient completePendingCommand
public boolean completePendingCommand() throws IOException
From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java
/** * @param args the command line arguments *//*from w w w.j a v a2 s .c o m*/ public static void main(String[] args) { SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH"); GMT.setTimeZone(TimeZone.getTimeZone("GMT-2")); System.out.println(GMT.format(new Date())); FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { //Connecting to AirNow FTP server to get the fresh AQI data ftpClient.connect("ftp.airnowapi.org"); ftpClient.login("pixelshade", "GZDN8uqduwvk"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //downloading .grib2 file File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of)); InputStream instr = ftpClient .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2"); byte[] bytesArray = new byte[4096]; int bytesRead = -1; while ((bytesRead = instr.read(bytesArray)) != -1) { outstr.write(bytesArray, 0, bytesRead); } //Close used resources ftpClient.completePendingCommand(); outstr.close(); instr.close(); // logout the user ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { //disconnect from AirNow server ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } try { //Open .grib2 file final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath()); //The data type needed - AQI; since it isn't defined in GRIB2 standard, //Aerosol type is used instead; look AirNow API documentation for details. GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl"); //Get the coordinate system for selected data type; //cut the rectangle to work with - time and height axes aren't present in these files //and latitude/longitude go "-1", which means all the data provided. GridCoordSystem AQIGCS = AQI.getCoordinateSystem(); List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes(); Array AQIslice = AQI.readDataSlice(0, 0, -1, -1); //Variables for iterating through coordinates VariableDS var = AQI.getVariable(); Index index = AQIslice.getIndex(); //Variables for counting lat/long from the indices provided double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1); double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0); double curX = AQI_XY.get(2).getMinValue(); double curY = AQI_XY.get(1).getMinValue(); //Output details OutputStream ValLog = new FileOutputStream("USA_AQI.json"); Writer ValWriter = new OutputStreamWriter(ValLog); for (int j = 0; j < index.getShape(0); j++) { for (int i = 0; i < index.getShape(1); i++) { float val = AQIslice.getFloat(index.set(j, i)); //Write the AQI value and its coordinates if it's present by i/j indices if (!Float.isNaN(val)) ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val + ",\r\n},\r\n"); curX += stepX; } curY += stepY; curX = AQI_XY.get(2).getMinValue(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:examples.server2serverFTP.java
public static final void main(String[] args) { String server1, username1, password1, file1; String server2, username2, password2, file2; FTPClient ftp1, ftp2; ProtocolCommandListener listener;//w w w . j a v a2s . c om if (args.length < 8) { System.err.println("Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"); System.exit(1); } server1 = args[0]; username1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; username2 = args[5]; password2 = args[6]; file2 = args[7]; listener = new PrintCommandListener(new PrintWriter(System.out)); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; 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; 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:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *///from w w w . j a v a2 s . com public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.xiangzhurui.util.ftp.ServerToServerFTP.java
public static void main(String[] args) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;/*from w ww. j ava 2s. c o m*/ int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; if (args.length < 8) { System.err.println( "Usage: com.xzr.practice.util.ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"); System.exit(1); } server1 = args[0]; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = args[5]; password2 = args[6]; file2 = args[7]; 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, com.xzr.practice.util.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:ServeurFTP.java
public static void main(String[] args) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;/*w w w. ja v a 2s .c om*/ int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; if (args.length < 8) { System.err.println("Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"); System.exit(1); } server1 = args[0]; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = args[5]; password2 = args[6]; file2 = args[7]; 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:com.feilong.tools.net.ZClientTest.java
/** * Gets the files.//from w w w .ja v a2s. c om * * @param ftp * the ftp * @param localDir * the local dir * @throws IOException * Signals that an I/O exception has occurred. */ private static void testGetFiles(FTPClient ftp, File localDir) throws IOException { String[] names = ftp.listNames(); for (String name : names) { File file = new File(localDir.getPath() + File.separator + name); if (!file.exists()) { file.createNewFile(); } long pos = file.length(); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(pos); ftp.setRestartOffset(pos); InputStream is = ftp.retrieveFileStream(name); if (is == null) { log.info("no such file:" + name); } else { log.info("start getting file:" + name); int b; while ((b = is.read()) != -1) { raf.write(b); } is.close(); if (ftp.completePendingCommand()) { log.info("done!"); } else { log.info("can't get file:" + name); } } raf.close(); } }
From source file:com.kcs.core.utilities.FtpUtil.java
public static boolean putFileByStream(String hostname, int port, String username, String password, String remoteFileName, String localFileName) throws Exception { FTPClient ftp = null; boolean result = false; try {/*from w ww . ja v a 2 s .c o m*/ ftp = FtpUtil.openFtpConnect(hostname, port, username, password); if (null != ftp && ftp.isConnected()) { File localFile = new File(localFileName); InputStream inputStream = new FileInputStream(localFile); System.out.println("Start uploading file"); OutputStream outputStream = ftp.storeFileStream(remoteFileName); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) { outputStream.write(bytesIn, 0, read); } inputStream.close(); outputStream.close(); boolean completed = ftp.completePendingCommand(); if (completed) { System.out.println("file is uploaded successfully."); result = true; } } } catch (Exception e) { e.printStackTrace(); throw new Exception("Error : " + e.getMessage()); } finally { FtpUtil.closeFtpServer(ftp); } return result; }
From source file:heigit.ors.routing.traffic.providers.FtpDataSource.java
@Override public String getMessage() throws IOException { String message = null;//from w w w . j ava 2 s .c om try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(2); String remoteFile1 = "/" + file; InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1); message = StreamUtility.readStream(inputStream, "iso-8859-1"); Boolean success = ftpClient.completePendingCommand(); if (success) { System.out.println("File has been downloaded successfully."); } inputStream.close(); } catch (IOException e) { /* SendMail mail = new SendMail(); try { mail.postMail(this.properties.getProperty("mail"), "TMC-Fehler", e.getStackTrace().toString(), "TMC@Fehlermeldung.de", this.properties .getProperty("smtpHost"), this.properties .getProperty("smtpUser"), this.properties .getProperty("smtpPort")); } catch (MessagingException e1) { e1.printStackTrace(); } this.logger.debug("Error with FTP connection " + e.getLocalizedMessage(), e); throw new DownloadException( "Error while downloading file from FTP " + e.getLocalizedMessage(), e); */ } return message; }
From source file:net.paissad.jcamstream.utils.FTPUtils.java
/** * Logout and then disconnect from the FTP server. * /*from ww w. j a va 2 s . com*/ * @throws IOException * * @see org.apache.commons.net.ftp.FTPClient#logout() * @see org.apache.commons.net.ftp.FTPClient#disconnect() */ public void logoutAndDisconnect() throws IOException { FTPClient client = this.getFtpClient(); if (client.isConnected() && !FTPReply.isPositiveIntermediate(client.getReplyCode())) { client.logout(); client.disconnect(); System.out.println("Disconnected successfully from FTP server."); } if (client.isConnected() && !client.completePendingCommand()) { System.err.println("Something failed !"); } }
From source file:com.clickha.nifi.processors.util.FTPTransferV2.java
@Override public void flush() throws IOException { final FTPClient client = getClient(null); client.completePendingCommand(); }