List of usage examples for org.apache.commons.net.ftp FTPClient connect
public void connect(InetAddress host) throws SocketException, IOException
From source file:org.programmatori.domotica.own.plugin.remote.FTPUtility.java
/** * Funzione che consente la connessione ad un Server FTP * /*from w ww .ja v a 2 s . c o m*/ * @param ftpServer Server FTP * @param username Nome utente per l'accesso * @param password Password per l'accesso * @return Un oggetto di tipo FTPClient contenente il Client per l'accesso */ public static FTPClient connect(String ftpServer, String username, String password) { FTPClient ftp = new FTPClient(); String replyString; try { ftp.connect(ftpServer); ftp.login(username, password); log.info("Connesso a " + ftpServer + "."); replyString = ftp.getReplyString(); log.debug(replyString); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("Il Server FTP ha rifiutato la connessione."); log.error(replyString); return null; } } catch (IOException e) { e.printStackTrace(); } return ftp; }
From source file:org.ramadda.repository.monitor.FtpAction.java
/** * _more_//from w w w .ja v a 2 s . c o m * * * @param monitor _more_ * @param entry _more_ */ protected void entryMatched(EntryMonitor monitor, Entry entry) { FTPClient ftpClient = new FTPClient(); try { Resource resource = entry.getResource(); if (!resource.isFile()) { return; } if (server.length() == 0) { return; } String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false); ftpClient.connect(server); if (user.length() > 0) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); monitor.handleError("FTP server refused connection:" + server, null); return; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (directory.length() > 0) { ftpClient.changeWorkingDirectory(directory); } String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate); InputStream is = new BufferedInputStream( monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath()))); boolean ok = ftpClient.storeUniqueFile(filename, is); is.close(); if (ok) { monitor.logInfo("Wrote file:" + directory + " " + filename); } else { monitor.handleError("Failed to write file:" + directory + " " + filename, null); } } catch (Exception exc) { monitor.handleError("Error posting to FTP:" + server, exc); } finally { try { ftpClient.logout(); } catch (Exception exc) { } try { ftpClient.disconnect(); } catch (Exception exc) { } } }
From source file:org.ramadda.repository.type.FtpTypeHandler.java
/** * _more_//w ww . j ava2 s . c om * * @param server _more_ * @param baseDir _more_ * @param user _more_ * @param password _more_ * * @return _more_ * * @throws Exception _more_ */ public static String test(String server, String baseDir, String user, String password) throws Exception { FTPClient ftpClient = new FTPClient(); try { String file = baseDir; ftpClient.connect(server); //System.out.print(ftp.getReplyString()); ftpClient.login(user, password); // System.out.print(ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); boolean isDir = isDir(ftpClient, file); // System.err.println("file:" + file + " is dir: " + isDir); if (isDir) { FTPFile[] files = ftpClient.listFiles(file); for (int i = 0; i < files.length; i++) { // System.err.println ("f:" + files[i].getName() + " " + files[i].isDirectory() + " " + files[i].isFile()); } } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftpClient.retrieveFile(file, bos)) { // System.err.println(new String(bos.toByteArray())); } else { throw new IOException("Unable to retrieve file:" + file); } } return ""; } finally { closeConnection(ftpClient); } }
From source file:org.ramadda.repository.type.FtpTypeHandler.java
/** * _more_/*from w w w . j av a2s . c om*/ * * @param parentEntry _more_ * * @return _more_ * * @throws Exception _more_ */ private FTPClient getFtpClient(Entry parentEntry) throws Exception { Object[] values = parentEntry.getValues(); if (values == null) { return null; } String server = (String) values[COL_SERVER]; String baseDir = (String) values[COL_BASEDIR]; String user = (String) values[COL_USER]; String password = (String) values[COL_PASSWORD]; if (password != null) { password = getRepository().getPageHandler().processTemplate(password, false); } else { password = ""; } FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server); if (user != null) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; } catch (Exception exc) { System.err.println("Could not connect to ftp server:" + server + "\nError:" + exc); return null; } }
From source file:org.ramadda.util.Utils.java
/** * _more_/* w ww . j a v a 2 s.com*/ * * @param url _more_ * * @return _more_ * * @throws Exception _more_ */ public static FTPClient makeFTPClient(URL url) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.connect(url.getHost()); ftpClient.login("anonymous", ""); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; }
From source file:org.spongepowered.repoindexer.FTPUtils.java
public static boolean uploadFTP(String user, String pass, String server, File local, String remoteLocation) { FTPClient ftpClient = new FTPClient(); boolean done = false; try {//from w w w . j a v a 2 s . c o m ftpClient.connect(server); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); InputStream inputStream = new FileInputStream(local); done = ftpClient.storeFile(remoteLocation, inputStream); inputStream.close(); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); return false; } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } return done; } }
From source file:org.umit.icm.mobile.connectivity.ServiceFTP.java
/** * Returns an FTP Response String.//from w w w. j a va2 s. c om * * @return String * @see FTPClient */ @Override public String connect() { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(getServiceURL()); ftpClient.login("test", "test"); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String reply = ftpClient.getReplyString(); ftpClient.logout(); ftpClient.disconnect(); if (reply != null) return "normal"; return "blocked"; } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
public Thread videoUploadToFTPserver(final Activity activity, final Handler handler, final String latestVideoFile_filename, final String latestVideoFile_absolutepath, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doVideoFTP starting"); // Make the progress bar view visible. ((SSCXferActivity) activity).startedUploading(); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. // FTP; connect preferences here! ///*from ww w . j a v a 2 s. com*/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); String ftpHostName = prefs.getString("defaultFTPhostPreference", null); String ftpUsername = prefs.getString("defaultFTPusernamePreference", null); String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null); // use name of local file. String ftpRemoteFtpFilename = latestVideoFile_filename; // FTP FTPClient ftpClient = new FTPClient(); InetAddress uploadhost = null; try { uploadhost = InetAddress.getByName(ftpHostName); } catch (UnknownHostException e1) { // If DNS resolution fails then abort immediately - show // dialog to // inform user first. e1.printStackTrace(); Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed."); uploadhost = null; } if (uploadhost == null) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean connected = false; try { ftpClient.connect(uploadhost); connected = true; } catch (SocketException e) { e.printStackTrace(); connected = false; } catch (UnknownHostException e) { // e.printStackTrace(); connected = false; } catch (IOException e) { // e.printStackTrace(); connected = false; } if (!connected) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean reply = false; try { reply = ftpClient.login(ftpUsername, ftpPassword); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp.login - video uploading failed."); } // check the reply code here // If we cant login, abort after showing user a dialog. if (!reply) { try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); } // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } // Set File type to binary try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { // e.printStackTrace(); // keep going?! } // BEYOND HERE DONT USE DIALOGS! // Construct the input stream to send to Ftp server, from the // local // video file on the sd card BufferedInputStream buffIn = null; File file = new File(latestVideoFile_absolutepath); try { buffIn = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { // e.printStackTrace(); Log.e(TAG, " got exception on local video file - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... return; } ftpClient.enterLocalPassiveMode(); try { // UPLOAD THE LOCAL VIDEO FILE. ftpClient.storeFile(ftpRemoteFtpFilename, buffIn); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on storeFile - video uploading failed."); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { buffIn.close(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on buff.close - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.logout(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp logout - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp disconnect - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } if (emailAddress != null && ftpHostName != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, ""); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(true); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:password.pwm.svc.telemetry.FtpTelemetrySender.java
private void ftpPut(final TelemetryPublishBean telemetryPublishBean) throws PwmUnrecoverableException { final FTPClient ftpClient; switch (settings.getFtpMode()) { case ftp:/*www.ja v a 2 s . com*/ ftpClient = new FTPClient(); break; case ftps: ftpClient = new FTPSClient(); break; default: JavaHelper.unhandledSwitchStatement(settings.getFtpMode()); throw new UnsupportedOperationException(); } // connect try { LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "establishing " + settings.getFtpMode() + " connection to " + settings.getHost()); ftpClient.connect(settings.getHost()); final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectFtpClient(ftpClient); final String msg = "error " + reply + " connecting to " + settings.getHost(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "connected to " + settings.getHost()); } catch (IOException e) { disconnectFtpClient(ftpClient); final String msg = "unable to connect to " + settings.getHost() + ", error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } // set modes try { ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectFtpClient(ftpClient); final String msg = "error setting file type mode to binary, error=" + reply; throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } } catch (IOException e) { disconnectFtpClient(ftpClient); final String msg = "unable to connect to " + settings.getHost() + ", error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } // authenticate try { ftpClient.login(settings.getUsername(), settings.getPassword()); final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectFtpClient(ftpClient); final String msg = "error authenticating as " + settings.getUsername() + " to " + settings.getHost() + ", error=" + reply; throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "authenticated to " + settings.getHost() + " as " + settings.getUsername()); } catch (IOException e) { disconnectFtpClient(ftpClient); final String msg = "error authenticating as " + settings.getUsername() + " to " + settings.getHost() + ", error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } // upload try { final String filePath = settings.getPath() + "/" + telemetryPublishBean.getId() + ".zip"; final byte[] fileBytes = dataToJsonZipFile(telemetryPublishBean); final ByteArrayInputStream fileStream = new ByteArrayInputStream(fileBytes); LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "preparing to transfer " + fileBytes.length + " bytes to file path " + filePath); final Instant startTime = Instant.now(); ftpClient.storeFile(filePath, fileStream); final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnectFtpClient(ftpClient); final String msg = "error uploading file to " + settings.getHost() + ", error=" + reply; throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "completed transfer of " + fileBytes.length + " in " + TimeDuration.compactFromCurrent(startTime)); } catch (IOException e) { disconnectFtpClient(ftpClient); final String msg = "error uploading file to " + settings.getHost() + ", error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TELEMETRY_SEND_ERROR, msg)); } }
From source file:patcher.FXMLDocumentController.java
private FTPClient ftpConnect(String url) throws IOException { //new ftp client FTPClient ftp = new FTPClient(); //Try to connect try {/*from www. ja v a 2 s . c om*/ ftp.connect(url); } catch (IOException object) { return null; } ftp.enterLocalPassiveMode(); ftp.login("anonymous", ""); return ftp; }