List of usage examples for org.apache.commons.net.ftp FTPClient getReplyCode
public int getReplyCode()
From source file:dk.dma.dmiweather.service.FTPLoader.java
/** * Check for files every 10 minutes. New files are given to the gridWeatherService */// ww w . java2 s .c om @Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000) public void checkFiles() { log.info("Checking FTP files at DMI."); FTPClient client = new FTPClient(); try { client.setDataTimeout(20 * 1000); client.setBufferSize(1024 * 1024); client.connect(hostname); if (client.login("anonymous", "")) { try { client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); for (ForecastConfiguration configuration : configurations) { // DMI creates a Newest link once all files have been created if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) { if (client.getReplyCode() != 250) { log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode()); } String workingDirectory = new File(client.printWorkingDirectory()).getName(); String previousNewest = newestDirectories.get(configuration); if (!workingDirectory.equals(previousNewest)) { // a new directory for this configuration is available on the server FTPFile[] listFiles = client.listFiles(); List<FTPFile> files = Arrays.stream(listFiles) .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches()) .collect(Collectors.toList()); try { Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory, files); gridWeatherService.newFiles(localFiles, configuration); } catch (IOException e) { log.warn("Unable to get new weather files from DMI", e); } if (previousNewest != null) { File previous = new File(tempDirLocation, previousNewest); deleteRecursively(previous); } newestDirectories.put(configuration, workingDirectory); } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to change ftp directory to {}", configuration.getFolder()); } } } finally { try { client.logout(); } catch (IOException e) { log.info("Failed to logout", e); } } } else { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to login to {}", hostname); } } catch (IOException e) { gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM); log.error("Unable to update weather files from DMI", e); } finally { try { client.disconnect(); } catch (IOException e) { log.info("Failed to disconnect", e); } } log.info("Check completed."); }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * /*from w ww . j a v a 2s .co m*/ * @throws UnknownHostException * If the hostname cannot be resolved. * * @throws SocketException * If the socket timeout could not be set. * * @throws FTPConnectionClosedException * If the connection is closed by the server. * * @throws LoginFailedException * If the login fails. * * @throws DirectoryChangeFailedException * If changing to the directory provided by the internet * archive fails. * * @throws CopyStreamException * If an I/O error occurs while in the middle of * transferring a file. * * @throws IOException * If an I/O error occurs while sending a command or * receiving a reply from the server * * @throws IllegalStateException * If the contribution object is not ready to upload * (no username, password, server, etc. set) * or if java's xml parser is configured badly */ public void upload() throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException, DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException { final int NUM_XML_FILES = 2; final String META_XML_SUFFIX = "_meta.xml"; final String FILES_XML_SUFFIX = "_files.xml"; final String username = getUsername(); final String password = getPassword(); if (getFtpServer() == null) { throw new IllegalStateException("ftp server not set"); } if (getFtpPath() == null) { throw new IllegalStateException("ftp path not set"); } if (username == null) { throw new IllegalStateException("username not set"); } if (password == null) { throw new IllegalStateException("password not set"); } // calculate total number of files and bytes final String metaXmlString = serializeDocument(getMetaDocument()); final String filesXmlString = serializeDocument(getFilesDocument()); final byte[] metaXmlBytes = metaXmlString.getBytes(); final byte[] filesXmlBytes = filesXmlString.getBytes(); final int metaXmlLength = metaXmlBytes.length; final int filesXmlLength = filesXmlBytes.length; final Collection files = getFiles(); final int totalFiles = NUM_XML_FILES + files.size(); final String[] fileNames = new String[totalFiles]; final long[] fileSizes = new long[totalFiles]; final String metaXmlName = getIdentifier() + META_XML_SUFFIX; fileNames[0] = metaXmlName; fileSizes[0] = metaXmlLength; final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX; fileNames[1] = filesXmlName; fileSizes[1] = filesXmlLength; int j = 2; for (Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); fileNames[j] = f.getRemoteFileName(); fileSizes[j] = f.getFileSize(); j++; } // init the progress mapping for (int i = 0; i < fileSizes.length; i++) { _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i])); _totalUploadSize += fileSizes[i]; } FTPClient ftp = new FTPClient(); try { // first connect if (isCancelled()) { return; } ftp.enterLocalPassiveMode(); if (isCancelled()) { return; } ftp.connect(getFtpServer()); final int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RefusedConnectionException(getFtpServer() + "refused FTP connection"); } // now login if (isCancelled()) { return; } if (!ftp.login(username, password)) { throw new LoginFailedException(); } try { // try to change the directory if (!ftp.changeWorkingDirectory(getFtpPath())) { // if changing fails, make the directory if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } // now change directory, if it fails again bail if (isCancelled()) { return; } if (!ftp.changeWorkingDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } } if (isCancelled()) { return; } connected(); // upload xml files uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp); uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp); // now switch to binary mode if (isCancelled()) { return; } ftp.setFileType(FTP.BINARY_FILE_TYPE); // upload contributed files for (final Iterator i = files.iterator(); i.hasNext();) { final File f = (File) i.next(); uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp); } } catch (InterruptedIOException ioe) { // we've been requested to cancel return; } finally { ftp.logout(); // we don't care if logging out fails } } finally { try { ftp.disconnect(); } catch (IOException e) { } // don't care if disconnecting fails } // now tell the Internet Archive that we're done if (isCancelled()) { return; } checkinStarted(); if (isCancelled()) { return; } checkin(); if (isCancelled()) { return; } checkinCompleted(); }
From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java
/** * @param host FTP Host name.// w w w . j av a2 s . com * @param port FTP port. * @param user FTP User. * @param pswd FTP Password. * @param c Context * @return Downloaded name file or blank list if something was going wrong. */ private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) { String result = ""; FTPClient mFTPClient = null; try { 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(user, pswd); mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA); FTPFile[] fileList = mFTPClient.listFiles(); long timestamp = 0l; String nameFile = ""; for (int i = 0; i < fileList.length; i++) { if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) { timestamp = fileList[i].getTimestamp().getTimeInMillis(); nameFile = fileList[i].getName(); } } Log.d(TAG, "File da scaricare: " + nameFile); mFTPClient.enterLocalActiveMode(); File folder = new File(Constants.DIR_ROBOT_IMG); OutputStream outputStream = null; boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } try { outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile); success = mFTPClient.retrieveFile(nameFile, outputStream); } catch (Exception e) { return e.getMessage(); } finally { if (outputStream != null) { outputStream.close(); } } if (success) { result = nameFile; mFTPClient.deleteFile(nameFile); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { if (mFTPClient != null) { try { mFTPClient.logout(); mFTPClient.disconnect(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } } return result; }
From source file:lucee.runtime.tag.Ftp.java
/** * check completion status of the client * @param client//from w ww . jav a 2 s . c o m * @return FTPCLient * @throws ApplicationException */ private boolean checkCompletion(FTPClient client) throws ApplicationException { boolean isPositiveCompletion = FTPReply.isPositiveCompletion(client.getReplyCode()); if (isPositiveCompletion) return false; if (count++ < retrycount) return true; if (stoponerror) { throw new lucee.runtime.exp.FTPException(action, client); } return false; }
From source file:com.tumblr.maximopro.iface.router.FTPHandler.java
@Override public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException { byte[] encodedData = super.invoke(metaData, data); this.metaData = metaData; FTPClient ftp; if (enableSSL()) { FTPSClient ftps = new FTPSClient(isImplicit()); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); ftp = ftps;//from w ww. j a v a 2 s . c om } else { ftp = new FTPClient(); } InputStream is = null; try { if (getTimeout() > 0) { ftp.setDefaultTimeout(getTimeout()); } if (getBufferSize() > 0) { ftp.setBufferSize(getBufferSize()); } if (getNoDelay()) { ftp.setTcpNoDelay(getNoDelay()); } ftp.connect(getHostname(), getPort()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } if (!ftp.login(getUsername(), getPassword())) { ftp.logout(); ftp.disconnect(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (enableActive()) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } is = new ByteArrayInputStream(encodedData); String remoteFileName = getFileName(metaData); ftp.changeWorkingDirectory("/"); if (createDirectoryStructure(ftp, getDirName().split("/"))) { ftp.storeFile(remoteFileName, is); } else { throw new MXApplicationException("iface", "cannotcreatedir"); } ftp.logout(); } catch (MXException e) { throw e; } catch (SocketException e) { throw new MXApplicationException("iface", "ftpsocketerror", e); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } if (ftp != null && ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new MXApplicationException("iface", "ftpioerror", e); } } } return null; }
From source file:ddf.test.itests.catalog.TestFtp.java
private FTPClient createInsecureClient() throws Exception { FTPClient ftp = new FTPClient(); int attempts = 0; while (true) { try {/*from w w w. ja va 2s.c om*/ ftp.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(ftp); int connectionReply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftp.login(USERNAME, PASSWORD); showServerReply(ftp); if (!success) { fail("Could not log in to the FTP server."); } ftp.enterLocalPassiveMode(); ftp.setControlKeepAliveTimeout(300); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; }
From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java
@Override public void run(ActionContext context) throws Exception { Path destination = new Path(config.getDestDirectory()); FileSystem fileSystem = FileSystem.get(new Configuration()); destination = fileSystem.makeQualified(destination); if (!fileSystem.exists(destination)) { fileSystem.mkdirs(destination);//w ww . ja v a 2 s . com } FTPClient ftp; if ("ftp".equals(config.getProtocol().toLowerCase())) { ftp = new FTPClient(); } else { ftp = new FTPSClient(); } ftp.setControlKeepAliveTimeout(5); // UNIX type server FTPClientConfig ftpConfig = new FTPClientConfig(); // Set additional parameters required for the ftp // for example config.setServerTimeZoneId("Pacific/Pitcairn") ftp.configure(ftpConfig); try { ftp.connect(config.getHost(), config.getPort()); ftp.enterLocalPassiveMode(); String replyString = ftp.getReplyString(); LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(), config.getPort(), replyString); // Check the reply code for actual success int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.", replyCode, replyString)); } if (!ftp.login(config.getUserName(), config.getPassword())) { LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString()); ftp.logout(); throw new RuntimeException(String.format( "Login to the FTP server %s and port %s failed. " + "Please check user name and password.", config.getHost(), config.getPort())); } FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory()); LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString()); // Check the reply code for listFiles call. // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) { // encrypt data channel and listFiles again ((FTPSClient) ftp).execPROT("P"); LOG.info("Attempting command listFiles on encrypted data channel."); ftpFiles = ftp.listFiles(config.getSrcDirectory()); } for (FTPFile file : ftpFiles) { String source = config.getSrcDirectory() + "/" + file.getName(); LOG.info("Current file {}, source {}", file.getName(), source); if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) { copyZip(ftp, source, fileSystem, destination); } else { Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName())); LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString()); try (OutputStream output = fileSystem.create(destinationPath)) { InputStream is = ftp.retrieveFileStream(source); ByteStreams.copy(is, output); } } if (!ftp.completePendingCommand()) { LOG.error("Error completing command."); } } ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (Throwable e) { LOG.error("Failure to disconnect the ftp connection.", e); } } } }
From source file:com.thebigbang.ftpclient.FTPOperation.java
/** * will force keep the device turned on for all the operation duration. * @param params//w w w . j av a 2 s. c o m * @return */ @SuppressLint("Wakelock") @SuppressWarnings("deprecation") @Override protected Boolean doInBackground(FTPBundle... params) { Thread.currentThread().setName("FTPOperationWorker"); for (final FTPBundle bundle : params) { FTPClient ftp = new FTPClient(); PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client"); try { // setup ftp connection: InetAddress addr = InetAddress.getByName(bundle.FTPServerHost); //set here the timeout. TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() { @Override public void Occurred(TimeoutException e) { bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; publishProgress(bundle); } }); timeout.start(); ftp.connect(addr, bundle.FTPServerPort); int reply = ftp.getReplyCode(); timeout.Stop(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("connection refuse"); } ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword); if (bundle.OperationType == FTPOperationType.Connect) { bundle.OperationStatus = FTPOperationStatus.Succed; publishProgress(bundle); continue; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); w.acquire(); // then switch between enum of operation types. if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.GetData) { String finalFPFi = bundle.LocalFilePathName; // The remote filename to be downloaded. if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") { File f = new File(bundle.LocalWorkingDirectory); f.mkdirs(); finalFPFi = bundle.LocalWorkingDirectory + finalFPFi; } FileOutputStream fos = new FileOutputStream(finalFPFi); // Download file from FTP server String finalFileN = bundle.RemoteFilePathName; if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") { finalFileN = bundle.RemoteWorkingDirectory + finalFileN; } boolean b = ftp.retrieveFile(finalFileN, fos); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; fos.close(); } else if (bundle.OperationType == FTPOperationType.SendData) { InputStream istr = new FileInputStream(bundle.LocalFilePathName); ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr); istr.close(); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; } else if (bundle.OperationType == FTPOperationType.DeleteData) { throw new IOException("DeleteData is Not yet implemented"); } ftp.disconnect(); // then finish/return. //publishProgress(bundle); } catch (IOException e) { e.printStackTrace(); bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; } try { w.release(); } catch (RuntimeException ex) { ex.printStackTrace(); } publishProgress(bundle); } return true; }
From source file:com.mirth.connect.connectors.file.filesystems.FtpConnection.java
public FtpConnection(String host, int port, FileSystemConnectionOptions fileSystemOptions, boolean passive, int timeout, FTPClient client) throws Exception { this.client = client; // This sets the timeout for read operations on data sockets. It does not affect write operations. client.setDataTimeout(timeout);/*from w ww . j a v a 2 s. c om*/ // This sets the timeout for the initial connection. client.setConnectTimeout(timeout); try { if (port > 0) { client.connect(host, port); } else { client.connect(host); } // This sets the timeout for read operations on the command socket. As per JavaDoc comments, you should only call this after the connection has been opened by connect() client.setSoTimeout(timeout); if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.login(fileSystemOptions.getUsername(), fileSystemOptions.getPassword())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IOException("Ftp error"); } initialize(); if (passive) { client.enterLocalPassiveMode(); } } catch (Exception e) { if (client.isConnected()) { client.disconnect(); } throw e; } }
From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java
private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException { if (config != null) { AzureManager manager = AzureManagerImpl.getManager(project); WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings( config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName()); // retrieve ftp publish profile WebSitePublishSettings.FTPPublishProfile ftpProfile = null; for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof WebSitePublishSettings.FTPPublishProfile) { ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp; break; }// w w w . ja v a2 s . c om } if (ftpProfile != null) { FTPClient ftp = new FTPClient(); try { URI uri = null; uri = new URI(ftpProfile.getPublishUrl()); ftp.connect(uri.getHost()); final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); } if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) { ftp.logout(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (ftpProfile.isFtpPassiveMode()) { ftp.enterLocalPassiveMode(); } ftp.deleteFile(ftpPath + message("configName")); String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator, message("configName")); File file = new File(tmpPath); if (file.exists()) { file.delete(); } WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath); String jdkFolderName = ""; if (customJDKUser.isSelected()) { String url = customUrl.getText(); jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length()); jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip")); } else { String cloudVal = WindowsAzureProjectManager .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile); jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length()); } String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName; String serverPath = "%programfiles(x86)%\\" + WAHelper .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion()); WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath); InputStream input = new FileInputStream(tmpPath); ftp.storeFile(ftpPath + message("configName"), input); cleanup(ftp); ftp.logout(); } catch (Exception e) { AzurePlugin.log(e.getMessage(), e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } } } }