List of usage examples for org.apache.commons.net.ftp FTPClient setFileType
public boolean setFileType(int fileType) throws IOException
From source file:org.limy.common.util.FtpUtils.java
/** * FTP????/*from w w w. ja v a 2 s . c om*/ * @param client FTP * @param rootPath * @param relativePath ?? * @param contents * @return ???? * @throws IOException I/O */ public static boolean uploadFileFtp(FTPClient client, String rootPath, String relativePath, InputStream contents) throws IOException { int cwd = client.cwd(rootPath); if (cwd == FTPReply.FILE_UNAVAILABLE) { // ??????? if (rootPath.startsWith("/")) { mkdirsAbsolute(client, rootPath); } else { mkdirs(client, rootPath); } } LOG.debug("uploadFileFtp : " + rootPath + " ->" + relativePath); String targetDir = UrlUtils.getParent(relativePath); if (targetDir.startsWith("/")) { mkdirsAbsolute(client, targetDir); } else { mkdirs(client, targetDir); } client.cwd(rootPath); client.setFileType(FTP.BINARY_FILE_TYPE); client.site("chmod 664 " + relativePath); return client.storeFile(relativePath, contents); }
From source file:org.mule.transport.ftp.FtpConnectionFactory.java
public Object makeObject() throws Exception { FTPClient client = new FTPClient(); if (uri.getPort() > 0) { client.connect(uri.getHost(), uri.getPort()); } else {/*from w w w. j a v a 2s . c o m*/ 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.ftp.FtpConnector.java
/** * Transfer type is BINARY by default. The value is taken from the connector * settings. In case there are any overriding properties set on the endpoint, * those will be used. <p/> The alternative type is ASCII. <p/> * * @see #setBinary(boolean)/*from w w w.j a va 2 s . c om*/ */ public void setupFileType(FTPClient client, ImmutableEndpoint endpoint) throws Exception { int type; // well, no endpoint URI here, as we have to use the most common denominator // in API :( final String binaryTransferString = (String) endpoint.getProperty(FtpConnector.PROPERTY_BINARY_TRANSFER); if (binaryTransferString == null) { // try the connector properties then if (isBinary()) { if (logger.isTraceEnabled()) { logger.trace("Using FTP BINARY type"); } type = org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE; } else { if (logger.isTraceEnabled()) { logger.trace("Using FTP ASCII type"); } type = org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE; } } else { // override with endpoint's definition final boolean binaryTransfer = Boolean.valueOf(binaryTransferString).booleanValue(); if (binaryTransfer) { if (logger.isTraceEnabled()) { logger.trace("Using FTP BINARY type (endpoint override)"); } type = org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE; } else { if (logger.isTraceEnabled()) { logger.trace("Using FTP ASCII type (endpoint override)"); } type = org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE; } } client.setFileType(type); }
From source file:org.opennms.systemreport.formatters.FtpSystemReportFormatter.java
@Override public void end() { m_zipFormatter.end();/* w w w . j a v a 2s. c o m*/ IOUtils.closeQuietly(m_outputStream); final FTPClient ftp = new FTPClient(); FileInputStream fis = null; try { if (m_url.getPort() == -1 || m_url.getPort() == 0 || m_url.getPort() == m_url.getDefaultPort()) { ftp.connect(m_url.getHost()); } else { ftp.connect(m_url.getHost(), m_url.getPort()); } if (m_url.getUserInfo() != null && m_url.getUserInfo().length() > 0) { final String[] userInfo = m_url.getUserInfo().split(":", 2); ftp.login(userInfo[0], userInfo[1]); } else { ftp.login("anonymous", "opennmsftp@"); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); LOG.error("FTP server refused connection."); return; } String path = m_url.getPath(); if (path.endsWith("/")) { LOG.error("Your FTP URL must specify a filename."); return; } File f = new File(path); path = f.getParent(); if (!ftp.changeWorkingDirectory(path)) { LOG.info("unable to change working directory to {}", path); return; } LOG.info("uploading {} to {}", f.getName(), path); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); fis = new FileInputStream(m_zipFile); if (!ftp.storeFile(f.getName(), fis)) { LOG.info("unable to store file"); return; } LOG.info("finished uploading"); } catch (final Exception e) { LOG.error("Unable to FTP file to {}", m_url, e); } finally { IOUtils.closeQuietly(fis); if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } }
From source file:org.openspice.vfs.ftp.FtpVVolume.java
private void reconnect(final FTPClient ftpc) throws IOException { Print.println(Print.VFS, "Reconnecting ..."); final String user_info = this.root_url.getUserInfo(); final int n = user_info.indexOf(':'); final String user = n >= 0 ? user_info.substring(0, n) : user_info; final String pw = n >= 0 ? user_info.substring(n + 1) : ""; if (Print.wouldPrint(Print.VFS)) { Print.println("User ID : " + user); Print.println("Password: " + pw); Print.println("Host : " + root_url.getHost()); }//from w w w . ja va 2 s . c o m ftpc.connect(this.root_url.getHost()); final boolean ok = ftpc.login(user, pw); if (!ok) { new Alert("Cannot connect to FTP server").culprit("host", root_url.getHost()).mishap(); } if (!ftpc.setFileType(FTP.BINARY_FILE_TYPE)) { new Alert("Cannot set file type").mishap(); } }
From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java
private String uploadSingleFile(FTPClient ftpClient, String localFilePath, String remoteFilePath) throws IOException { File localFile = new File(localFilePath); try (InputStream inputStream = new FileInputStream(localFile)) { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //upload a single file to the FTP server if (ftpClient.storeFile(remoteFilePath, inputStream)) { getOut().println("file UPLOADED successfully to: " + Paths.get(remoteFilePath)); return remoteFilePath; } else {//ww w .j a v a2 s . c o m throw new IOException( "Error: COULD NOT upload the file: " + localFilePath + " to " + remoteFilePath); } } }
From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java
private String downloadSingleFile(FTPClient ftpClient, String remoteFilePath, String savePath) throws IOException { getOut().println("About to DOWNLOAD the file: " + remoteFilePath); File downloadFile = new File(savePath); File parentDir = downloadFile.getParentFile(); if (parentDir != null && !parentDir.exists()) { parentDir.mkdirs();//from www. ja va2 s.c o m } try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile))) { //retrieve a single file from the FTP server ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (ftpClient.retrieveFile(remoteFilePath, outputStream)) { getOut().println( "DOWNLOADED successfully the file " + remoteFilePath + " to " + ftpLocalRelativePath); return savePath; } else { throw new IOException("Error: COULD NOT download the file: " + ftpRemoteRelativePath); } } }
From source file:org.pepstock.jem.node.resources.impl.ftp.FtpFactory.java
/** * Creates and configures a FtpClient instance based on the * given properties.//from ww w .ja va 2s . co m * * @param properties the ftp client configuration properties * @return remote input/output steam * @throws JNDIException if an error occurs creating the ftp client */ private Object createFtpClient(Properties properties) throws JNDIException { // URL is mandatory String ftpUrlString = properties.getProperty(CommonKeys.URL); if (ftpUrlString == null) { throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.URL); } // creates URL objects // from URL string URL ftpUrl; try { ftpUrl = new URL(ftpUrlString); } catch (MalformedURLException e) { throw new JNDIException(NodeMessage.JEMC233E, e, ftpUrlString); } // checks scheme // if SSL, activates a FTPS if (!ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL) && !ftpUrl.getProtocol().equalsIgnoreCase(FTPS_PROTOCOL)) { throw new JNDIException(NodeMessage.JEMC137E, ftpUrl.getProtocol()); } // gets port the host (from URL) int port = ftpUrl.getPort(); String server = ftpUrl.getHost(); // User id is mandatory String username = properties.getProperty(CommonKeys.USERID); if (username == null) { throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.USERID); } // password is mandatory String password = properties.getProperty(CommonKeys.PASSWORD); if (password == null) { throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.PASSWORD); } // checks if as input stream or not boolean asInputStream = Parser .parseBoolean(properties.getProperty(FtpResourceKeys.AS_INPUT_STREAM, "false"), false); String remoteFile = null; String accessMode = null; if (asInputStream) { // remote file is mandatory // it must be set by a data description remoteFile = properties.getProperty(FtpResourceKeys.REMOTE_FILE); if (remoteFile == null) { throw new JNDIException(NodeMessage.JEMC136E, FtpResourceKeys.REMOTE_FILE); } // access mode is mandatory // it must be set by a data description accessMode = properties.getProperty(FtpResourceKeys.ACTION_MODE, FtpResourceKeys.ACTION_READ); } // creates a FTPclient FTPClient ftp = ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL) ? new FTPClient() : new FTPSClient(); // checks if binary boolean binaryTransfer = Parser.parseBoolean(properties.getProperty(FtpResourceKeys.BINARY, "false"), false); // checks if must be restarted long restartOffset = Parser.parseLong(properties.getProperty(FtpResourceKeys.RESTART_OFFSET, "-1"), -1); // checks and sets buffer size int bufferSize = Parser.parseInt(properties.getProperty(FtpResourceKeys.BUFFER_SIZE, "-1"), -1); try { // reply code instance int reply; // connect to server if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } // After connection attempt, you should check the reply code to // verify // success. reply = ftp.getReplyCode(); // if not connected for error, EXCEPTION if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new JNDIException(NodeMessage.JEMC138E, reply); } // login!! if (!ftp.login(username, password)) { ftp.logout(); } // set all ftp properties if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } // sets restart offset if has been set if (restartOffset >= 0) { ftp.setRestartOffset(restartOffset); } // sets buffer size if (bufferSize >= 0) { ftp.setBufferSize(bufferSize); } // if is not related to a data descritpion, // returns a FTP object if (!asInputStream) { return new Ftp(ftp); } // checks if is in WRITE mode if (accessMode.equalsIgnoreCase(FtpResourceKeys.ACTION_WRITE)) { // gets outputstream // using the file name passed by data descritpion OutputStream os = ftp.storeFileStream(remoteFile); if (os == null) { reply = ftp.getReplyCode(); throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply); } // returns outputstream return new FtpOutputStream(os, ftp); } else { // gest inputstream // using the file name passed by data descritpion InputStream is = ftp.retrieveFileStream(remoteFile); if (is == null) { reply = ftp.getReplyCode(); throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply); } // returns inputstream return new FtpInputStream(is, ftp); } } catch (SocketException e) { throw new JNDIException(NodeMessage.JEMC234E, e); } catch (IOException e) { throw new JNDIException(NodeMessage.JEMC234E, e); } }
From source file:org.ramadda.repository.monitor.FtpAction.java
/** * _more_/* ww w . j av a2 s.c o m*/ * * * @param monitor _more_ * @param entry _more_ */ protected void entryMatched(EntryMonitor monitor, Entry entry) { FTPClient ftpClient = new FTPClient(); try { Resource resource = entry.getResource(); if (!resource.isFile()) { return; } if (server.length() == 0) { return; } String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false); ftpClient.connect(server); if (user.length() > 0) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); monitor.handleError("FTP server refused connection:" + server, null); return; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (directory.length() > 0) { ftpClient.changeWorkingDirectory(directory); } String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate); InputStream is = new BufferedInputStream( monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath()))); boolean ok = ftpClient.storeUniqueFile(filename, is); is.close(); if (ok) { monitor.logInfo("Wrote file:" + directory + " " + filename); } else { monitor.handleError("Failed to write file:" + directory + " " + filename, null); } } catch (Exception exc) { monitor.handleError("Error posting to FTP:" + server, exc); } finally { try { ftpClient.logout(); } catch (Exception exc) { } try { ftpClient.disconnect(); } catch (Exception exc) { } } }
From source file:org.ramadda.repository.type.FtpTypeHandler.java
/** * _more_/* ww w. j a v a 2 s. c o m*/ * * @param server _more_ * @param baseDir _more_ * @param user _more_ * @param password _more_ * * @return _more_ * * @throws Exception _more_ */ public static String test(String server, String baseDir, String user, String password) throws Exception { FTPClient ftpClient = new FTPClient(); try { String file = baseDir; ftpClient.connect(server); //System.out.print(ftp.getReplyString()); ftpClient.login(user, password); // System.out.print(ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); boolean isDir = isDir(ftpClient, file); // System.err.println("file:" + file + " is dir: " + isDir); if (isDir) { FTPFile[] files = ftpClient.listFiles(file); for (int i = 0; i < files.length; i++) { // System.err.println ("f:" + files[i].getName() + " " + files[i].isDirectory() + " " + files[i].isFile()); } } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ftpClient.retrieveFile(file, bos)) { // System.err.println(new String(bos.toByteArray())); } else { throw new IOException("Unable to retrieve file:" + file); } } return ""; } finally { closeConnection(ftpClient); } }