List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:database.DataLoader.java
private void initFtpClient() throws Exception { ftpClient = new FTPClient(); String server = "92.53.114.87"; String login = "dekkar_ivan"; String password = "qwerty123"; ftpClient.connect(server);/*w w w. ja va2 s .c o m*/ boolean ok = ftpClient.login(login, password); if (!ok) { ftpClient.logout(); throw new Exception(" ? ?? FTP"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new Exception(" ? ?? FTP. ReplyCode"); } }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downIBSA() { String fl = ""; String fp = ""; String fs = ""; try {//from w ww . j av 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(); } } }
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;//from w ww . j a va2 s . 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:fr.bmartel.speedtest.SpeedTestTask.java
/** * start FTP download with specific port, user, password. * * @param hostname ftp host/*ww w .ja v a 2 s . com*/ * @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: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;//ww w.j a v a 2s . c o m String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host); // 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.maxl.java.aips2sqlite.AllDown.java
public void downZurRose() { String fl = ""; String fp = ""; String fs = ""; try {//from w w w .j a v a2 s.c om FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(access, "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("P_ywesee")) { 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.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("- Connected to server " + fs + "..."); String[] working_dir = { "ywesee out", "../ywesee in" }; for (int i = 0; i < working_dir.length; ++i) { // Set working directory ftp_client.changeWorkingDirectory(working_dir[i]); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } // Get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { // ... then download all csv files for (FTPFile f : ftpFiles) { String remote_file = f.getName(); if (remote_file.endsWith("csv")) { String local_file = remote_file; if (remote_file.startsWith("Artikelstamm")) local_file = Constants.CSV_FILE_DISPO_ZR; OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("success."); else System.out.println("error."); os.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:fr.bmartel.speedtest.SpeedTestTask.java
/** * Start FTP upload./*from w ww .j a v a2s . c om*/ * * @param hostname ftp host * @param port ftp port * @param uri upload uri * @param fileSizeOctet file size in octet * @param user username * @param password password */ public void startFtpUpload(final String hostname, final int port, final String uri, final int fileSizeOctet, final String user, final String password) { mSpeedTestMode = SpeedTestMode.UPLOAD; mUploadFileSize = new BigDecimal(fileSizeOctet); mForceCloseSocket = false; mErrorDispatched = false; if (mWriteExecutorService == null || mWriteExecutorService.isShutdown()) { mWriteExecutorService = Executors.newSingleThreadExecutor(); } mWriteExecutorService.execute(new Runnable() { @Override public void run() { final FTPClient ftpClient = new FTPClient(); final RandomGen randomGen = new RandomGen(); RandomAccessFile uploadFile = null; try { ftpClient.connect(hostname, port); ftpClient.login(user, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); byte[] fileContent = new byte[] {}; if (mSocketInterface.getUploadStorageType() == UploadStorageType.RAM_STORAGE) { /* generate a file with size of fileSizeOctet octet */ fileContent = randomGen.generateRandomArray(fileSizeOctet); } else { uploadFile = randomGen.generateRandomFile(fileSizeOctet); uploadFile.seek(0); } mFtpOutputstream = ftpClient.storeFileStream(uri); if (mFtpOutputstream != null) { mUploadTempFileSize = 0; final int uploadChunkSize = mSocketInterface.getUploadChunkSize(); final int step = fileSizeOctet / uploadChunkSize; final int remain = fileSizeOctet % uploadChunkSize; mTimeStart = System.currentTimeMillis(); mTimeEnd = 0; if (mRepeatWrapper.isFirstUpload()) { mRepeatWrapper.setFirstUploadRepeat(false); mRepeatWrapper.setStartDate(mTimeStart); } if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updatePacketSize(mUploadFileSize); } if (mForceCloseSocket) { SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, ""); } else { for (int i = 0; i < step; i++) { final byte[] chunk = SpeedTestUtils.readUploadData( mSocketInterface.getUploadStorageType(), fileContent, uploadFile, mUploadTempFileSize, uploadChunkSize); mFtpOutputstream.write(chunk, 0, uploadChunkSize); mUploadTempFileSize += uploadChunkSize; if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updateTempPacketSize(uploadChunkSize); } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int j = 0; j < mListenerList.size(); j++) { mListenerList.get(j).onUploadProgress(report.getProgressPercent(), report); } } } if (remain != 0) { final byte[] chunk = SpeedTestUtils.readUploadData( mSocketInterface.getUploadStorageType(), fileContent, uploadFile, mUploadTempFileSize, remain); mFtpOutputstream.write(chunk, 0, remain); mUploadTempFileSize += remain; if (mRepeatWrapper.isRepeatUpload()) { mRepeatWrapper.updateTempPacketSize(remain); } } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int j = 0; j < mListenerList.size(); j++) { mListenerList.get(j).onUploadProgress(SpeedTestConst.PERCENT_MAX.floatValue(), report); } } mTimeEnd = System.currentTimeMillis(); } mFtpOutputstream.close(); mReportInterval = false; final SpeedTestReport report = mSocketInterface.getLiveUploadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onUploadFinished(report); } if (!mRepeatWrapper.isRepeatUpload()) { closeExecutors(); } } else { mReportInterval = false; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "cant create stream " + "from uri " + uri + " with reply code : " + ftpClient.getReplyCode()); } } catch (SocketTimeoutException e) { //e.printStackTrace(); mReportInterval = false; mErrorDispatched = true; if (!mForceCloseSocket) { SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, false, SpeedTestConst.SOCKET_WRITE_ERROR); } else { SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage()); } closeSocket(); closeExecutors(); } catch (IOException e) { //e.printStackTrace(); mReportInterval = false; mErrorDispatched = true; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage()); closeExecutors(); } finally { mErrorDispatched = false; mSpeedTestMode = SpeedTestMode.NONE; disconnectFtp(ftpClient); if (uploadFile != null) { try { uploadFile.close(); randomGen.deleteFile(); } catch (IOException e) { //e.printStackTrace(); } } } } }); }
From source file:com.sos.VirtualFileSystem.FTP.SOSVfsFtp.java
@Override protected final FTPClient Client() { if (objFTPClient == null) { objFTPClient = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(); // conf.setServerLanguageCode("fr"); // objFTPClient.configure(conf); /**/* w w w . j a v a 2 s.co m*/ * This listener is to write all commands and response from commands to system.out * */ objProtocolCommandListener = new SOSFtpClientLogger(HostID("")); if (objConnection2Options != null) { if (objConnection2Options.ProtocolCommandListener.isTrue()) { objFTPClient.addProtocolCommandListener(objProtocolCommandListener); logger.debug("ProtocolcommandListener added and activated"); } } // TODO implement as an additional Option-setting String strAddFTPProtocol = System.getenv("AddFTPProtocol"); if (strAddFTPProtocol != null && strAddFTPProtocol.equalsIgnoreCase("true")) { objFTPClient.addProtocolCommandListener(objProtocolCommandListener); } } return objFTPClient; }
From source file:br.com.jinsync.view.FrmJInSync.java
public void connectionFtp(String nomePds, String tipo) { // setNomePds(nomePds); ftp = new FTPClient(); conexao = true;//from www. java 2 s . c om filtro = ""; if (ipFtp.equals("")) { JOptionPane.showMessageDialog(null, Language.msgParameterNotFound, Language.msgErr, JOptionPane.ERROR_MESSAGE); return; } if (user.equals("")) { FrmUser frmPar = new FrmUser(); frmPar.setLocationRelativeTo(null); frmPar.setVisible(true); loadParameters(); } openConnection openConnect = new openConnection(); openConnect.setType(tipo); openConnect.start(); }
From source file:com.maxl.java.aips2sqlite.AllDown.java
public void downDesitin() { String fl = ""; String fp = ""; String fs = ""; try {/*from w w w .jav a2 s . com*/ FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv"); BufferedReader br = new BufferedReader(new InputStreamReader(access, "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("ftp_amiko")) { 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.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("- Connected to server " + fs + "..."); // Set working directory String working_dir = "ywesee_in"; ftp_client.changeWorkingDirectory(working_dir); int reply = ftp_client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp_client.disconnect(); System.err.println("FTP server refused connection."); return; } // Get list of filenames FTPFile[] ftpFiles = ftp_client.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { // ... then download all csv files for (FTPFile f : ftpFiles) { String remote_file = f.getName(); if (remote_file.endsWith("csv")) { String local_file = remote_file; if (remote_file.startsWith("Kunden")) local_file = Constants.FILE_CUST_DESITIN; if (remote_file.startsWith("Artikel")) local_file = Constants.FILE_ARTICLES_DESITIN; OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file); System.out.print("- Downloading " + remote_file + " from server " + fs + "... "); boolean done = ftp_client.retrieveFile(remote_file, os); if (done) System.out.println("success."); else System.out.println("error."); os.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(); } } }