List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
private void Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;/*from ww w.j a va 2 s . c o m*/ try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(SourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); Report = "Server Error"; jLabel6.setText(Report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:ddf.test.itests.catalog.TestFtp.java
private FTPClient createInsecureClient() throws Exception { FTPClient ftp = new FTPClient(); int attempts = 0; while (true) { try {//from ww w . j a v a 2 s .c om ftp.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort())); break; } catch (SocketException e) { // a socket exception can be thrown if the ftp server is still in the process of coming up // or down Thread.sleep(1000); if (attempts++ > 30) { throw e; } } } showServerReply(ftp); int connectionReply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftp.login(USERNAME, PASSWORD); showServerReply(ftp); if (!success) { fail("Could not log in to the FTP server."); } ftp.enterLocalPassiveMode(); ftp.setControlKeepAliveTimeout(300); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; }
From source file:com.netpace.aims.controller.application.WapApplicationHelper.java
public static boolean wapFTPZipFile(File transferFile) throws AimsException { log.debug("wapFTPZipFile FTP Start. FileName: " + transferFile.getName()); boolean loginStatus = false; boolean dirChanged = false; FileInputStream transferStream = null; FTPClient ftpClient = new FTPClient(); ConfigEnvProperties envProperties = ConfigEnvProperties.getInstance(); //ftp server config String ftpServerAddress = envProperties.getProperty("wap.images.ftp.server.address"); String ftpUser = envProperties.getProperty("wap.images.ftp.user.name"); String ftpPassword = envProperties.getProperty("wap.images.ftp.user.password"); String ftpWorkingDirectory = envProperties.getProperty("wap.images.ftp.working.dir"); //general exception for ftp transfer AimsException aimsException = new AimsException("Error"); aimsException.addException(new AimsException("error.wap.app.ftp.transfer")); String errorMessage = ""; boolean transfered = false; try {//from w ww.ja v a 2s. co m ftpClient.connect(ftpServerAddress); loginStatus = ftpClient.login(ftpUser, ftpPassword); log.debug("Connection to server " + ftpServerAddress + " " + (loginStatus ? "success" : "failure")); if (loginStatus) { dirChanged = ftpClient.changeWorkingDirectory(ftpWorkingDirectory); log.debug("change remote directory to " + ftpWorkingDirectory + ": " + dirChanged); if (dirChanged) { transferStream = new FileInputStream(transferFile); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); transfered = ftpClient.storeFile(transferFile.getName(), transferStream); log.debug(transferFile.getName() + " transfered: " + transfered + " on server: " + ftpServerAddress); if (!transfered) { errorMessage = "File: " + transferFile.getName() + " not transfered to " + (ftpServerAddress + "/" + ftpServerAddress); System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } else { errorMessage = "Directory: " + ftpWorkingDirectory + " not found in " + ftpServerAddress; System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } //end loginstatus else { errorMessage = "FTP Authentication failed. \n\nServer: " + ftpServerAddress + "\nUserID: " + ftpUser + "\nPassword: " + ftpPassword; System.out.println("Error in FTP Transfer: " + errorMessage); sendFTPErrorMail(errorMessage); throw aimsException; } } //end try catch (FileNotFoundException e) { System.out.println("Exception: " + transferFile.getName() + " not found in temp directory"); e.printStackTrace();//zip file not found throw aimsException; } catch (IOException ioe) { System.out.println("Exception: Error in connection " + ftpServerAddress); ioe.printStackTrace(); sendFTPErrorMail("Error in connection to : " + ftpServerAddress + "\n\n" + MiscUtils.getExceptionStackTraceInfo(ioe)); throw aimsException; } finally { try { //close stream if (transferStream != null) { transferStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { //logout. Issues QUIT command ftpClient.logout(); } catch (IOException ioex) { ioex.printStackTrace(); } finally { try { //disconnect ftp session ftpClient.disconnect(); } catch (IOException ioexc) { ioexc.printStackTrace(); } } } } } log.debug("wapFTPZipFile FTP end. FileName: " + transferFile.getName() + "\t transfered: " + transfered); return transfered; }
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);//from w ww. j a va 2 s. c om // 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:com.savy3.util.MainframeFTPClientUtils.java
public static FTPClient getFTPConnection(Configuration conf) throws IOException { FTPClient ftp = null; try {//from ww w. j av a2 s . c o m String username = conf.get(DBConfiguration.USERNAME_PROPERTY); String password; if (username == null) { username = "anonymous"; password = ""; } else { password = DBConfiguration.getPassword((JobConf) conf); } String connectString = conf.get(DBConfiguration.URL_PROPERTY); String server = connectString; int port = 0; String[] parts = connectString.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { LOG.warn("Invalid port number: " + e.toString()); } } if (null != mockFTPClient) { ftp = mockFTPClient; } else { ftp = new FTPClient(); } FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS); ftp.configure(config); if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } } catch (IOException ioexp) { throw new IOException("Could not connect to server " + server, ioexp); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString()); } LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); if (!ftp.login(username, password)) { ftp.logout(); throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString()); } // set Binary transfer mode ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.featureValue("LITERAL SITE RDW"); ftp.doCommand("SITE", "RDW"); System.out.println("reply for LITERAL" + ftp.getReplyString()); // Use passive mode as default. ftp.enterLocalPassiveMode(); } catch (IOException ioe) { if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } ftp = null; throw ioe; } return ftp; }
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) throws SocketException, IOException { String[] vehicles = controlledVehicles.split(","); jTextArea1.setText(""); jTextArea1.repaint();//www . ja v a2s .co m showText("Initializing Control Structures"); try { startLocalStructures(vehicles); } catch (Exception e) { GuiUtils.errorMessage(getConsole(), e); return; } AUVS = positions.keySet().size(); showText("Initializing server connection"); FTPClient client = new FTPClient(); boolean PathNameCreated = false; try { client.connect("www.convcao.com", 21); client.login(jTextField1.getText(), new String(jPasswordField1.getPassword())); PathNameCreated = client.makeDirectory("/NEPTUS/" + SessionID); client.logout(); } catch (IOException e) { jLabel6.setText("Connection Error"); throw e; } showText("Sending session data"); InputData initialState = new InputData(); initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()); initialState.SessionID = SessionID; initialState.DemoMode = "1"; initialState.AUVs = "" + positions.keySet().size(); String fileName = SessionID + ".txt"; Gson gson = new Gson(); String json = gson.toJson(initialState); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.write(json); writer.close(); if (PathNameCreated) { jLabel6.setText("Connection Established"); jLabel1.setVisible(true); System.out.println("Uploading first file"); Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()), fileName); //send first file System.out.println("Uploading second file"); Upload("www.convcao.com", "NEPTUS/" + SessionID, "plugins-dev/caoAgent/convcao/com/caoAgent/", jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); //send sparse map System.out.println("Both files uploaded"); jButton1.setEnabled(true); jButton2.setEnabled(true); jTextPane1.setEditable(false); jTextField1.setEditable(false); jPasswordField1.setEditable(false); connectButton.setEnabled(false); renewButton.setEnabled(false); } else { jLabel6.setText(client.getReplyString()); jLabel1.setVisible(false); } myDeleteFile(fileName); showText("ConvCAO control has started"); }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;// ww w.j av a2s .c om try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(sourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + sourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); report = "Server Error"; jLabel6.setText(report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.thebigbang.ftpclient.FTPOperation.java
/** * will force keep the device turned on for all the operation duration. * @param params//from w ww. ja va 2 s . c o m * @return */ @SuppressLint("Wakelock") @SuppressWarnings("deprecation") @Override protected Boolean doInBackground(FTPBundle... params) { Thread.currentThread().setName("FTPOperationWorker"); for (final FTPBundle bundle : params) { FTPClient ftp = new FTPClient(); PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client"); try { // setup ftp connection: InetAddress addr = InetAddress.getByName(bundle.FTPServerHost); //set here the timeout. TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() { @Override public void Occurred(TimeoutException e) { bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; publishProgress(bundle); } }); timeout.start(); ftp.connect(addr, bundle.FTPServerPort); int reply = ftp.getReplyCode(); timeout.Stop(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("connection refuse"); } ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword); if (bundle.OperationType == FTPOperationType.Connect) { bundle.OperationStatus = FTPOperationStatus.Succed; publishProgress(bundle); continue; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); w.acquire(); // then switch between enum of operation types. if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.GetData) { String finalFPFi = bundle.LocalFilePathName; // The remote filename to be downloaded. if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") { File f = new File(bundle.LocalWorkingDirectory); f.mkdirs(); finalFPFi = bundle.LocalWorkingDirectory + finalFPFi; } FileOutputStream fos = new FileOutputStream(finalFPFi); // Download file from FTP server String finalFileN = bundle.RemoteFilePathName; if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") { finalFileN = bundle.RemoteWorkingDirectory + finalFileN; } boolean b = ftp.retrieveFile(finalFileN, fos); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; fos.close(); } else if (bundle.OperationType == FTPOperationType.SendData) { InputStream istr = new FileInputStream(bundle.LocalFilePathName); ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr); istr.close(); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; } else if (bundle.OperationType == FTPOperationType.DeleteData) { throw new IOException("DeleteData is Not yet implemented"); } ftp.disconnect(); // then finish/return. //publishProgress(bundle); } catch (IOException e) { e.printStackTrace(); bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; } try { w.release(); } catch (RuntimeException ex) { ex.printStackTrace(); } publishProgress(bundle); } return true; }
From source file:fr.bmartel.speedtest.SpeedTestTask.java
/** * start FTP download with specific port, user, password. * * @param hostname ftp host/*from w ww .j av a2 s . c o m*/ * @param uri ftp uri * @param user ftp username * @param password ftp password */ public void startFtpDownload(final String hostname, final int port, final String uri, final String user, final String password) { mSpeedTestMode = SpeedTestMode.DOWNLOAD; mErrorDispatched = false; mForceCloseSocket = false; if (mReadExecutorService == null || mReadExecutorService.isShutdown()) { mReadExecutorService = Executors.newSingleThreadExecutor(); } mReadExecutorService.execute(new Runnable() { @Override public void run() { final FTPClient ftpclient = new FTPClient(); try { ftpclient.connect(hostname, port); ftpclient.login(user, password); ftpclient.enterLocalPassiveMode(); ftpclient.setFileType(FTP.BINARY_FILE_TYPE); mDownloadTemporaryPacketSize = 0; mTimeStart = System.currentTimeMillis(); mTimeEnd = 0; if (mRepeatWrapper.isFirstDownload()) { mRepeatWrapper.setFirstDownloadRepeat(false); mRepeatWrapper.setStartDate(mTimeStart); } mDownloadPckSize = new BigDecimal(getFileSize(ftpclient, uri)); if (mRepeatWrapper.isRepeatDownload()) { mRepeatWrapper.updatePacketSize(mDownloadPckSize); } mFtpInputstream = ftpclient.retrieveFileStream(uri); if (mFtpInputstream != null) { final byte[] bytesArray = new byte[SpeedTestConst.READ_BUFFER_SIZE]; int read; while ((read = mFtpInputstream.read(bytesArray)) != -1) { mDownloadTemporaryPacketSize += read; if (mRepeatWrapper.isRepeatDownload()) { mRepeatWrapper.updateTempPacketSize(read); } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveDownloadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onDownloadProgress(report.getProgressPercent(), report); } } if (mDownloadTemporaryPacketSize == mDownloadPckSize.longValueExact()) { break; } } mFtpInputstream.close(); mTimeEnd = System.currentTimeMillis(); mReportInterval = false; final SpeedTestReport report = mSocketInterface.getLiveDownloadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onDownloadFinished(report); } } else { mReportInterval = false; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, "cant create stream " + "from uri " + uri + " with reply code : " + ftpclient.getReplyCode()); } if (!mRepeatWrapper.isRepeatDownload()) { closeExecutors(); } } catch (IOException e) { //e.printStackTrace(); mReportInterval = false; catchError(true, e.getMessage()); } finally { mErrorDispatched = false; mSpeedTestMode = SpeedTestMode.NONE; disconnectFtp(ftpclient); } } }); }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
private void connectButtonActionPerformed(ActionEvent evt) throws SocketException, IOException { String[] vehicles = controlledVehicles.split(","); jTextArea1.setText(""); jTextArea1.repaint();/*from w w w. ja v a2s.c o m*/ showText("Initializing Control Structures"); try { startLocalStructures(vehicles); } catch (Exception e) { GuiUtils.errorMessage(getConsole(), e); return; } auvs = positions.keySet().size(); showText("Initializing server connection"); FTPClient client = new FTPClient(); boolean PathNameCreated = false; try { client.connect("www.convcao.com", 21); client.login(jTextField1.getText(), new String(jPasswordField1.getPassword())); PathNameCreated = client.makeDirectory("/NEPTUS/" + sessionID); client.logout(); } catch (IOException e) { jLabel6.setText("Connection Error"); throw e; } showText("Sending session data"); InputData initialState = new InputData(); initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()); initialState.SessionID = sessionID; initialState.DemoMode = "1"; initialState.AUVs = "" + positions.keySet().size(); String fileName = sessionID + ".txt"; Gson gson = new Gson(); String json = gson.toJson(initialState); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.write(json); writer.close(); if (PathNameCreated) { jLabel6.setText("Connection Established"); jLabel1.setVisible(true); System.out.println("Uploading first file"); upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()), fileName); // send first file System.out.println("Uploading second file"); String mapFxStr = FileUtil.getResourceAsFileKeepName("convcao/com/caoAgent/mapPortoSparse.txt"); File mapFx = new File(mapFxStr); upload("www.convcao.com", "NEPTUS/" + sessionID, mapFx.getParent(), jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); // send sparse map System.out.println("Both files uploaded"); jButton1.setEnabled(true); jButton2.setEnabled(true); jTextPane1.setEditable(false); jTextField1.setEditable(false); jPasswordField1.setEditable(false); connectButton.setEnabled(false); renewButton.setEnabled(false); } else { jLabel6.setText(client.getReplyString()); jLabel1.setVisible(false); } myDeleteFile(fileName); showText("ConvCAO control has started"); }