List of usage examples for org.apache.commons.net.ftp FTPClient isConnected
public boolean isConnected()
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
/** * Login into a account/*ww w . ja v a 2s.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:com.eryansky.common.utils.ftp.FtpFactory.java
/** * FTP?.//from w w w. j ava 2s . 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:facturacion.ftp.FtpServer.java
public static InputStream getTokenInputStream2(String remote_file_ruta) { FTPClient ftpClient = new FTPClient(); File downloadFile1 = null;// ww w.j a v a 2s . c o m try { downloadFile1 = File.createTempFile("tmptokenEmpresa", ".p12"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken), Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken))); ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken), Config.getInstance().getProperty(Config.PassFtpToken)); //ftpClient.connect(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_SERVER), Integer.parseInt( ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_PORT)) ); //ftpClient.login(ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FTP_USER), ConfigurationFtp.getInstance().getProperty(ConfigurationFtp.FT_PSWD)); //ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); boolean success; String remoteFile1 = "/0702144833/kepti_lenin_pereira_tinoco.p12"; downloadFile1 = new File("C:/Users/aaguerra/Desktop/firmado2.p12"); OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1)); success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\arpr\\documentacion\\kepti_lenin_pereira_tinoco.p12"); FileInputStream fis = new FileInputStream( "C:\\Users\\aaguerra\\Desktop\\arpr\\archivos\\0702144833\\kepti_lenin_pereira_tinoco.p12"); InputStream is = fis; if (success) { System.out.println("File #1 has been downloaded successfully. 222adadfsdfadf"); } else { System.out.println("File #1 has been downloaded successfully. 3333"); } ; return is; } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 222"); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { System.out.println("File #1 has been downloaded successfully. 3"); return null; //ex.printStackTrace(); } } return null; }
From source file:com.hackengine_er.muslumyusuf.DBOperations.java
private boolean uploadToFTP(String username, String fileName, InputStream inputStream) { FTPClient client = new FTPClient(); try {// ww w . j ava2 s. co m client.connect(Configuration.FTPClient()); if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) { client.setDefaultTimeout(10000); client.setFileType(FTPClient.BINARY_FILE_TYPE); if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) { return true; } } } catch (IOException e) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e); } finally { if (client.isConnected()) { try { client.logout(); client.disconnect(); } catch (IOException ex) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex); } } } return false; }
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();/* w ww . ja v a 2 s .c o m*/ 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.muslumyusuf.DBOperations.java
private boolean uploadToFTP(String username, String fileName, InputStream inputStream) { FTPClient client = new FTPClient(); try {/*from w w w. j a v a2 s .c o m*/ client.connect(Initialize.FTPClient()); if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) { client.setDefaultTimeout(10000); client.setFileType(FTPClient.BINARY_FILE_TYPE); if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) { return true; } } } catch (IOException e) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e); } finally { if (client.isConnected()) { try { client.logout(); client.disconnect(); } catch (IOException ex) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex); } } } return false; }
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 w ww. j a va 2 s . c o m*/ 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.dp2345.plugin.ftp.FtpPlugin.java
@Override public void upload(String path, File file, String contentType) { PluginConfig pluginConfig = getPluginConfig(); if (pluginConfig != null) { String host = pluginConfig.getAttribute("host"); Integer port = Integer.valueOf(pluginConfig.getAttribute("port")); String username = pluginConfig.getAttribute("username"); String password = pluginConfig.getAttribute("password"); FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; try {//from w w w .j a v a 2 s. com inputStream = new FileInputStream(file); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { String directory = StringUtils.substringBeforeLast(path, "/"); String filename = StringUtils.substringAfterLast(path, "/"); if (!ftpClient.changeWorkingDirectory(directory)) { String[] paths = StringUtils.split(directory, "/"); String p = "/"; ftpClient.changeWorkingDirectory(p); for (String s : paths) { p += s + "/"; if (!ftpClient.changeWorkingDirectory(p)) { ftpClient.makeDirectory(s); ftpClient.changeWorkingDirectory(p); } } } ftpClient.storeFile(filename, inputStream); ftpClient.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { } } } } }
From source file:com.mirth.connect.connectors.file.filesystems.FtpConnection.java
public FtpConnection(String host, int port, FileSystemConnectionOptions fileSystemOptions, boolean passive, int timeout, FTPClient client) throws Exception { this.client = client; // This sets the timeout for read operations on data sockets. It does not affect write operations. client.setDataTimeout(timeout);/*ww w . j a va 2 s. co m*/ // This sets the timeout for the initial connection. client.setConnectTimeout(timeout); try { if (port > 0) { client.connect(host, port); } else { client.connect(host); } // This sets the timeout for read operations on the command socket. As per JavaDoc comments, you should only call this after the connection has been opened by connect() client.setSoTimeout(timeout); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.login(fileSystemOptions.getUsername(), fileSystemOptions.getPassword())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IOException("Ftp error"); } initialize(); if (passive) { client.enterLocalPassiveMode(); } } catch (Exception e) { if (client.isConnected()) { client.disconnect(); } throw e; } }
From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java
private static boolean processDownload(final BackgroundTaskStatusProviderSupportingExternalCallImpl status, String downloadURL, String targetFileName, ObjectRef lastStatus, final int thisRun, String server, String remote, final FTPClient ftp) { String username;//from w w w. jav a 2 s. c om String password; String local; username = "anonymous@" + server; password = "anonymous"; local = targetFileName; final ObjectRef myoutputstream = new ObjectRef(); ftp.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent arg0) { // System.out.print("out: " + arg0.getMessage()); status.setCurrentStatusText1("Command: " + arg0.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent arg0) { // System.out.print("in : " + arg0.getMessage()); 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 DOWNLOAD: " + 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 false; } if (!ftp.login("anonymous", "anonymous")) { if (!ftp.login(username, password)) { ftp.disconnect(); status.setCurrentStatusText1("Can't login to FTP server"); status.setCurrentStatusText2("ERROR"); return false; } } 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.listFiles(pathname); OutputStream output = new MyOutputStream(lastStatus, status, new FileOutputStream(local)); myoutputstream.setObject(output); ftp.setRemoteVerificationEnabled(false); long tA = System.currentTimeMillis(); boolean result = ftp.retrieveFile(remote, output); output.close(); long tB = System.currentTimeMillis(); if (!result) { new File(local).delete(); MainFrame.showMessage("Can't download " + downloadURL + ". File not available.", MessageType.INFO); } else { File f = new File(local); System.out.println("Download completed (" + f.getAbsolutePath() + ", " + (f.length() / 1024) + " KB, " + (int) ((f.length() / 1024d / (tB - tA) * 1000d)) + " KB/s)."); } BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() { public void run() { try { synchronized (GUIhelper.class) { if (runIdx == thisRun) { System.out.println("Disconnect FTP connection"); ftp.disconnect(); } } } catch (Exception err) { ErrorMsg.addErrorMessage(err); } } }); return result; } catch (Exception err) { System.out.println("ERROR: FTP DOWNLOAD ERROR: " + err.getMessage()); if (ftp != null && ftp.isConnected()) { try { System.out.println("Disconnect FTP connection (following error condition)"); ftp.disconnect(); } catch (Exception err2) { ErrorMsg.addErrorMessage(err2); } } return false; } }