List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion
public static boolean isPositiveCompletion(int reply)
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#put(String, String, * String, String, java.util.Map)/*from w w w . j ava 2 s. c o m*/ */ @Override public boolean put(String localDirectory, String localFile, String remoteDirectory, String remoteFile, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean result = false; FileInputStream input = null; try { File localPathname = new File(localDirectory, localFile); if (!localPathname.isAbsolute()) { throw new RemoteManagerException("Local pathname (" + localPathname + ") is NOT absolute."); } input = new FileInputStream(localPathname); logger.debug("Uploading local file " + localPathname + (remoteDirectory != null ? " to remote directory " + remoteDirectory : " to current remote working directory") + "..."); if (remoteFile != null) { logger.debug("Renaming remote file to " + remoteFile); } if (remoteDirectory != null) { changeWorkingDirectory(remoteDirectory); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile((remoteFile != null ? remoteFile : localFile), input); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Local file " + localPathname + " uploaded."); 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 (input != null) { try { input.close(); } catch (IOException exc) { logger.warn("Error while closing local file input stream", exc); } } if (isAutoconnect()) { disconnect(); } } }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static InputStream open(URL url) throws IOException { // System.out.println( "URLUtilities.open( "+url+")"); InputStream stream = null;// ww w. j av a 2 s.c o m String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { try { DefaultAuthenticator authenticator = Main.getDefaultAuthenticator(); URL newURL = new URL(URLUtilities.toString(url)); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication( new PasswordAuthentication(username, password.toCharArray())); } stream = newURL.openStream(); if (authenticator != null && password != null && username != null) { authenticator.setPasswordAuthentication(null); } } catch (Exception e) { // System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage()); // try it with webdav WebdavResource webdav = createWebdavResource(toString(url), username, password); stream = webdav.getMethodData(toString(url)); webdav.close(); } } else if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); try { // System.out.println( "Connecting to: "+host+" ..."); client = new FTPClient(); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Could not connect."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in using: "+username+", "+password+" ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Opening file \""+url.getFile()+"\" ..."); stream = client.retrieveFileStream(url.getFile()); // System.out.println( "File opened."); // System.out.println( "Disconnecting ..."); client.disconnect(); // System.out.println( "Disconnected."); } catch (IOException e) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException f) { // do nothing e.printStackTrace(); } } throw new IOException("Could not connect to FTP Server \"" + host + "\"."); } } else if (protocol.equals("file")) { stream = url.openStream(); } else { //unknown protocol but try anyways try { stream = url.openStream(); } catch (IOException ioe) { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } } return stream; }
From source file:VentanaPrincipal.java
private void conectar() { if ((!tfServidor.getText().isEmpty())) { servFTP = tfServidor.getText();// w ww . jav a 2 s.c o m usuario = tfUsuario.getText(); clave = tfContrasena.getText(); lblMens.setText("Nos conectamos a: " + servFTP); try { cliente.connect(servFTP); boolean login = cliente.login(usuario, clave); if (login) lblMens.setText("Login correcto "); else { lblMens.setText("Login incorrecto "); cliente.disconnect(); System.exit(0); } lblRuta.setText(cliente.printWorkingDirectory()); FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace simb." }; for (int i = 0; i < files.length; i++) { listFicheros.add(files[i].getName() + "- " + tipos[files[i].getType()]); } tfServidor.setEnabled(false); tfUsuario.setEnabled(false); tfContrasena.setEnabled(false); btnConect.setEnabled(false); btnSubir.setEnabled(true); btnDescargar.setEnabled(true); btnEliminar.setEnabled(true); btnEliminarCar.setEnabled(true); btnCrear.setEnabled(true); } catch (IOException ex) { Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(cliente.getReplyString()); int respuesta = cliente.getReplyCode(); if (!FTPReply.isPositiveCompletion(respuesta)) { try { cliente.disconnect(); } catch (IOException ex) { Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Conexin rechazada: " + respuesta); System.exit(0); } } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#put(InputStream, String, * String, java.util.Map)//from w w w .j a va 2 s. c om */ @Override public boolean put(InputStream inputDataStream, String remoteDirectory, String remoteFile, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean result = false; try { logger.debug("Uploading stream " + (remoteDirectory != null ? " to remote directory " + remoteDirectory : " to current remote working directory") + "..."); if (remoteFile != null) { logger.debug("Renaming remote file to " + remoteFile); } if (remoteDirectory != null) { changeWorkingDirectory(remoteDirectory); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile(remoteFile, inputDataStream); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Stream uploaded."); 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 (isAutoconnect()) { disconnect(); } } }
From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java
private static ArrayList<String> listFiles(final BackgroundTaskStatusProviderSupportingExternalCall status, String downloadURL, String server, String remotePath, final FTPClient ftp) { String username;//from w w w . j a v a 2s. com String password; username = "anonymous@" + server; password = "anonymous"; final ObjectRef myoutputstream = new ObjectRef(); ftp.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent arg0) { status.setCurrentStatusText1("Command: " + arg0.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent arg0) { status.setCurrentStatusText2("Message: " + arg0.getMessage()); if (myoutputstream.getObject() != null) { String msg = arg0.getMessage(); if (msg.indexOf("Opening BINARY mode") >= 0) { if (msg.indexOf("(") > 0) { msg = msg.substring(msg.indexOf("(") + "(".length()); if (msg.indexOf(" ") > 0) { msg = msg.substring(0, msg.indexOf(" ")); try { long max = Long.parseLong(msg); MyOutputStream os = (MyOutputStream) myoutputstream.getObject(); os.setMaxBytes(max); } catch (Exception e) { System.out.println( "Could not determine file length for detailed progress information"); } } } } } } }); System.out.println("FTP LIST DIRECTORY: " + downloadURL); try { if (ftp.isConnected()) { status.setCurrentStatusText2("Using open FTP connection"); System.out.println("Reusing open FTP connection"); } else { ftp.connect(server); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); status.setCurrentStatusText1("Can't connect to FTP server"); status.setCurrentStatusText2("ERROR"); return new ArrayList<String>(); } if (!ftp.login("anonymous", "anonymous")) { if (!ftp.login(username, password)) { ftp.disconnect(); status.setCurrentStatusText1("Can't login to FTP server"); status.setCurrentStatusText2("ERROR"); return new ArrayList<String>(); } } status.setCurrentStatusText1("Set Binary Transfer Mode"); ftp.setFileType(FTP.BINARY_FILE_TYPE); status.setCurrentStatusText2("Activate Passive Transfer Mode"); ftp.enterLocalPassiveMode(); } status.setCurrentStatusText1("Start download..."); status.setCurrentStatusText2("Please Wait."); ftp.setRemoteVerificationEnabled(false); FTPFile[] res = ftp.listFiles(remotePath); ArrayList<String> result = new ArrayList<String>(); for (FTPFile r : res) { result.add(r.getName()); } return result; } catch (Exception err) { ErrorMsg.addErrorMessage(err); if (ftp != null && ftp.isConnected()) { try { System.out.println("Disconnect FTP connection (following error condition)"); ftp.disconnect(); } catch (Exception err2) { ErrorMsg.addErrorMessage(err2); } } return new ArrayList<String>(); } }
From source file:database.DataLoader.java
private void initFtpClient() throws Exception { ftpClient = new FTPClient(); String server = "92.53.114.87"; String login = "dekkar_ivan"; String password = "qwerty123"; ftpClient.connect(server);//from w w w . j a va 2s . c o m boolean ok = ftpClient.login(login, password); if (!ok) { ftpClient.logout(); throw new Exception(" ? ?? FTP"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new Exception(" ? ?? FTP. ReplyCode"); } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#put(String, String, * String, java.util.Map)// w w w. j a va 2 s . c o m */ @Override public boolean put(String localDirectory, String localFilePattern, String remoteDirectory, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean oldAutoConnect = isAutoconnect(); setAutoconnect(false); boolean result = false; try { File localDirectoryObj = new File(localDirectory); changeWorkingDirectory(remoteDirectory); File[] localFiles = localDirectoryObj .listFiles(new RegExFileFilter(localFilePattern, RegExFileFilter.ALL)); for (File currLocalFile : localFiles) { boolean partialResult = true; if (currLocalFile.isDirectory()) { partialResult = putDir(currLocalFile.getAbsolutePath(), null, null, optProperties); } else { partialResult = put(localDirectoryObj.getAbsolutePath(), currLocalFile.getName(), null, null, optProperties); } if (!partialResult) { break; } } int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Local directory " + localDirectory + " uploaded"); result = true; } else { logger.warn( "Could not upload local directory " + localDirectory + " (FTP Server NEGATIVE response):"); logServerReply(Level.WARN); } return result; } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { setAutoconnect(oldAutoConnect); if (isAutoconnect()) { disconnect(); } } }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downIBSA() { String fl = ""; String fp = ""; String fs = ""; try {/* www . j a va 2 s . co m*/ 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:com.cladonia.xngreditor.URLUtilities.java
public static void save(URL url, InputStream input, String encoding) throws IOException { // System.out.println( "URLUtilities.save( "+url+", "+encoding+")"); String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("ftp")) { FTPClient client = null;//from ww w . j a v a 2s .com String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host); // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Disconnecting..."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Writing output ..."); OutputStream output = client.storeFileStream(url.getFile()); // if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) { // output.close(); // client.disconnect(); // throw new IOException( "Could not transfer file \""+url.getFile()+"\"."); // } InputStreamReader reader = new InputStreamReader(input, encoding); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); output.close(); // Must call completePendingCommand() to finish command. if (!client.completePendingCommand()) { client.disconnect(); throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } else { client.disconnect(); } } else if (protocol.equals("http") || protocol.equals("https")) { WebdavResource webdav = createWebdavResource(toString(url), username, password); if (webdav != null) { webdav.putMethod(url.getPath(), input); webdav.close(); } else { throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } } else if (protocol.equals("file")) { FileOutputStream stream = new FileOutputStream(toFile(url)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding)); InputStreamReader reader = new InputStreamReader(input, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); } else { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#putDir(String, String, * String, java.util.Map)//from www .j a v a 2 s .c o m */ @Override public boolean putDir(String localDirectory, String remoteParentDirectory, String remoteDirectory, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean oldAutoConnect = isAutoconnect(); setAutoconnect(false); boolean result = false; try { File localDirectoryObj = new File(localDirectory); if (remoteParentDirectory != null) { changeWorkingDirectory(remoteParentDirectory); } if (remoteDirectory == null) { remoteDirectory = localDirectoryObj.getName(); } ftpClient.makeDirectory(remoteDirectory); logger.debug( "Remote directory " + remoteDirectory + " created into " + ftpClient.printWorkingDirectory()); changeWorkingDirectory(remoteDirectory); File[] localFiles = localDirectoryObj.listFiles(); for (File currLocalFile : localFiles) { boolean partialResult = true; if (currLocalFile.isDirectory()) { partialResult = putDir(currLocalFile.getAbsolutePath(), null, null, optProperties); } else { partialResult = put(localDirectoryObj.getAbsolutePath(), currLocalFile.getName(), null, null, optProperties); } if (!partialResult) { break; } } ftpClient.changeToParentDirectory(); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Local directory " + localDirectory + " uploaded"); result = true; } else { logger.warn( "Could not upload local directory " + localDirectory + " (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 { setAutoconnect(oldAutoConnect); if (isAutoconnect()) { disconnect(); } } }