List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:com.eryansky.common.utils.ftp.FtpFactory.java
/** * FTP?./*from w w w. j a va 2 s. co m*/ * * @param remotePath * FTP? * @param fileName * ??? * @param localPath * ?? * @return */ public boolean ftpDownFile(String remotePath, String fileName, String localPath) { // ? boolean success = false; // FTPClient FTPClient ftp = new FTPClient(); ftp.setControlEncoding("GBK"); try { int reply; // FTP? // ??ftp.connect(url)?FTP? ftp.connect(url, port); // ftp ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } // ftp.changeWorkingDirectory(remotePath); // FTPFile[] fs = ftp.listFiles(); // ?? for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { // ??? File localFile = new File(localPath + "/" + ff.getName()); // ? OutputStream is = new FileOutputStream(localFile); // ftp.retrieveFile(ff.getName(), is); is.close(); success = true; } } ftp.logout(); // ? } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
From source file:com.taurus.compratae.appservice.impl.EnvioArchivoFTPServiceImpl.java
public void conectarFTP(Archivo archivo) { FTPClient client = new FTPClient(); /*String sFTP = "127.0.0.1"; String sUser = "tae";/*www . j av a 2 s . com*/ String sPassword = "tae";*/ String sFTP = buscarParametros(FTP_SERVER); String sUser = buscarParametros(FTP_USER); String sPassword = buscarParametros(FTP_PASSWORD); /////////////////////////////////// //String[] lista; try { client.connect(sFTP); boolean login = client.login(sUser, sPassword); System.out.println("1. Directorio de trabajo: " + client.printWorkingDirectory()); client.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = null; buffIn = new BufferedInputStream(new FileInputStream(archivo.getNombre())); client.enterLocalPassiveMode(); StringTokenizer tokens = new StringTokenizer(archivo.getNombre(), "/");//Para separar el nombre de la ruta. int i = 0; String nombre = ""; while (tokens.hasMoreTokens()) { if (i == 1) { nombre = tokens.nextToken(); i++; } else { i++; } } client.storeFile(nombre, buffIn); buffIn.close(); /*lista = client.listNames(); for (String lista1 : lista) { System.out.println(lista1); }*/ //client.changeWorkingDirectory("\\done"); //System.out.println("2. Working Directory: " + client.printWorkingDirectory()); client.logout(); client.disconnect(); System.out.println("Termin de conectarme al FTP!!"); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java
/** * {@inheritDoc}/* w ww.j ava 2 s.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:dk.netarkivet.common.distribute.IntegrityTestsFTP.java
public void testWrongChecksumThrowsError() throws Exception { Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.FTPRemoteFile"); RemoteFile rf = RemoteFileFactory.getInstance(testFile2, true, false, true); // upload error to ftp server File temp = File.createTempFile("foo", "bar"); FTPClient client = new FTPClient(); client.connect(Settings.get(CommonSettings.FTP_SERVER_NAME), Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT))); client.login(Settings.get(CommonSettings.FTP_USER_NAME), Settings.get(CommonSettings.FTP_USER_PASSWORD)); Field field = FTPRemoteFile.class.getDeclaredField("ftpFileName"); field.setAccessible(true);/* w ww. ja v a2 s. co m*/ String filename = (String) field.get(rf); client.storeFile(filename, new ByteArrayInputStream("foo".getBytes())); client.logout(); try { rf.copyTo(temp); fail("Should throw exception on wrong checksum"); } catch (IOFailure e) { // expected } assertFalse("Destination file should not exist", temp.exists()); }
From source file:edu.mda.bioinfo.ids.DownloadFiles.java
private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile) throws IOException, Exception { FTPClient ftp = new FTPClient(); try {/*from ww w .j a va 2s . co m*/ int reply = 0; boolean replyB = false; ftp.connect(theServer); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } else { ftp.login("anonymous", "anonymous"); replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to login to " + theServer); } OutputStream output = new FileOutputStream(theLocalFile); replyB = ftp.retrieveFile(theServerFile, output); System.out.print(ftp.getReplyString()); System.out.println("replyB= " + replyB); if (false == replyB) { throw new Exception("Unable to retrieve " + theServerFile); } } ftp.logout(); } catch (IOException rethrownExp) { System.err.println("exception " + rethrownExp.getMessage()); throw rethrownExp; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignore) { // do nothing } } } }
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 ww w . j ava 2 s.c om 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.jmeter.alfresco.utils.FtpUtils.java
/** * Upload directory or file.//from ww w .ja va2 s .c o m * * @param host the host * @param port the port * @param userName the user name * @param password the password * @param fromLocalDirOrFile the local dir * @param toRemoteDirOrFile the remote dir * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String uploadDirectoryOrFile(final String host, final int port, final String userName, final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile) throws IOException { final FTPClient ftpClient = new FTPClient(); String responseMessage = Constants.EMPTY; try { // Connect and login to get the session ftpClient.connect(host, port); final int replyCode = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { final boolean loginSuccess = ftpClient.login(userName, password); if (loginSuccess) { LOG.debug("Connected to remote host!"); //Use local passive mode to pass fire-wall //In this mode a data connection is made by opening a port on the server for the client to connect //and this is not blocked by fire-wall. ftpClient.enterLocalPassiveMode(); final File localDirOrFileObj = new File(fromLocalDirOrFile); if (localDirOrFileObj.isFile()) { LOG.debug("Uploading file: " + fromLocalDirOrFile); uploadFile(ftpClient, fromLocalDirOrFile, toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName()); } else { uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY); } responseMessage = "Upload completed successfully!"; } else { responseMessage = "Could not login to the remote host!"; } //Log out and disconnect from the server once FTP operation is completed. if (ftpClient.isConnected()) { try { ftpClient.logout(); } catch (IOException ignored) { LOG.error("Ignoring the exception while logging out from remote host: ", ignored); } try { ftpClient.disconnect(); LOG.debug("Disconnected from remote host!"); } catch (IOException ignored) { LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored); } } } else { responseMessage = "Host connection failed!"; } LOG.debug("ResponseMessage:=> " + responseMessage); } catch (IOException ioexcp) { LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp); throw ioexcp; } return responseMessage; }
From source file:com.claim.controller.FileTransferController.java
public void readFilesFromServer(String targetDirectory) { FTPClient ftpClient = new FTPClient(); try {//from w w w. j a v a2 s .c o m 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:com.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java
private void checkConnect(FTPClient ftp, String server, String login, String password) throws IOException { try {//from w w w . j a v a 2 s .c o m if (ftp.isConnected()) if (ftp.sendNoOp()) return; } catch (FTPConnectionClosedException e) { Logging.warn(e); } ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(server); ftp.login(login, password); }
From source file:com.clican.pluto.cms.core.service.impl.SiteServiceImpl.java
public FTPClient getFTPClient(ISite site) throws IOException { String url = site.getUrl();//from w w w. j a v a2 s . c om if (url == null) { return null; } if (url.startsWith("ftp://")) { int port = 21; String hostname = null; try { url = url.substring(6); if (url.indexOf(":") != -1) { hostname = url.substring(0, url.indexOf(":")); if (url.endsWith("/")) { port = Integer.parseInt(url.substring(url.indexOf(":") + 1, url.length() - 1)); } else { port = Integer.parseInt(url.substring(url.indexOf(":") + 1)); } } else { if (url.endsWith("/")) { hostname = url.substring(0, url.length() - 1); } else { hostname = url; } } } catch (Exception e) { throw new UnknownHostException(url); } FTPClient client = new FTPClient(); client.connect(hostname, port); if (log.isDebugEnabled()) { log.debug("Connected to " + url + "."); log.debug(client.getReplyString()); } int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); log.warn("FTP server " + url + " refused connection."); return null; } if (StringUtils.isNotEmpty(site.getUsername())) { boolean login = client.login(site.getUsername(), site.getPassword()); if (!login) { client.disconnect(); return null; } } return client; } return null; }