List of usage examples for org.apache.commons.net.ftp FTPSClient getReplyCode
public int getReplyCode()
From source file:examples.ftp.FTPSExample.java
public static final void main(String[] args) throws NoSuchAlgorithmException { int base = 0; boolean storeFile = false, binaryTransfer = false, error = false; String server, username, password, remote, local; String protocol = "SSL"; // SSL/TLS FTPSClient ftps; for (base = 0; base < args.length; base++) { if (args[base].startsWith("-s")) storeFile = true;/* ww w . j ava2s. c om*/ else if (args[base].startsWith("-b")) binaryTransfer = true; else break; } if ((args.length - base) != 5) { System.err.println(USAGE); System.exit(1); } server = args[base++]; username = args[base++]; password = args[base++]; remote = args[base++]; local = args[base]; ftps = new FTPSClient(protocol); ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); try { int reply; ftps.connect(server); System.out.println("Connected to " + server + "."); // After connection attempt, you should check the reply code to verify // success. reply = ftps.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftps.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftps.isConnected()) { try { ftps.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { ftps.setBufferSize(1000); if (!ftps.login(username, password)) { ftps.logout(); error = true; break __main; } System.out.println("Remote system is " + ftps.getSystemName()); if (binaryTransfer) ftps.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are // behind firewalls these days. ftps.enterLocalPassiveMode(); if (storeFile) { InputStream input; input = new FileInputStream(local); ftps.storeFile(remote, input); input.close(); } else { OutputStream output; output = new FileOutputStream(local); ftps.retrieveFile(remote, output); output.close(); } ftps.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftps.isConnected()) { try { ftps.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:gov.nih.nci.cacis.ip.mirthconnect.FTPSSenderTest.java
@Test public void sendDocument() throws Exception { final FTPSClient ftpsClient = sender.getFtpsClient(); int numFiles = getNumFiles(); final File inputFile = new File( Thread.currentThread().getContextClassLoader().getResource("Sample_SFTP_File.xml").toURI()); final InputStream inputStream = new FileInputStream(inputFile); sender.sendDocument(inputStream, TEST_SERVER, EXTENSION); assertTrue(FTPReply.isPositiveCompletion(ftpsClient.getReplyCode())); assertEquals(numFiles + 1, getNumFiles()); }
From source file:gov.nih.nci.cacis.ip.mirthconnect.FTPSSenderTest.java
/** * To test, make sure you create the sub directory under /tmp locally, change the sub-directory in * ftoConfig.properties to /test/test2 and remove the @Ignore on this test. Please revert prior to commit. * @throws Exception on error/*w ww. j av a 2 s. co m*/ */ @Test @Ignore public void sendDocumentToSubDirectory() throws Exception { final FTPSClient ftpsClient = sender.getFtpsClient(); int numFiles = getNumFiles(); final File inputFile = new File( Thread.currentThread().getContextClassLoader().getResource("Sample_SFTP_File.xml").toURI()); final InputStream inputStream = new FileInputStream(inputFile); sender.sendDocument(inputStream, TEST_SERVER, EXTENSION); assertTrue(FTPReply.isPositiveCompletion(ftpsClient.getReplyCode())); assertEquals(numFiles + 1, getNumFiles()); }
From source file:ddf.test.itests.catalog.TestFtp.java
private FTPSClient createSecureClient(boolean setKeystore) throws Exception { FTPSClient ftps = new FTPSClient(); if (setKeystore) { KeyManager keyManager = KeyManagerUtils.createClientKeyManager( new File(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword")); ftps.setKeyManager(keyManager);/*from w ww . j ava 2 s. c o m*/ } int attempts = 0; while (true) { try { ftps.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(ftps); int connectionReply = ftps.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftps.login(USERNAME, PASSWORD); showServerReply(ftps); if (!success) { fail("Could not log in to the FTP server."); } ftps.enterLocalPassiveMode(); ftps.setControlKeepAliveTimeout(300); ftps.setFileType(FTP.BINARY_FILE_TYPE); return ftps; }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTPS(ObjFileTransfer ftpObj) throws Exception { FTPSClient ftpsClient = null; int replyCode; boolean completed = false; try {// w w w . ja va 2s .co m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpsClient = new FTPSClient(properties.getFtp_protocal(), properties.isFtp_impicit()); //ftpsClient.setAuthValue(ConstantFtp.FTPS_PROTOCAL); ftpsClient.setDataTimeout(ConstantFtp.FTP_TIMEOUT); ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); System.out.print(ftpsClient.getReplyString()); ftpsClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpsClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpsClient.getReplyCode(); FtpUtil.showServerReply(ftpsClient); if (!FTPReply.isPositiveCompletion(replyCode)) { ftpsClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpsClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpsClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpsClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpsClient.setFileType(FTP.BINARY_FILE_TYPE); ftpsClient.execPBSZ(0); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpsClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpsClient); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpsClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpsClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpsClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpsClient); completed = true; ftpsClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpsClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpsClient.isConnected()) { ftpsClient.logout(); ftpsClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }
From source file:org.mule.transport.ftps.FtpsConnectionFactory.java
public Object makeObject() throws Exception { FTPSClient client = createFTPSClient(); if (uri.getPort() > 0) { client.connect(uri.getHost(), uri.getPort()); } else {/* w w w.j a v a 2 s . c om*/ client.connect(uri.getHost()); } if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Ftp connect failed: " + client.getReplyCode()); } if (!client.login(uri.getUser(), uri.getPassword())) { throw new IOException("Ftp login failed: " + client.getReplyCode()); } if (!client.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IOException("Ftp error. Couldn't set BINARY transfer type: " + client.getReplyCode()); } return client; }
From source file:org.mule.transport.ftps.FtpsConnector.java
/** * Creates a new FTPSClient that logs in and changes the working directory using the data * provided in <code>endpoint</code>. *///from w w w . ja v a2 s . c o m protected FTPSClient createFTPSClient(ImmutableEndpoint endpoint) throws Exception { EndpointURI uri = endpoint.getEndpointURI(); FTPSClient client = this.getFtp(uri); client.setDataTimeout(endpoint.getResponseTimeout()); this.enterActiveOrPassiveMode(client, endpoint); this.setupFileType(client, endpoint); String path = uri.getPath(); // only change directory if one was configured if (StringUtils.isNotBlank(path)) { // MULE-2400: if the path begins with '~' we must strip the first '/' to make things // work with FTPSClient if ((path.length() >= 2) && (path.charAt(1) == '~')) { path = path.substring(1); } //Checking if it is a file or a directory boolean isFile = this.isFile(endpoint, client); if (!isFile && !client.changeWorkingDirectory(path)) { throw new IOException(MessageFormat.format( "Failed to change working directory to {0}. Ftp error: {1}", path, client.getReplyCode())); } else if (isFile) { // Changing the working directory to the parent folder, it should be better if // the FTPSClient API would provide a way to retrieve the parent folder FTPFile[] listFiles = client.listFiles(path); String directory = path.replaceAll(listFiles[0].getName(), ""); client.changeWorkingDirectory(directory); } } return client; }
From source file:org.mule.transport.ftps.FtpsMessageReceiver.java
protected FTPFile[] listFiles() throws Exception { FTPSClient client = null; try {// ww w. j a v a 2 s . c om client = connector.createFTPSClient(endpoint); FTPListParseEngine engine = client.initiateListParsing(); FTPFile[] files = null; List<FTPFile> v = new ArrayList<FTPFile>(); while (engine.hasNext()) { if (getLifecycleState().isStopping()) { break; } files = engine.getNext(FTP_LIST_PAGE_SIZE); if (files == null || files.length == 0) { return files; } for (FTPFile file : files) { if (file.isFile()) { if (filenameFilter == null || filenameFilter.accept(null, file.getName())) { v.add(file); } } } } if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Failed to list files. Ftp error: " + client.getReplyCode()); } return v.toArray(new FTPFile[v.size()]); } finally { if (client != null) { connector.releaseFtp(endpoint.getEndpointURI(), client); } } }
From source file:org.mule.transport.ftps.FtpsMessageReceiver.java
protected void postProcess(FTPSClient client, FTPFile file, MuleMessage message) throws Exception { if (!client.deleteFile(file.getName())) { throw new IOException(MessageFormat.format("Failed to delete file {0}. Ftp error: {1}", file.getName(), client.getReplyCode())); }//from w w w .ja v a 2 s . c o m if (logger.isDebugEnabled()) { logger.debug("Deleted processed file " + file.getName()); } if (connector.isStreaming()) { if (!client.completePendingCommand()) { throw new IOException(MessageFormat.format( "Failed to complete a pending command. Retrieveing file {0}. Ftp error: {1}", file.getName(), client.getReplyCode())); } } }
From source file:org.mule.transport.ftps.FtpsMessageRequester.java
protected void postProcess(FTPSClient client, FTPFile file, MuleMessage message) throws Exception { if (!connector.isStreaming()) { if (!client.deleteFile(file.getName())) { throw new IOException(MessageFormat.format("Failed to delete file {0}. Ftp error: {1}", file.getName(), client.getReplyCode())); }/* w w w.ja v a2 s .co m*/ if (logger.isDebugEnabled()) { logger.debug("Deleted file " + file.getName()); } } }