List of usage examples for org.apache.commons.net.ftp FTPClient isConnected
public boolean isConnected()
From source file:org.wso2.carbon.connector.FileFtpOverProxyConnector.java
/** * Send file FTP over Proxy./*from w ww . java 2 s .com*/ * * @param messageContext The message context that is generated for processing the file. * @return true, if the FTP client tunnels over an HTTP proxy connection or stores a file on the server. * */ public boolean ftpOverHttpProxy(MessageContext messageContext) { String proxyHost = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_HOST)); String proxyPort = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PORT)); String proxyUsername = StringUtils.trim( (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_USERNAME)); String proxyPassword = StringUtils.trim( (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.PROXY_PASSWORD)); String ftpHost = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_SERVER)); String ftpPort = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PORT)); String ftpUsername = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_USERNAME)); String ftpPassword = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FTP_PASSWORD)); String keepAliveTimeout = StringUtils.trim( (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.KEEP_ALIVE_TIMEOUT)); String controlKeepAliveReplyTimeout = StringUtils.trim((String) ConnectorUtils .lookupTemplateParamater(messageContext, FileConstants.CONTROL_KEEP_ALIVE_REPLY_TIMEOUT)); String targetPath = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_PATH)); String targetFile = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.TARGET_FILE)); String activeMode = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ACTIVE_MODE)); String fileType = StringUtils .trim((String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_TYPE)); boolean activeModeParameter = false; if (StringUtils.isEmpty(keepAliveTimeout)) { keepAliveTimeout = FileConstants.DEFAULT_KEEP_ALIVE_TIMEOUT; } if (StringUtils.isEmpty(controlKeepAliveReplyTimeout)) { controlKeepAliveReplyTimeout = FileConstants.DEFAULT_CONTROL_KEEP_ALIVE_REPLY_TIMEOUT; } if (StringUtils.isNotEmpty(activeMode)) { activeModeParameter = Boolean.parseBoolean(activeMode); } InputStream inputStream = null; FTPClient ftp = new FTPClient(); if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort) && StringUtils.isNotEmpty(proxyUsername) && StringUtils.isNotEmpty(proxyPassword)) { ftp = new FTPHTTPClient(proxyHost, Integer.parseInt(proxyPort), proxyUsername, proxyPassword); } //Set the time to wait between sending control connection keep alive messages when processing file upload or // download (Zero (or less) disables). ftp.setControlKeepAliveTimeout(Long.parseLong(keepAliveTimeout)); //Set how long to wait for control keep-alive message replies.(defaults to 1000 milliseconds.) ftp.setControlKeepAliveReplyTimeout(Integer.parseInt(controlKeepAliveReplyTimeout)); try { int reply; int IntFtpPort = Integer.parseInt(ftpPort); if (IntFtpPort > 0) { ftp.connect(ftpHost, IntFtpPort); } else { ftp.connect(ftpHost); } if (log.isDebugEnabled()) { log.debug(" Connected to " + ftpHost + " on " + (IntFtpPort > 0 ? ftpPort : ftp.getDefaultPort())); } // After connection attempt, should check the reply code to verify success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("FTP ftpServer refused connection."); } if (!ftp.login(ftpUsername, ftpPassword)) { ftp.logout(); throw new SynapseException("Error while login ftp server."); } setFileType(fileType, ftp); // Use passive mode as default because most of us are behind firewalls these days. if (activeModeParameter) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } inputStream = new ByteArrayInputStream( messageContext.getEnvelope().getBody().getFirstElement().toString().getBytes()); if (StringUtils.isNotEmpty(targetPath)) { ftp.changeWorkingDirectory(targetPath); ftp.storeFile(targetFile, inputStream); if (log.isDebugEnabled()) { log.debug("Successfully FTP server transferred the File"); } } // check that control connection is working if (log.isDebugEnabled()) { log.debug("The code received from the server." + ftp.noop()); } } catch (IOException e) { throw new SynapseException("Could not connect to FTP Server", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); ftp.logout(); } catch (IOException f) { log.error("Error while disconnecting/logging out ftp server"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException f) { log.error("Error while closing inputStream"); } } } return true; }
From source file:org.wso2.iot.agent.services.FileDownloadService.java
/** * This method downloads the file using sftp client. * * @param operation - operation object. * @param host - host address. * @param ftpUserName - ftp user name. * @param ftpPassword - ftp password. * @param savingLocation - location in the device to save the file. * @param fileName - name of the file to download. * @param serverPort - ftp server port. * @param fileDirectory - the directory of the file in FTP server. * @throws AndroidAgentException - Android agent exception. *//*from ww w.ja v a 2 s . c om*/ private void downloadFileUsingFTPClient(Operation operation, String host, String ftpUserName, String ftpPassword, String savingLocation, String fileName, int serverPort, String fileDirectory) throws AndroidAgentException { FTPClient ftpClient = new FTPClient(); FileOutputStream fileOutputStream = null; OutputStream outputStream = null; String response; try { ftpClient.connect(host, serverPort); if (ftpClient.login(ftpUserName, ftpPassword)) { ftpClient.enterLocalPassiveMode(); fileOutputStream = new FileOutputStream(savingLocation + File.separator + fileName); outputStream = new BufferedOutputStream(fileOutputStream); ftpClient.changeWorkingDirectory(fileDirectory); if (ftpClient.retrieveFile(fileName, outputStream)) { response = "File uploaded to the device successfully ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_completed)); } else { response = "File uploaded to the device not completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_error)); } operation.setOperationResponse(response); } else { downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName, serverPort, fileDirectory); } } catch (FTPConnectionClosedException | ConnectException e) { downloadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, savingLocation, fileName, serverPort, fileDirectory); } catch (IOException e) { handleOperationError(operation, fileTransferExceptionCause(e, fileName), e); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ignored) { } cleanupStreams(null, outputStream, null, fileOutputStream, null, null, null, null); } }
From source file:org.wso2.iot.agent.services.FileUploadService.java
/** * File upload operation using an FTP client. * * @param operation - operation object. * @param host - host name.//w w w .j a v a2 s .c om * @param ftpUserName - ftp user name. * @param ftpPassword - ftp password. * @param uploadDirectory - ftp directory to upload file. * @param fileLocation - local file location. * @param serverPort - ftp port to connect. * @throws AndroidAgentException - AndroidAgent exception. */ private void uploadFileUsingFTPClient(Operation operation, String host, String ftpUserName, String ftpPassword, String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException { FTPClient ftpClient = new FTPClient(); String fileName = null; InputStream inputStream = null; String response; try { File file = new File(fileLocation); fileName = file.getName(); ftpClient.connect(host, serverPort); ftpClient.enterLocalPassiveMode(); ftpClient.login(ftpUserName, ftpPassword); inputStream = new FileInputStream(file); ftpClient.changeWorkingDirectory(uploadDirectory); if (ftpClient.storeFile(file.getName(), inputStream)) { response = "File uploaded from the device completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_completed)); } else { response = "File uploaded from the device not completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_error)); } operation.setOperationResponse(response); } catch (FTPConnectionClosedException e) { uploadFileUsingFTPSClient(operation, host, ftpUserName, ftpPassword, uploadDirectory, fileLocation, serverPort); } catch (IOException e) { handleOperationError(operation, fileTransferExceptionCause(e, fileName), e, resources); } finally { if (ftpClient.isConnected()) { try { ftpClient.logout(); } catch (IOException ignored) { } } if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ignored) { } } cleanupStreams(inputStream, null, null, null, null, null, null, null); } }
From source file:password.pwm.svc.telemetry.FtpTelemetrySender.java
private void disconnectFtpClient(final FTPClient ftpClient) { if (ftpClient.isConnected()) { try {/*from www . ja va 2 s . c om*/ ftpClient.disconnect(); LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "disconnected"); } catch (IOException e) { LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "error while disconnecting ftp client: " + e.getMessage()); } } }
From source file:Proiect.uploadFTP.java
public void actionFTP() { adressf.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent e) { InetAddress thisIp;//from w w w . ja v a 2 s . co m try { thisIp = InetAddress.getLocalHost(); titleFTP.setText("Connection: " + thisIp.getHostAddress() + " -> " + adressf.getText()); } catch (UnknownHostException e1) { e1.printStackTrace(); } } }); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveState(); uploadFTP.dispose(); tree.dispose(); } }); connect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FTPClient client = new FTPClient(); FileInputStream fis = null; String pass = String.valueOf(passf.getPassword()); try { if (filename == null) { status.setText("File does not exist!"); } else { // Server address client.connect(adressf.getText()); // Login credentials client.login(userf.getText(), pass); if (client.isConnected()) { status.setText("Succesfull transfer!"); // File type client.setFileType(FTP.BINARY_FILE_TYPE); // File location File file = new File(filepath); fis = new FileInputStream(file); // Change the folder on the server client.changeWorkingDirectory(folderf.getText()); // Save the file on the server client.storeFile(filename, fis); } else { status.setText("Transfer failed!"); } } client.logout(); } catch (IOException e1) { Encrypter.printException(e1); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e1) { Encrypter.printException(e1); } } } }); browsef.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int retval = chooserf.showOpenDialog(chooserf); if (retval == JFileChooser.APPROVE_OPTION) { status.setText(""); filename = chooserf.getSelectedFile().getName().toString(); filepath = chooserf.getSelectedFile().getPath(); filenf.setText(chooserf.getSelectedFile().getName().toString()); } } }); adv.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tree.setSize(220, uploadFTP.getHeight()); tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY()); tree.setResizable(false); tree.setIconImage(Toolkit.getDefaultToolkit() .getImage(getClass().getClassLoader().getResource("assets/ico.png"))); tree.setUndecorated(true); tree.getRootPane().setBorder(BorderFactory.createLineBorder(Encrypter.color_black, 2)); tree.setVisible(true); tree.setLayout(new BorderLayout()); JLabel labeltree = new JLabel("Server documents"); labeltree.setOpaque(true); labeltree.setBackground(Encrypter.color_light); labeltree.setBorder(BorderFactory.createMatteBorder(8, 10, 10, 0, Encrypter.color_light)); labeltree.setForeground(Encrypter.color_blue); labeltree.setFont(Encrypter.font16); JButton refresh = new JButton(""); ImageIcon refresh_icon = getImageIcon("assets/icons/refresh.png"); refresh.setIcon(refresh_icon); refresh.setBackground(Encrypter.color_light); refresh.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); refresh.setForeground(Encrypter.color_black); refresh.setFont(Encrypter.font16); refresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); final FTPClient client = new FTPClient(); DefaultMutableTreeNode top = new DefaultMutableTreeNode(adressf.getText()); DefaultMutableTreeNode files = null; DefaultMutableTreeNode leaf = null; final JTree tree_view = new JTree(top); tree_view.setForeground(Encrypter.color_black); tree_view.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); tree_view.putClientProperty("JTree.lineStyle", "None"); tree_view.setBackground(Encrypter.color_light); JScrollPane scrolltree = new JScrollPane(tree_view); scrolltree.setBackground(Encrypter.color_light); scrolltree.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0)); UIManager.put("Tree.textBackground", Encrypter.color_light); UIManager.put("Tree.selectionBackground", Encrypter.color_blue); UIManager.put("Tree.selectionBorderColor", Encrypter.color_blue); tree_view.updateUI(); final String pass = String.valueOf(passf.getPassword()); try { client.connect(adressf.getText()); client.login(userf.getText(), pass); client.enterLocalPassiveMode(); if (client.isConnected()) { try { FTPFile[] ftpFiles = client.listFiles(); for (FTPFile ftpFile : ftpFiles) { files = new DefaultMutableTreeNode(ftpFile.getName()); top.add(files); if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) { FTPFile[] ftpFiles1 = client.listFiles(ftpFile.getName()); for (FTPFile ftpFile1 : ftpFiles1) { leaf = new DefaultMutableTreeNode(ftpFile1.getName()); files.add(leaf); } } } } catch (IOException e1) { Encrypter.printException(e1); } client.disconnect(); } else { status.setText("Failed connection!"); } } catch (IOException e1) { Encrypter.printException(e1); } finally { try { client.disconnect(); } catch (IOException e1) { Encrypter.printException(e1); } } tree.add(labeltree, BorderLayout.NORTH); tree.add(scrolltree, BorderLayout.CENTER); tree.add(refresh, BorderLayout.SOUTH); uploadFTP.addComponentListener(new ComponentListener() { public void componentMoved(ComponentEvent e) { tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY()); } public void componentShown(ComponentEvent e) { } public void componentResized(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); uploadFTP.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) { tree.toFront(); } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { } public void windowClosed(WindowEvent e) { } }); refresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tree.dispose(); tree.setVisible(true); } }); } }); }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public <X> X connect(URI remoteHostUri, String username, String password, String remoteHost, int remotePort, String options) throws Exception { long startTime = new Date().getTime(); X abstractConnection = null;//from ww w .j av a2 s .c o m FTPClient ftpConnection = new FTPClient(); try { remotePort = (remotePort == -1) ? (int) 21 : remotePort; ftpConnection.setDefaultTimeout(60 * 1000); ftpConnection.setRemoteVerificationEnabled(false); // FTPconnection.setSoTimeout( 60 * 1000 ); // FTPconnection.setDataTimeout( 60 * 1000 ); ftpConnection.connect(remoteHost, remotePort); ftpConnection.login(username, password); ftpConnection.enterLocalPassiveMode(); ftpConnection.setFileType(FTPClient.BINARY_FILE_TYPE); // FTPconnection.setControlKeepAliveTimeout(300); // Check reply code for success int reply = ftpConnection.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpConnection.disconnect(); throw new Exception(ErrorMessages.err_FTC005); } else { abstractConnection = (X) ftpConnection; } } catch (IOException se) { if (ftpConnection.isConnected()) { try { ftpConnection.disconnect(); } catch (IOException ioe) { throw new Exception(ErrorMessages.err_FTC005); } } } log.info("The FTP sub-module connected to '" + remoteHostUri + "' in " + (new Date().getTime() - startTime) + " ms."); return abstractConnection; }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public StreamResult listResources(Object abstractConnection, String remoteResourcePath) throws Exception { long startTime = new Date().getTime(); boolean isDirectory = checkIsDirectory(remoteResourcePath); if (!isDirectory) { throw new Exception(ErrorMessages.err_FTC008); }// w w w . ja va2 s. c o m FTPClient connection = (FTPClient) abstractConnection; if (!connection.isConnected()) { throw new Exception(ErrorMessages.err_FTC002); } List<Object> connectionObject = _checkResourcePath(connection, remoteResourcePath, "list-resources", isDirectory); System.out.println("resources: " + connectionObject.size()); FTPFile[] resources = (FTPFile[]) connectionObject.get(1); StringWriter writer = new StringWriter(); XMLStreamWriter xmlWriter = null; try { xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); xmlWriter.setPrefix(modulePrefix, moduleNsUri); xmlWriter.writeStartDocument(); xmlWriter.writeStartElement(modulePrefix + ":resources-list"); xmlWriter.writeNamespace(modulePrefix, moduleNsUri); xmlWriter.writeAttribute("absolute-path", remoteResourcePath); for (FTPFile resource : resources) { _generateResourceElement(xmlWriter, resource, null, remoteResourcePath + resource.getName()); } xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (Exception ex) { throw new Exception(ex.getMessage()); } // FTPconnection.completePendingCommand(); StreamResult resultAsStreamResult = new StreamResult(writer); log.info("The FTP sub-module retrieved the list of resources in " + (new Date().getTime() - startTime) + " ms."); return resultAsStreamResult; }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public StreamResult getResourceMetadata(Object abstractConnection, String remoteResourcePath) 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 2 s.com*/ List<Object> FTPconnectionObject = _checkResourcePath(FTPconnection, remoteResourcePath, "get-resource-metadata", checkIsDirectory(remoteResourcePath)); FTPFile[] resources = (FTPFile[]) FTPconnectionObject.get(1); StringWriter writer = new StringWriter(); XMLStreamWriter xmlWriter = null; try { xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); xmlWriter.setPrefix(modulePrefix, moduleNsUri); xmlWriter.writeStartDocument(); for (FTPFile resource : resources) { _generateResourceElement(xmlWriter, resource, null, remoteResourcePath); } xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (Exception ex) { throw new Exception(ex.getMessage()); } // FTPconnection.completePendingCommand(); StreamResult resultAsStreamResult = new StreamResult(writer); log.info("The FTP sub-module retrieved the metadata for resource '" + remoteResourcePath + "' in " + (new Date().getTime() - startTime) + " ms."); return resultAsStreamResult; }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public InputStream retrieveResource(Object abstractConnection, String remoteResourcePath) throws Exception { long startTime = new Date().getTime(); FTPClient connection = (FTPClient) abstractConnection; if (!connection.isConnected()) { throw new Exception(ErrorMessages.err_FTC002); }//from ww w . j av a 2s . c o m _checkResourcePath(connection, remoteResourcePath, "retrieve-resource", checkIsDirectory(remoteResourcePath)); InputStream is = connection.retrieveFileStream(remoteResourcePath); log.info("The FTP sub-module retrieved the resource '" + remoteResourcePath + "' in " + (new Date().getTime() - startTime) + " ms."); return is; }
From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java
public boolean storeResource(Object abstractConnection, String remoteDirectoryPath, String resourceName, InputStream resourceInputStream) throws Exception { long startTime = new Date().getTime(); FTPClient connection = (FTPClient) abstractConnection; if (!connection.isConnected()) { throw new Exception(ErrorMessages.err_FTC002); }//from ww w . jav a2 s . c o m Boolean result = true; try { if (resourceName.length() == 0) { resourceName = remoteDirectoryPath.substring(remoteDirectoryPath.lastIndexOf("/") + 1); remoteDirectoryPath = remoteDirectoryPath.substring(0, remoteDirectoryPath.lastIndexOf("/")); _checkResourcePath(connection, remoteDirectoryPath, "store-resource", true); result = connection.makeDirectory(resourceName); } else { _checkResourcePath(connection, remoteDirectoryPath, "store-resource", false); result = connection.storeFile(resourceName, resourceInputStream); resourceInputStream.close(); } } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); // TODO: add throw exception here for cases when server doesn't // allow storage of file - a use case is when vsftpd was configured // with mandatory SSL encryption result = false; } // if(!FTPconnection.completePendingCommand()) { // throw new Exception( // "err:FTC007: The current operation failed."); // } log.info("The FTP sub-module stored the resource '" + resourceName + "' at '" + remoteDirectoryPath + "' in " + (new Date().getTime() - startTime) + " ms."); return result; }