List of usage examples for org.apache.commons.net.ftp FTPClient login
public boolean login(String username, String password) throws IOException
From source file:adams.gui.chooser.FtpRemoteDirectorySetup.java
/** * Returns a new client for the host/port defined in the options. * * @return the client/* w w w . jav a 2 s . c o m*/ */ public FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java
/** * _more_// ww w . j a v a 2s . c om * * @param file * _more_ * @param ignoreErrors * _more_ * * @return _more_ * * @throws Exception * _more_ */ private byte[] readFile(String file, boolean ignoreErrors) throws Exception { if (new File(file).exists()) { return IOUtil.readBytes(IOUtil.getInputStream(file, getClass())); } if (!file.startsWith("ftp:")) { if (ignoreErrors) { return null; } throw new FileNotFoundException("Could not read file: " + file); } URL url = new URL(file); FTPClient ftp = new FTPClient(); try { ftp.connect(url.getHost()); ftp.login("anonymous", "password"); ftp.setFileType(FTP.IMAGE_FILE_TYPE); ftp.enterLocalPassiveMode(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftp.retrieveFile(url.getPath(), bos)) { return bos.toByteArray(); } else { throw new IOException("Unable to retrieve file:" + url); } } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) { System.err.println("ftp error:" + fcce); System.err.println(ftp.getReplyString()); if (!ignoreErrors) { throw fcce; } return null; } catch (Exception exc) { if (!ignoreErrors) { throw exc; } return null; } finally { try { ftp.logout(); } catch (Exception exc) { } try { ftp.disconnect(); } catch (Exception exc) { } } }
From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java
protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient ftp = null; try {/* w w w. ja va2s .com*/ ftp = new FTPClient(); // For debug // f.addProtocolCommandListener(new PrintCommandListener( // new PrintWriter(System.out))); ftp.setConnectTimeout(120000); ftp.setControlKeepAliveTimeout(180); ftp.setDataTimeout(120000); ftp.connect(fpi.getHost()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); ftp.login(fpi.getUsername(), fpi.getPassword()); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); if (fpi.isFtpUsePassiveMode()) ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException("FTP Error Code: " + reply); FTPClient ftpReturn = ftp; ftp = null; return ftpReturn; } finally { if (ftp != null) ftpQuietDisconnect(ftp); } }
From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java
/** * ftp?/*from w w w . ja v a 2 s . com*/ * * @param ftpClient * @return ?true?false * @throws Exception */ private boolean connect(FTPClient ftpClient) throws Exception { try { ftpClient.connect(host, port); // ????? int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { //ftp? if (ftpClient.login(username, password)) { setFileType(ftpClient); return true; } } else { ftpClient.disconnect(); throw new Exception("FTP server refused connection."); } } catch (IOException e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); // } catch (IOException e1) { throw new Exception("Could not disconnect from server.", e1); } } throw new Exception("Could not connect to server.", e); } return false; }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates a connection to a target host and then executes an FTP * request to send or receive a file to or from the target. This is fully * key-based, as a result, a keyfile is required for the connection to * successfully authenticate./*from w ww . jav a2 s .c o m*/ * * @param sourceFile - The full path to the source file to transfer * @param targetFile - The full path (including file name) of the desired target file * @param targetHost - The target server to perform the transfer to * @param isUpload - <code>true</code> is the transfer is an upload, <code>false</code> if it * is a download * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized void executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", sourceFile); DEBUGGER.debug("Value: {}", targetFile); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", isUpload); } final FTPClient client = new FTPClient(); final FTPConfig ftpConfig = appBean.getConfigData().getFtpConfig(); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); DEBUGGER.debug("FTPConfig: {}", ftpConfig); } try { client.connect(targetHost); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); } if (!(client.isConnected())) { throw new IOException("Failed to authenticate to remote host with the provided information"); } boolean isAuthenticated = false; if (StringUtils.isNotBlank(ftpConfig.getFtpAccount())) { isAuthenticated = client.login( (StringUtils.isNotEmpty(ftpConfig.getFtpAccount())) ? ftpConfig.getFtpAccount() : System.getProperty("user.name"), PasswordUtils.decryptText(ftpConfig.getFtpPassword(), ftpConfig.getFtpSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding())); } else { isAuthenticated = client.login(ftpConfig.getFtpAccount(), null); } if (DEBUG) { DEBUGGER.debug("isAuthenticated: {}", isAuthenticated); } if (!(isAuthenticated)) { throw new IOException("Failed to connect to FTP server: " + targetHost); } client.enterLocalPassiveMode(); if (!(FileUtils.getFile(sourceFile).exists())) { throw new IOException("File " + sourceFile + " does not exist. Skipping"); } if (isUpload) { client.storeFile(targetFile, new FileInputStream(FileUtils.getFile(sourceFile))); } else { client.retrieveFile(sourceFile, new FileOutputStream(targetFile)); } if (DEBUG) { DEBUGGER.debug("Reply: {}", client.getReplyCode()); DEBUGGER.debug("Reply: {}", client.getReplyString()); } } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } finally { try { if (client.isConnected()) { client.completePendingCommand(); client.disconnect(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } }
From source file:adams.core.io.lister.FtpDirectoryLister.java
/** * Returns a new client for the host defined in the options. * * @return the client, null if failed to create *//*from www . jav a 2 s . c om*/ protected FTPClient newClient() { FTPClient result; int reply; try { result = new FTPClient(); result.addProtocolCommandListener(this); result.connect(m_Host); reply = result.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { getLogger().severe("FTP server refused connection: " + reply); } else { if (!result.login(m_User, m_Password.getValue())) { getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'"); } else { if (m_UsePassiveMode) result.enterLocalPassiveMode(); if (m_UseBinaryMode) result.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); result = null; } return result; }
From source file:com.dinochiesa.edgecallouts.FtpPut.java
public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) { FtpCalloutResult info = new FtpCalloutResult(); try {/*from w ww . j a v a 2s .c o m*/ // The executes in the IO thread! String sourceVar = getSourceVar(messageContext); InputStream src = null; boolean wantBase64Decode = getWantBase64Decode(messageContext); if (sourceVar == null) { src = messageContext.getMessage().getContentAsStream(); // conditionally wrap a decoder around it if (wantBase64Decode) { src = new Base64InputStream(src); } } else { info.addMessage("Retrieving data from " + sourceVar); String sourceData = messageContext.getVariable(sourceVar); byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData) : sourceData.getBytes(StandardCharsets.UTF_8); src = new ByteArrayInputStream(b); } String remoteName = getRemoteFileName(messageContext); remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-"); String ftpServer = getFtpServer(messageContext); int ftpPort = getFtpPort(messageContext); String user = getFtpUser(messageContext); String password = getFtpPassword(messageContext); info.addMessage("connecting to server " + ftpServer); FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new FtpCommandListener(info)); ftp.connect(ftpServer, ftpPort); ftp.enterLocalPassiveMode(); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("The FTP server refused the connection."); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } if (!ftp.login(user, password)) { ftp.disconnect(); info.setStatus("FAIL"); info.addMessage("Login failure"); messageContext.setVariable(varName("result"), info.toJsonString()); return ExecutionResult.ABORT; } info.addMessage("logged in as " + user); String initialDirectory = getInitialDirectory(messageContext); if ((initialDirectory != null) && (!initialDirectory.equals(""))) { ftp.changeWorkingDirectory(initialDirectory); } ftp.setFileType(FTP.BINARY_FILE_TYPE); OutputStream os = ftp.storeFileStream(remoteName); if (os == null) { // cannot open output stream info.addMessage("cannot open output stream to " + remoteName); info.setStatus("FAIL"); } else { byte[] buf = new byte[2048]; int n; while ((n = src.read(buf)) > 0) { os.write(buf, 0, n); } os.close(); src.close(); boolean completed = ftp.completePendingCommand(); info.addMessage("transfer completed: " + completed); info.setStatus("OK"); } ftp.disconnect(); info.addMessage("All done."); messageContext.setVariable(varName("result"), info.toJsonString()); } catch (java.lang.Exception exc1) { if (getDebug()) { System.out.println(ExceptionUtils.getStackTrace(exc1)); } String error = exc1.toString(); messageContext.setVariable(varName("exception"), error); info.setStatus("FAIL"); info.addMessage(error); messageContext.setVariable(varName("result"), info.toJsonString()); int ch = error.lastIndexOf(':'); if (ch >= 0) { messageContext.setVariable(varName("error"), error.substring(ch + 2).trim()); } else { messageContext.setVariable(varName("error"), error); } messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1)); return ExecutionResult.ABORT; } return ExecutionResult.SUCCESS; }
From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java
/** * Retrieve the FTP client belonging to the given URI. * /*ww w . j av a 2 s. com*/ * @param uri * @return FTPClient */ protected FTPClient retrieveFtpClient(final URI uri) { // Create the FTP client FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not connect to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); logger.error("Could not login to the given FTP server " + uri.getHost() + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString()); return null; } // Switch to PASV and BINARY mode ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return ftpClient; } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } return null; }
From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java
public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName, String originalFileName) { if (logger.isDebugEnabled()) { logger.debug("SampleUploadCluster.process called"); }/* ww w.jav a 2 s . c om*/ FTPClient ftp = new FTPClient(); OutputStream out = null; File file = new File(sourceRepositoryPath + "/" + maskingFileName); FileInputStream fin = null; BufferedInputStream bin = null; String storeFileName = null; String server = "?IP";//?? ? . ex) 210.25.3.21 try { ftp.connect(server); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); storeFileName = maskingFileName + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); ftp.login("testId", "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length())); if (logger.isDebugEnabled()) { logger.debug(server + " connect success !!! "); } ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/"); out = ftp.storeFileStream(storeFileName); FileCopyUtils.copy(fin, out); if (logger.isDebugEnabled()) { logger.debug(" cluster success !!! "); } } else { ftp.disconnect(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (bin != null) bin.close(); ftp.logout(); out = null; bin = null; } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java
/** * //from w w w . jav a 2 s . co m */ private String retrieveFTP(String aURL) { debug("retrieveFTP (" + aURL + ")"); URL urlObject = null; try { urlObject = new URL(aURL); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/"); HoopLink.fManager.createDirectory(downloadPath); File translator = new File(urlObject.getFile()); String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName(); OutputStream fileStream = null; if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) { this.setErrorString("Error opening temporary output file"); return (null); } fileStream = HoopLink.fManager.getOutputStreamBinary(); if (fileStream == null) { this.setErrorString("Error opening temporary output file"); return (null); } debug("Starting FTP client ..."); FTPClient ftp = new FTPClient(); try { int reply; debug("Connecting ..."); ftp.connect(urlObject.getHost()); debug("Connected to " + urlObject.getHost() + "."); debug(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("FTP server refused connection."); return (null); } else { ftp.login("anonymous", "hoop-dev@gmail.com"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); debug("Unable to login to FTP server"); return (null); } debug("Logged in"); boolean rep = true; String pathFixed = translator.getParent().replace("\\", "/"); rep = ftp.changeWorkingDirectory(pathFixed); if (rep == false) { debug("Unable to change working directory to: " + pathFixed); return (null); } else { debug("Current working directory: " + pathFixed); debug("Retrieving file " + urlObject.getFile() + " ..."); try { rep = ftp.retrieveFile(urlObject.getFile(), fileStream); } catch (FTPConnectionClosedException connEx) { debug("Caught: FTPConnectionClosedException"); connEx.printStackTrace(); return (null); } catch (CopyStreamException strEx) { debug("Caught: CopyStreamException"); strEx.printStackTrace(); return (null); } catch (IOException ioEx) { debug("Caught: IOException"); ioEx.printStackTrace(); return (null); } debug("File retrieved"); } ftp.logout(); } } catch (IOException e) { debug("Error retrieving FTP file"); e.printStackTrace(); return (null); } finally { if (ftp.isConnected()) { debug("Closing ftp connection ..."); try { ftp.disconnect(); } catch (IOException ioe) { debug("Exception closing ftp connection"); } } } debug("Closing local file stream ..."); try { fileStream.close(); } catch (IOException e) { e.printStackTrace(); } String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName)); return (result); }