List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
public boolean ftpConnect(String host, String username, String password, int port) { try {/*from w w w. j a v a 2 s . c o m*/ mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // login using username & password boolean status = mFTPClient.login(username, password); /* Set File Transfer Mode * * To avoid corruption issue you must specified a correct * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE, * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE * for transferring text, image, and compressed files. */ mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); return status; } } catch (Exception e) { String errMsg = parentActivity.getString(R.string.error_message_general); Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR_FTP_CONNECT, 0, 0, errMsg); activityHandler.sendMessage(msg); } return false; }
From source file:com.aliasi.lingmed.medline.DownloadMedline.java
private void initializeFTPClient() throws IOException { mFTPClient = new FTPClient(); mFTPClient.setDataTimeout(FIVE_MINUTES_IN_MS); // mLogger.info("Connecting to NLM"); mFTPClient.connect(mDomainName);//w w w . j a v a2 s . co m checkFtpCompletion("Connecting to server"); // mLogger.info("Connected."); // mLogger.info("Logging in."); mFTPClient.login(mUserName, mPassword); checkFtpCompletion("Login"); // mLogger.info("Logged in to NLM FTP Server."); }
From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java
private FTPClient getClient(final FlowFile flowFile) throws IOException { if (client != null) { String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); if (remoteHostName.equals(desthost)) { // destination matches so we can keep our current session resetWorkingDirectory();/*from w w w . j ava 2 s . co m*/ return client; } else { // this flowFile is going to a different destination, reset // session close(); } } final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue()); final String proxyHost = ctx.getProperty(PROXY_HOST).getValue(); final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger(); FTPClient client; if (proxyType == Proxy.Type.HTTP) { client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(), ctx.getProperty(HTTP_PROXY_PASSWORD).getValue()); } else { client = new FTPClient(); if (proxyType == Proxy.Type.SOCKS) { client.setSocketFactory(new SocksProxySocketFactory( new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort)))); } } this.client = client; client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setDefaultTimeout( ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setRemoteVerificationEnabled(false); final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); this.remoteHostName = remoteHostname; InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(remoteHostname, null); } catch (final UnknownHostException uhe) { } if (inetAddress == null) { inetAddress = InetAddress.getByName(remoteHostname); } client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger()); this.closed = false; client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue(); final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue(); final boolean loggedIn = client.login(username, password); if (!loggedIn) { throw new IOException("Could not login for user '" + username + "'"); } final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue(); if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) { client.enterLocalActiveMode(); } else { client.enterLocalPassiveMode(); } final String transferMode = ctx.getProperty(TRANSFER_MODE).evaluateAttributeExpressions(flowFile) .getValue(); final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE : FTPClient.BINARY_FILE_TYPE; if (!client.setFileType(fileType)) { throw new IOException("Unable to set transfer mode to type " + transferMode); } this.homeDirectory = client.printWorkingDirectory(); return client; }
From source file:dk.netarkivet.common.distribute.IntegrityTestsFTP.java
public void testWrongChecksumThrowsError() throws Exception { Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.FTPRemoteFile"); RemoteFile rf = RemoteFileFactory.getInstance(testFile2, true, false, true); // upload error to ftp server File temp = File.createTempFile("foo", "bar"); FTPClient client = new FTPClient(); client.connect(Settings.get(CommonSettings.FTP_SERVER_NAME), Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT))); client.login(Settings.get(CommonSettings.FTP_USER_NAME), Settings.get(CommonSettings.FTP_USER_PASSWORD)); Field field = FTPRemoteFile.class.getDeclaredField("ftpFileName"); field.setAccessible(true);//from w w w .j av a 2s . co m String filename = (String) field.get(rf); client.storeFile(filename, new ByteArrayInputStream("foo".getBytes())); client.logout(); try { rf.copyTo(temp); fail("Should throw exception on wrong checksum"); } catch (IOFailure e) { // expected } assertFalse("Destination file should not exist", temp.exists()); }
From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java
/** * Login into a account//from www.j a va2 s .c o m * * @return FTPClient object or null * @throws IOException */ public FTPClient login() throws IOException { int reply = 0; FTPClient ftp = new FTPClient(); try { if (port != 0) ftp.connect(getHost(), getPort()); else ftp.connect(getHost()); if (isAnonymous()) ftp.login(ANONYMOUS, GUEST); else if (getSubAccount() != null && !getSubAccount().isEmpty()) ftp.login(getLogin(), getPassword(), getSubAccount()); else ftp.login(getLogin(), getPassword()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString())); if (isPassiveMode()) ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } throw e; } return ftp; }
From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java
private static boolean processFTPdownload(final BackgroundTaskStatusProviderSupportingExternalCallImpl status, String downloadURL, String targetFileName, ObjectRef lastStatus) throws InterruptedException { runIdx++;/*from www.j a va2s. co m*/ final int thisRun = runIdx; status.setCurrentStatusText1(downloadURL); status.setCurrentStatusText2("FTP DOWNLOAD..."); String server, remote; server = downloadURL.substring("ftp://".length()); remote = server.substring(server.indexOf("/") + "/".length()); server = server.substring(0, server.indexOf("/")); final FTPClient ftp; ThreadSafeOptions tso; synchronized (host2ftp) { if (!host2ftp.containsKey(server)) { ThreadSafeOptions ttt = new ThreadSafeOptions(); ttt.setParam(0, new FTPClient()); host2ftp.put(server, ttt); } tso = host2ftp.get(server); ftp = (FTPClient) tso.getParam(0, null); } status.setCurrentStatusValue(0); boolean res; try { boolean wait = false; BackgroundTaskHelper.lockAquire(server, 1); if (wait) { while (wait) { status.setCurrentStatusText1("Waiting for shared FTP connection"); status.setCurrentStatusText2("Server: " + server); try { Thread.sleep(100); } catch (InterruptedException e) { } synchronized (tso) { wait = tso.getBval(1, false); } } } status.setCurrentStatusValue(-1); status.setCurrentStatusText1(downloadURL); status.setCurrentStatusText2("FTP DOWNLOAD..."); res = processDownload(status, downloadURL, targetFileName, lastStatus, thisRun, server, remote, ftp); } finally { BackgroundTaskHelper.lockRelease(server); } return res; }
From source file:adams.flow.standalone.FTPConnection.java
/** * Starts up a FTP session./*from w w w .ja v a 2s . c o m*/ * * @return null if OK, otherwise error message */ protected String connect() { String result; int reply; result = null; try { m_Client = new FTPClient(); m_Client.addProtocolCommandListener(this); m_Client.connect(m_Host); reply = m_Client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { result = "FTP server refused connection: " + reply; } else { if (!m_Client.login(m_User, m_ActualPassword.getValue())) { result = "Failed to connect to '" + m_Host + "' as user '" + m_User + "'"; } else { if (m_UsePassiveMode) m_Client.enterLocalPassiveMode(); if (m_UseBinaryMode) m_Client.setFileType(FTPClient.BINARY_FILE_TYPE); } } } catch (Exception e) { result = handleException("Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e); m_Client = null; } return result; }
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.//w w w . j a va 2 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:edu.lternet.pasta.dml.download.DownloadHandler.java
/** * Gets content from given source and writes it to DataStorageInterface * to store them. This method will be called by run() * //from w w w . j av a 2 s . c o m * @param resourceName the URL to the source data to be retrieved */ protected boolean getContentFromSource(String resourceName) { boolean successFlag = false; QualityCheck onlineURLsQualityCheck = null; boolean onlineURLsException = false; // used to determine status of onlineURLs quality check if (resourceName != null) { resourceName = resourceName.trim(); } if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://") || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) { // get the data from a URL int responseCode = 0; String responseMessage = null; try { URL url = new URL(resourceName); boolean isFTP = false; if (entity != null) { String contentType = null; // Find the right MIME type and set it as content type if (resourceName.startsWith("http")) { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.connect(); contentType = httpURLConnection.getContentType(); responseCode = httpURLConnection.getResponseCode(); responseMessage = httpURLConnection.getResponseMessage(); } else if (resourceName.startsWith("file")) { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); contentType = urlConnection.getContentType(); } else { // FTP isFTP = true; contentType = "application/octet-stream"; } entity.setUrlContentType(contentType); } if (!isFTP) { // HTTP(S) or FILE InputStream filestream = url.openStream(); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { filestream.close(); } } else { // FTP String[] urlParts = resourceName.split("/"); String address = urlParts[2]; String dir = "/"; for (int i = 3; i < urlParts.length - 1; i++) { dir += urlParts[i] + "/"; } String fileName = urlParts[urlParts.length - 1]; FTPClient ftpClient = new FTPClient(); ftpClient.connect(address); ftpClient.login(ANONYMOUS, anonymousFtpPasswd); ftpClient.changeWorkingDirectory(dir); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking InputStream filestream = ftpClient.retrieveFileStream(fileName); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { try { filestream.close(); } catch (IOException e) { exception = new DataSourceNotFoundException(String .format("Error closing local file '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } // logout and disconnect if FTP session if (resourceName.startsWith("ftp") && ftpClient != null) { try { ftpClient.enterLocalActiveMode(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { exception = new DataSourceNotFoundException( String.format("Error disconnecting from FTP with resource '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } } } catch (MalformedURLException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage)); } catch (IOException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); if (responseCode > 0) { eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage); } onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is not reachable: %s", resourceName, eMessage)); } // Initialize the "Online URLs are live" quality check String qualityCheckIdentifier = "onlineURLs"; QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier); onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate); if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) { String resourceNameEscaped = embedInCDATA(resourceName); if (!onlineURLsException) { onlineURLsQualityCheck.setStatus(Status.valid); onlineURLsQualityCheck.setFound("true"); onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped); } else { onlineURLsQualityCheck.setFailedStatus(); onlineURLsQualityCheck.setFound("false"); String explanation = "Failed to access URL: " + resourceNameEscaped; explanation = explanation + "; " + embedInCDATA(exception.getMessage()); onlineURLsQualityCheck.setExplanation(explanation); } entity.addQualityCheck(onlineURLsQualityCheck); } return successFlag; } else if (resourceName != null && resourceName.startsWith("ecogrid://")) { // get the docid from url int start = resourceName.indexOf("/", 11) + 1; //log.debug("start: " + start); int end = resourceName.indexOf("/", start); if (end == -1) { end = resourceName.length(); } //log.debug("end: " + end); String ecogridIdentifier = resourceName.substring(start, end); // pass this docid and get data item //System.out.println("the endpoint is "+ECOGRIDENDPOINT); //System.out.println("The identifier is "+ecogridIdentifier); //return false; return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier); } else if (resourceName != null && resourceName.startsWith("srb://")) { // get srb docid from the url String srbIdentifier = transformSRBurlToDocid(resourceName); // reset endpoint for srb (This is hack we need to figure ou // elegent way to do this //mEndPoint = Config.getValue("//ecogridService/srb/endPoint"); // pass this docid and get data item //log.debug("before get srb data"); return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier); } else { successFlag = false; return successFlag; } }
From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) throws SocketException, IOException { String[] vehicles = controlledVehicles.split(","); jTextArea1.setText(""); jTextArea1.repaint();/*w ww . ja v a 2 s . co m*/ showText("Initializing Control Structures"); try { startLocalStructures(vehicles); } catch (Exception e) { GuiUtils.errorMessage(getConsole(), e); return; } AUVS = positions.keySet().size(); showText("Initializing server connection"); FTPClient client = new FTPClient(); boolean PathNameCreated = false; try { client.connect("www.convcao.com", 21); client.login(jTextField1.getText(), new String(jPasswordField1.getPassword())); PathNameCreated = client.makeDirectory("/NEPTUS/" + SessionID); client.logout(); } catch (IOException e) { jLabel6.setText("Connection Error"); throw e; } showText("Sending session data"); InputData initialState = new InputData(); initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()); initialState.SessionID = SessionID; initialState.DemoMode = "1"; initialState.AUVs = "" + positions.keySet().size(); String fileName = SessionID + ".txt"; Gson gson = new Gson(); String json = gson.toJson(initialState); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.write(json); writer.close(); if (PathNameCreated) { jLabel6.setText("Connection Established"); jLabel1.setVisible(true); System.out.println("Uploading first file"); Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()), fileName); //send first file System.out.println("Uploading second file"); Upload("www.convcao.com", "NEPTUS/" + SessionID, "plugins-dev/caoAgent/convcao/com/caoAgent/", jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); //send sparse map System.out.println("Both files uploaded"); jButton1.setEnabled(true); jButton2.setEnabled(true); jTextPane1.setEditable(false); jTextField1.setEditable(false); jPasswordField1.setEditable(false); connectButton.setEnabled(false); renewButton.setEnabled(false); } else { jLabel6.setText(client.getReplyString()); jLabel1.setVisible(false); } myDeleteFile(fileName); showText("ConvCAO control has started"); }