List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:net.paissad.jcamstream.utils.FTPUtils.java
public void estabishConnection() throws SocketException, IOException, FTPException { this.setFtpClient(new FTPClient()); String errMsg;//from ww w .j a va 2 s .co m FTPClient client = this.getFtpClient(); PrintCommandListener listener = new PrintCommandListener(System.out); client.addProtocolCommandListener(listener); // Connects to the FTP server String host = this.getFtpServerHost(); int port = this.getFtpServerPort(); client.connect(host, port); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); errMsg = "Unable to connect to the server " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Login to the FTP server String username = this.getFtpUser(); String pass = this.getFtpPassword(); if (!client.login(username, pass)) { errMsg = "Unable to login to " + this.getFtpServerHost(); this.verifyReplyCode(errMsg); } // Change the current directory String dirname = this.getFtpServerDir(); if (!client.changeWorkingDirectory(dirname)) { System.out.println("Unable to change to the directory '" + dirname + "'."); System.out.println("Going to create the directory !"); this.mkdirs(dirname); System.out.println("Creation of the directory is successful."); } client.changeWorkingDirectory(dirname); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { errMsg = "Unable to change to the directory : " + dirname; this.verifyReplyCode(errMsg); } client.pwd(); }
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
/** * Login into a account/*from w w w. j av a 2 s . c o m*/ * * @return FTPClient object or null * @throws IOException */ public FTPClient login() throws IOException { int reply = 0; FTPClient ftp = new FTPClient(); try { if (port != 0) ftp.connect(getHost(), getPort()); else ftp.connect(getHost()); if (isAnonymous()) ftp.login(ANONYMOUS, GUEST); else if (getSubAccount() != null && !getSubAccount().isEmpty()) ftp.login(getLogin(), getPassword(), getSubAccount()); else ftp.login(getLogin(), getPassword()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString())); if (isPassiveMode()) ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } throw e; } return ftp; }
From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java
private void login(final BapFtpClient client, final PrintCommandListener commandListener) throws IOException { final FTPClient ftpClient = client.getFtpClient(); final BPBuildInfo buildInfo = client.getBuildInfo(); if (commandListener != null) { buildInfo.println(Messages.console_logInHidingCommunication()); ftpClient.removeProtocolCommandListener(commandListener); }/*from w w w . jav a 2 s . c o m*/ final BapFtpCredentials overrideCredentials = (BapFtpCredentials) buildInfo .get(BPBuildInfo.OVERRIDE_CREDENTIALS_CONTEXT_KEY); final String username = overrideCredentials == null ? getUsername() : overrideCredentials.getUsername(); final String password = overrideCredentials == null ? getPassword() : Secret.toString(overrideCredentials.getPassword()); if (!ftpClient.login(username, password)) { exception(client, Messages.exception_logInFailed(username)); } if (commandListener != null) { buildInfo.println(Messages.console_loggedInShowingCommunication()); ftpClient.addProtocolCommandListener(commandListener); } }
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; String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host);/*from w ww . j a v a2s . c o m*/ // 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:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve the content of a result feed URL. * /*from w ww . j av a2 s . 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:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java
/** * Get {@link FTPClient} with initialized connects to server given in properties file * @return/*from ww w .java 2 s.c o m*/ */ public FTPClient getClientInstance() { ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor(); Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() { FTPClient ftpClient = new FTPClient(); boolean connected; public FTPClient call() throws Exception { try { while (!connected) { try { ftpClient.connect(host, port); if (!ftpClient.login(username, password)) { ftpClient.logout(); } connected = true; return ftpClient; } catch (Exception e) { connected = false; } } int reply = ftpClient.getReplyCode(); // FTPReply stores a set of constants for FTP reply codes. if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (Exception e) { log.error(e.getMessage(), e); } return ftpClient; } }); FTPClient ftpClient = new FTPClient(); try { // wait for 100 secs for acquiring conn else terminate ftpClient = future.get(100, TimeUnit.SECONDS); } catch (TimeoutException e) { log.info("FTP client Conn wait thread terminated!"); } catch (InterruptedException e) { log.error(e.getMessage(), e); } catch (ExecutionException e) { log.error(e.getMessage(), e); } ftpclientConnThreadPool.shutdownNow(); return ftpClient; }
From source file:net.audumla.climate.bom.BOMDataLoader.java
private synchronized FTPClient getFTPClient(String host) { FTPClient ftp = ftpClients.get(host); if (ftp == null || !ftp.isAvailable() || !ftp.isConnected()) { ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config);/*from w w w. j a v a 2s . c o m*/ try { ftp.setControlKeepAliveTimeout(30); ftp.setControlKeepAliveReplyTimeout(5); ftp.setDataTimeout(3000); ftp.setDefaultTimeout(1000); int reply; ftp.connect(host); LOG.debug("Connected to " + host); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); LOG.error("FTP server '" + host + "' refused connection."); } else { if (!ftp.login("anonymous", "guest")) { LOG.error("Unable to login to server " + host); } ftp.setSoTimeout(60000); ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); } } catch (IOException e) { LOG.error("Unable to connect to " + host, e); } ftpClients.put(host, ftp); } if (!ftp.isConnected() || !ftp.isAvailable()) { throw new UnsupportedOperationException("Cannot connect to " + host); } return ftp; }
From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java
/** * @param host FTP Host name.// w ww . j a v a 2s . c o m * @param port FTP port. * @param user FTP User. * @param pswd FTP Password. * @param c Context * @return Downloaded name file or blank list if something was going wrong. */ private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) { String result = ""; FTPClient mFTPClient = null; try { mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // Now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // Login using username & password boolean status = mFTPClient.login(user, pswd); mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA); FTPFile[] fileList = mFTPClient.listFiles(); long timestamp = 0l; String nameFile = ""; for (int i = 0; i < fileList.length; i++) { if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) { timestamp = fileList[i].getTimestamp().getTimeInMillis(); nameFile = fileList[i].getName(); } } Log.d(TAG, "File da scaricare: " + nameFile); mFTPClient.enterLocalActiveMode(); File folder = new File(Constants.DIR_ROBOT_IMG); OutputStream outputStream = null; boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } try { outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile); success = mFTPClient.retrieveFile(nameFile, outputStream); } catch (Exception e) { return e.getMessage(); } finally { if (outputStream != null) { outputStream.close(); } } if (success) { result = nameFile; mFTPClient.deleteFile(nameFile); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { if (mFTPClient != null) { try { mFTPClient.logout(); mFTPClient.disconnect(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } } return result; }
From source file:com.tobias.vocabulary_trainer.UpdateVocabularies.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.update_vocabularies_layout); prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE); serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text); serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text); serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text); serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text); serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text); localFileEditText = (EditText) findViewById(R.id.local_file_edit_text); vocabularies = new VocabularyData(this); System.out.println("before updateUIFromPreferences();"); updateUIFromPreferences();//from w ww . jav a 2s . c om System.out.println("after updateUIFromPreferences();"); final Button ServerOkButton = (Button) findViewById(R.id.server_ok); ServerOkButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { System.out.println("ServerOKButton pressed"); savePreferences(); InputStream in; String serverAdresse = serverAdresseEditText.getText().toString(); String serverUsername = serverUsernameEditText.getText().toString(); String serverPassword = serverPasswordEditText.getText().toString(); int serverPort = Integer.parseInt(serverPortEditText.getText().toString()); String serverFile = serverFileEditText.getText().toString(); FTPClient ftp; ftp = new FTPClient(); try { int reply; System.out.println("try to connect to ftp server"); ftp.connect(serverAdresse, serverPort); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("connected to ftp server"); } else { ftp.disconnect(); System.out.println("FTP server refused connection."); } // transfer files System.out.println("try to login"); ftp.login(serverUsername, serverPassword); System.out.println("current working directory: " + ftp.printWorkingDirectory()); System.out.println("try to start downloading"); in = ftp.retrieveFileStream(serverFile); // files transferred //write to database and textfile on sdcard vocabularies.readVocabularies(in, false); ftp.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } // settings.populateSpinners(); finish(); } }); final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok); LocalFileOkButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { File f = new File(Environment.getExternalStorageDirectory(), localFileEditText.getText().toString()); savePreferences(); vocabularies.readVocabularies(f, false); // settings.populateSpinners(); finish(); } }); final Button CancelButton = (Button) findViewById(R.id.Cancel); CancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); vocabularies.close(); }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downIBSA() { String fl = ""; String fp = ""; String fs = ""; try {/* w ww.j a v a 2s . c o 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(); } } }