List of usage examples for org.apache.commons.net.ftp FTPClient isConnected
public boolean isConnected()
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public boolean deleteResource(Object abstractConnection, String remoteResourcePath) throws Exception { long startTime = new Date().getTime(); FTPClient FTPconnection = (FTPClient) abstractConnection; if (!FTPconnection.isConnected()) { throw new Exception(ErrorMessages.err_FTC002); }//from ww w . j a v a2 s . c o m Boolean result = true; List<Object> FTPconnectionObject = _checkResourcePath(FTPconnection, remoteResourcePath, "delete-resource", checkIsDirectory(remoteResourcePath)); try { if ((Boolean) FTPconnectionObject.get(0)) { FTPconnection.removeDirectory(remoteResourcePath); log.info("The FTP sub-module deleted the directory in " + (new Date().getTime() - startTime) + " ms."); } else { FTPconnection.deleteFile(remoteResourcePath); log.info("The FTP sub-module deleted the file in " + (new Date().getTime() - startTime) + " ms."); } } catch (Exception ex) { log.error(ex.getMessage(), ex); result = false; } // if (!FTPconnection.completePendingCommand()) { // throw new Exception("err:FTC007: The current operation failed."); // } log.info("The FTP sub-module deleted the resource '" + remoteResourcePath + "' in " + (new Date().getTime() - startTime) + " ms."); return result; }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public static Boolean disconnect(Object abstractConnection) throws Exception { long startTime = new Date().getTime(); FTPClient FTPconnection = (FTPClient) abstractConnection; if (!FTPconnection.isConnected()) { throw new Exception(ErrorMessages.err_FTC002); }/*w w w.j a v a 2s . com*/ Boolean result = true; // try { // // close the Connection // long startTime = new Date().getTime(); // //FTPconnection.logout(); // log.info("Logout was done in " + (new Date().getTime() - startTime) + // " ms."); // } catch (IOException ioe) { // // log.error(ioe.getMessage(), ioe); // result = false; // } finally { // long startTime = new Date().getTime(); // try { // FTPconnection.disconnect(); // } catch (IOException ioe) { // log.error(ioe.getMessage(), ioe); // result = false; // } // log.info("Disconnection was done in " + (new Date().getTime() - // startTime) + " ms."); // } try { // FTPconnection.logout(); FTPconnection.disconnect(); log.info("The FTP sub-module disconnected in " + (new Date().getTime() - startTime) + " ms."); } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); result = false; } return result; }
From source file:s32a.FTPTest.java
public FTPTest() { FTPClient client = new FTPSClient(false); FileInputStream fis = null;/* w w w . ja va2 s .c om*/ FileOutputStream fos = null; try { System.out.println("connecting"); client.connect("athena.fhict.nl"); boolean login = client.login("i293443", "ifvr2edfh101"); System.out.println("login: " + login); client.enterLocalPassiveMode(); System.out.println("connected: " + client.isConnected() + ", available: " + client.isAvailable()); client.setFileType(FTP.ASCII_FILE_TYPE); // // Create an InputStream of the file to be uploaded // String filename = ".gitattributes"; File file = new File(filename); file.createNewFile(); System.out.println(file.length()); fis = new FileInputStream(file.getAbsolutePath()); client.makeDirectory("/Airhockey/Codebase/test"); client.makeDirectory("\\Airhockey\\Codebase\\testey"); // // Store file to server // String desiredName = "s32a\\Server\\.gitattributes"; System.out.println("storefile: " + file.getAbsolutePath() + " - " + client.storeFile("/Airhockey/" + desiredName, fis)); System.out.println("file stored"); // File output = new File("colors.json"); // fos = new FileOutputStream(output.getAbsolutePath()); // client.retrieveFile("/colors.json", fos); client.logout(); } catch (IOException e) { e.printStackTrace(); } catch (Exception ex) { System.out.println("exception caught: " + ex.getMessage()); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } client.disconnect(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } }
From source file:simplehttpdb.DBAccessWorker.java
/** * write a key-value pair to the given server * in case hexKey != null the value will be encrypted by use of the given key * in case no update is required the function won't write to the server * * FIXME: switching between encrypted and plain text is not supported yet * FIXME: using different keys for the same server is not supported yet * * @param webURL//from www.j av a2 s . c om * @param ftpServer * @param ftpUser * @param ftpPass * @param rootDir * @param hexKey * @param name * @param value * @return * @throws DecodingExeption * @throws EncodingExeption */ public int write(String webURL, String ftpServer, String ftpUser, String ftpPass, String rootDir, String hexKey, String name, String value) throws DecodingExeption, EncodingExeption { Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "\n\nwrite:\n" + "webURL: " + webURL + "\nftpServer: " + ftpServer + "\nftpUser: " + ftpUser + "\nrootDir: " + rootDir + "\nhexKey: " + hexKey + "\nname: " + name + "\nvalue: " + value + "\n"); int result = -1; String relPath = http.findLocationOfName(webURL, name); FTPClient ftpClient = null; try { Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "relpath=" + relPath); if (relPath == null) { //entry doesn't exist yet if (hexKey == null) { relPath = "free/"; } else { relPath = "crypt/"; } ftpClient = ftp.getFTPConnection(ftpServer, ftpUser, ftpPass); relPath = ftp.findFileToAddNewEntry(ftpClient, rootDir, relPath); } else { //we got the name of the file } Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "relpath(2)=" + relPath); //handling files Entries localList = http.getListFromUrl(webURL + relPath, hexKey); //if file is not existing we just continue with the empty list //check if value changed after all String oldValue = localList.getValue(name); if ((oldValue == null) || (!oldValue.equals(value))) { //ok, we have to write to ftp localList.put(new Entry(name, value)); if (ftpClient == null) { //for performace issues, ftp only got initialized in case //there was no entry found in the index already //so it might be required to initialize it here ftpClient = ftp.getFTPConnection(ftpServer, ftpUser, ftpPass); } if (ftp.storeFileAndUpdateIndex(webURL, rootDir, ftpClient, name, relPath, localList, hexKey)) { result = 0; } } else { //no update was necessary result = 0; } //Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "logout"); if (ftpClient != null) { ftpClient.logout(); } } catch (SocketException ex) { Logger.getLogger(DBAccessWorker.class.getName()).log(Level.SEVERE, null, ex); return -1; } catch (IOException ex) { Logger.getLogger(DBAccessWorker.class.getName()).log(Level.SEVERE, null, ex); return -1; } finally { if ((ftpClient != null) && (ftpClient.isConnected())) { try { //Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "disconnect"); ftpClient.disconnect(); } catch (IOException ex) { return -1; } } } return result; }
From source file:smilehouse.opensyncro.defaultcomponents.ftp.FTPDestination.java
public void take(String data, DestinationInfo info, MessageLogger logger) throws FailTransferException, AbortTransferException { FTPClient ftp = new FTPClient(); try {//from ww w . j a va2 s . c om // ----------------- // Try to connect... // ----------------- String host = this.data.getAttribute(HOST_ATTR); int port = -1; String portStr = this.data.getAttribute(PORT_ATTR); if (portStr != null && portStr.length() > 0) { try { port = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } } int reply; try { if (port != -1) { ftp.connect(host, port); } else { ftp.connect(host); } } catch (SocketException e) { logger.logMessage("SocketException while connecting to host " + host + ", aborting", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } catch (IOException e) { logger.logMessage("IOException while connecting to host " + host + ", aborting", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftp.disconnect(); } catch (IOException e) { /** * ftp.disconnect() is called only as additional clean-up here, so we choose to * ignore possible exceptions */ } logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // ----------- // Then log in // ----------- try { if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) { logger.logMessage("Could not log in, check your username and password settings.", this, MessageLogger.ERROR); ftp.logout(); PipeComponentUtils.failTransfer(); } } catch (IOException e) { logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // Use passive mode ftp.enterLocalPassiveMode(); // ----------------- // ASCII or binary ? // ----------------- boolean fileTypeSetOk = false; try { switch (getFileType()) { case FILE_TYPE_ASCII: fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE); break; case FILE_TYPE_BINARY: fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE); } if (!fileTypeSetOk) { logger.logMessage("Could not set file type: " + ftp.getReplyString(), this, MessageLogger.WARNING); } } catch (IOException e) { logger.logMessage("IOException while setting file transfer type parameter", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // ------------- // Send the data // ------------- String fileName = getFileName(); logger.logMessage("Storing file: " + fileName, this, MessageLogger.DEBUG); String charSet = this.data.getAttribute(CHARSET_ATTR); if (charSet == null || charSet.length() == 0) charSet = DEFAULT_CHARSET; InputStream dataStream = null; try { dataStream = new ByteArrayInputStream(data.getBytes(charSet)); } catch (UnsupportedEncodingException e1) { logger.logMessage(charSet + " charset not supported", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } try { if (!ftp.storeFile(fileName, dataStream)) { logger.logMessage("Could not store file '" + fileName + "': " + ftp.getReplyString(), this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } } catch (IOException e) { logger.logMessage("IOException while uploading the file to FTP server", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } }
From source file:smilehouse.opensyncro.defaultcomponents.ftp.FTPSource.java
public String[] give(SourceInfo info, MessageLogger logger) throws FailTransferException, AbortTransferException { // This component does not support iteration, so we output all our data // once (and only once) if (this.allDataOutput == true) return null; else/*from ww w. j av a 2 s . co m*/ this.allDataOutput = true; String[] dataArray = new String[1]; FTPClient ftp = new FTPClient(); try { // ----------------- // Try to connect... // ----------------- String host = this.data.getAttribute(HOST_ATTR); int port = -1; String portStr = this.data.getAttribute(PORT_ATTR); if (portStr != null && portStr.length() > 0) { try { port = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } } int reply; try { if (port != -1) { ftp.connect(host, port); } else { ftp.connect(host); } } catch (SocketException e) { logger.logMessage("SocketException while connecting to host " + host + ", aborting", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } catch (IOException e) { logger.logMessage("IOException while connecting to host " + host + ", aborting", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftp.disconnect(); } catch (IOException e) { /** * ftp.disconnect() is called only as additional clean-up here, so we choose to * ignore possible exceptions */ } logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // ----------- // Then log in // ----------- try { if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) { logger.logMessage("Could not log in, check your username and password settings.", this, MessageLogger.ERROR); ftp.logout(); PipeComponentUtils.failTransfer(); } } catch (IOException e) { logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // Use passive mode ftp.enterLocalPassiveMode(); // ----------------- // ASCII or binary ? // ----------------- boolean fileTypeSetOk = false; try { switch (getFileType()) { case FILE_TYPE_ASCII: fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE); break; case FILE_TYPE_BINARY: fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE); } if (!fileTypeSetOk) { logger.logMessage("Could not set file type: " + ftp.getReplyString(), this, MessageLogger.WARNING); } } catch (IOException e) { logger.logMessage("IOException while setting file transfer type parameter", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } // ----------------- // Retrieve the data // ----------------- String fileName = getFileName(logger); logger.logMessage("Retrieving file: " + fileName, this, MessageLogger.DEBUG); OutputStream dataStream = new ByteArrayOutputStream(); try { if (!ftp.retrieveFile(fileName, dataStream)) { logger.logMessage("Could not retrieve file '" + fileName + "': " + ftp.getReplyString(), this, MessageLogger.WARNING); PipeComponentUtils.abortTransfer(); } String charSet = this.data.getAttribute(CHARSET_ATTR); if (charSet == null || charSet.length() == 0) charSet = DEFAULT_CHARSET; dataArray[0] = ((ByteArrayOutputStream) dataStream).toString(charSet); } catch (IOException e) { logger.logMessage("IOException while downloading file from FTP server", this, MessageLogger.ERROR); PipeComponentUtils.failTransfer(); } } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } return dataArray; }
From source file:srv.update.java
public void getVersao(View view) { String server = "ftp.atmatech.com.br"; int port = 21; String user = "atmatech"; String pass = "ftpp2015"; FTPClient ftpClient = new FTPClient(); try {// w ww. j a v a2 s.c o m ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/"); // APPROACH #1: using retrieveFile(String, OutputStream) String[] arq = ftpClient.listNames(); for (String f : arq) { if (!f.equals(".")) { if (!f.equals("..")) { if (f.contains(".")) { view.jLprogresso.setText(f); String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f; String destino = ".\\" + f; File downloadFile1 = new File(destino); OutputStream outputStream1 = new BufferedOutputStream( new FileOutputStream(downloadFile1)); boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); if (!success) { JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso"); System.exit(0); } } else { ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/" + f); String[] arq2 = ftpClient.listNames(); for (String f2 : arq2) { if (!f2.equals(".")) { if (!f2.equals("..")) { view.jLprogresso.setText(f2); File diretorio = new File(".\\" + f); if (!diretorio.exists()) { diretorio.mkdirs(); //mkdir() cria somente um diretrio, mkdirs() cria diretrios e subdiretrios. } String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f + "/" + f2; String destino = ".\\" + f + "\\" + f2; File downloadFile1 = new File(destino); OutputStream outputStream1 = new BufferedOutputStream( new FileOutputStream(downloadFile1)); boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); if (!success) { JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso"); System.exit(0); } } } } } } } } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro \n" + ex); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro \n" + ex); } } }
From source file:test.java.FTPServerTest.java
@Test public void testConnectFTPServer() throws IOException { FTPClient ftpClient = ConnectionFTP.connectFTP(SERVER1_USER, SERVER1_PASSWORD, SERVER1_ADDRESS); Assert.assertEquals(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()), true); ftpClient = ConnectionFTP.diconnectFTP(ftpClient, SERVER1_ADDRESS); Assert.assertEquals(ftpClient.isConnected(), false); }
From source file:test.java.FTPServerTest.java
@Test public void testExistFileXMLFTPServer() throws IOException { FTPClient ftpClient = ConnectionFTP.connectFTP(SERVER1_USER, SERVER1_PASSWORD, SERVER1_ADDRESS); Assert.assertEquals(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()), true); List<String> listXMLFiles = FTPServerController.findFilesXMLFTPServer(ftpClient); Assert.assertEquals(listXMLFiles.isEmpty(), false); ftpClient = ConnectionFTP.diconnectFTP(ftpClient, SERVER1_ADDRESS); Assert.assertEquals(ftpClient.isConnected(), false); }
From source file:test.java.FTPServerTest.java
@Test public void testSaveFileXMLFTPServerInDB() throws IOException { Server serverSaved = CommonsTest.saveServerTest(SERVER1_USER, SERVER1_PASSWORD, SERVER1_ADDRESS); FTPClient ftpClient = ConnectionFTP.connectFTP(serverSaved.getUser(), serverSaved.getPassword(), serverSaved.getAddress());//from w ww. j a v a 2s. c o m Assert.assertEquals(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()), true); List<String> listNameFilesXML = FTPServerController.findFilesXMLFTPServer(ftpClient); for (String itemNameFileXML : listNameFilesXML) { ftpClient = ConnectionFTP.diconnectFTP(ftpClient, serverSaved.getAddress()); ftpClient = ConnectionFTP.connectFTP(serverSaved.getUser(), serverSaved.getPassword(), serverSaved.getAddress()); String contentFileXML = FTPServerController.getFileFTPServer(ftpClient, itemNameFileXML); XMLFile xmlFileSavedRecent = CommonsTest.saveXMLFileTest(itemNameFileXML, contentFileXML, serverSaved.getAddress()); XMLFileDAO xmlFileDAO = new XMLFileDAO(); xmlFileDAO.removeXMLFile(xmlFileSavedRecent); Assert.assertEquals(xmlFileDAO.findXMLFileById(xmlFileSavedRecent.getId()), null); } ServerDAO serverDAO = new ServerDAO(); serverDAO.removeServer(serverSaved); Assert.assertEquals(serverDAO.findServerByAddress(serverSaved.getAddress()), null); ftpClient = ConnectionFTP.diconnectFTP(ftpClient, SERVER1_ADDRESS); Assert.assertEquals(ftpClient.isConnected(), false); }