List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE
int BINARY_FILE_TYPE
To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.
Click Source Link
From source file:net.sf.ufsc.ftp.FtpFile.java
/** * @see net.sf.ufsc.File#getInputStream() *//*from w w w . j ava2 s . co m*/ public InputStream getInputStream() throws IOException { return this.getInputStream(FTP.BINARY_FILE_TYPE); }
From source file:be.thomasmore.controller.FileController.java
public String uploadFile() throws IOException { String server = "logic.sinners.be"; int port = 21; String user = "logic_java"; String pass = "scoretracker"; FTPClient ftpClient = new FTPClient(); try {// w ww . j a va 2s . c o m ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String firstRemoteFile = getFileName(part); InputStream inputStream = part.getInputStream(); System.out.println("Bestand uploaden"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { System.out.println("Het bestand is succesvol upgeload."); statusMessage = "De gegevens werden succesvol ingeladen."; } } catch (IOException ex) { System.out.println("Fout: " + ex.getMessage()); statusMessage = "Er is een fout opgetreden: " + ex.getMessage(); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } /* //De bestandsnaam uit het bestand (part) halen String fileName = getFileName(part); System.out.println("***** fileName: " + fileName); String basePath = "C:" + File.separator + "data" + File.separator; File outputFilePath = new File(basePath + fileName); //Streams aanmaken om het upgeloade bestand naar de destination te kopiren InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = part.getInputStream(); outputStream = new FileOutputStream(outputFilePath); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } statusMessage = "De gegevens werden succesvol ingeladen."; } catch (IOException e) { e.printStackTrace(); statusMessage = "Er is een fout opgetreden."; } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } }*/ leesExcel(); return null; }
From source file:demo.FTP.FTPClientExample.java
public static void main(String[] args) throws UnknownHostException { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;// w w w .j a v a 2 s. c o m boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false; boolean lenient = false; long keepAliveTimeout = -1; int controlKeepAliveReplyTimeout = -1; int minParams = 5; // listings require 3 params String protocol = null; // SSL protocol String doCommand = null; String trustmgr = null; String proxyHost = null; int proxyPort = 80; String proxyUser = null; String proxyPassword = null; String username = null; String password = null; String encoding = null; String serverTimeZoneId = null; String displayTimeZoneId = null; String serverType = null; String defaultDateFormat = null; String recentDateFormat = null; int base = 0; for (base = 0; base < args.length; base++) { if (args[base].equals("-s")) { storeFile = true; } else if (args[base].equals("-a")) { localActive = true; } else if (args[base].equals("-A")) { username = "anonymous"; password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName(); } else if (args[base].equals("-b")) { binaryTransfer = true; } else if (args[base].equals("-c")) { doCommand = args[++base]; minParams = 3; } else if (args[base].equals("-d")) { mlsd = true; minParams = 3; } else if (args[base].equals("-e")) { useEpsvWithIPv4 = true; } else if (args[base].equals("-E")) { encoding = args[++base]; } else if (args[base].equals("-f")) { feat = true; minParams = 3; } else if (args[base].equals("-h")) { hidden = true; } else if (args[base].equals("-k")) { keepAliveTimeout = Long.parseLong(args[++base]); } else if (args[base].equals("-l")) { listFiles = true; minParams = 3; } else if (args[base].equals("-m")) { mdtm = true; minParams = 3; } else if (args[base].equals("-L")) { lenient = true; } else if (args[base].equals("-n")) { listNames = true; minParams = 3; } else if (args[base].equals("-p")) { protocol = args[++base]; System.out.println("protocal:" + protocol); } else if (args[base].equals("-S")) { serverType = args[++base]; } else if (args[base].equals("-t")) { mlst = true; minParams = 3; } else if (args[base].equals("-U")) { saveUnparseable = true; } else if (args[base].equals("-w")) { controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]); } else if (args[base].equals("-T")) { trustmgr = args[++base]; } else if (args[base].equals("-y")) { defaultDateFormat = args[++base]; } else if (args[base].equals("-Y")) { recentDateFormat = args[++base]; } else if (args[base].equals("-Z")) { serverTimeZoneId = args[++base]; } else if (args[base].equals("-z")) { displayTimeZoneId = args[++base]; } else if (args[base].equals("-PrH")) { proxyHost = args[++base]; String parts[] = proxyHost.split(":"); if (parts.length == 2) { proxyHost = parts[0]; proxyPort = Integer.parseInt(parts[1]); } } else if (args[base].equals("-PrU")) { proxyUser = args[++base]; } else if (args[base].equals("-PrP")) { proxyPassword = args[++base]; } else if (args[base].equals("-#")) { printHash = true; } else { break; } } int remain = args.length - base; if (username != null) { minParams -= 2; } if (remain < minParams) // server, user, pass, remote, local [protocol] { if (args.length > 0) { System.err.println("Actual Parameters: " + Arrays.toString(args)); } System.err.println(USAGE); System.exit(1); } String server = args[base++]; int port = 0; String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); System.out.println("server:" + server); System.out.println("port:" + port); } if (username == null) { username = args[base++]; password = args[base++]; System.out.println("username:" + username); System.out.println("password:" + password); } String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } final FTPClient ftp; if (protocol == null) { if (proxyHost != null) { System.out.println("Using HTTP proxy server: " + proxyHost); ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword); } else { ftp = new FTPClient(); } } else { FTPSClient ftps; if (protocol.equals("true")) { ftps = new FTPSClient(true); } else if (protocol.equals("false")) { ftps = new FTPSClient(false); } else { String prot[] = protocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } ftp = ftps; if ("all".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { ftps.setTrustManager(null); } } if (printHash) { ftp.setCopyStreamListener(createListener()); } if (keepAliveTimeout >= 0) { ftp.setControlKeepAliveTimeout(keepAliveTimeout); } if (controlKeepAliveReplyTimeout >= 0) { ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } if (encoding != null) { ftp.setControlEncoding(encoding); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); final FTPClientConfig config; if (serverType != null) { config = new FTPClientConfig(serverType); } else { config = new FTPClientConfig(); } config.setUnparseableEntries(saveUnparseable); if (defaultDateFormat != null) { config.setDefaultDateFormatStr(defaultDateFormat); } if (recentDateFormat != null) { config.setRecentDateFormatStr(recentDateFormat); } ftp.configure(config); try { int reply; if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should default to ASCII // but they don't all do so - see NET-500 ftp.setFileType(FTP.ASCII_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (localActive) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4(useEpsvWithIPv4); if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } // Allow multiple list types for single invocation else if (listFiles || mlsd || mdtm || mlst || listNames) { if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } } if (mdtm) { FTPFile f = ftp.mdtmFile(remote); System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString(displayTimeZoneId)); } } if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } // Do this last because it changes the client if (listFiles) { if (lenient || serverTimeZoneId != null) { config.setLenientFutureDates(lenient); if (serverTimeZoneId != null) { config.setServerTimeZoneId(serverTimeZoneId); } ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString(displayTimeZoneId)); } } } else if (feat) { // boolean feature check if (remote != null) { // See if the command is present if (ftp.hasFeature(remote)) { System.out.println("Has feature: " + remote); } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " was not detected"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } // Strings feature check String[] features = ftp.featureValues(remote); if (features != null) { for (String f : features) { System.out.println("FEAT " + remote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " is not present"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } } else { if (ftp.features()) { // Command listener has already printed the output } else { System.out.println("Failed: " + ftp.getReplyString()); } } } else if (doCommand != null) { if (ftp.doCommand(doCommand, remote)) { // Command listener has already printed the output // for(String s : ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:de.awtools.basic.io.FTPWrapper.java
/** * Binr Modus ein./*from ww w. j a v a 2s . c om*/ * * @return true, alles in Ordnung; false, sonst. * @throws IOException Da ging was schief. */ public boolean binary() throws IOException { return ftpClient.setFileType(FTP.BINARY_FILE_TYPE); }
From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java
/** * Retrieve the FTP client belonging to the given URI. * //from w w w. j av a 2s . c o m * @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:fr.lille1.car.burihabwa.rest.utils.FTPAdapterImpl.java
@Override public File retr(final String path) throws IOException { if (!authenticate()) { throw new IOException("Wrong username and password!"); }//from ww w . ja v a 2 s . com if (path == null || path.isEmpty()) { throw new IOException("A path to the file must be given!"); } String[] tokens = path.split("/"); String filename = tokens[tokens.length - 1]; File file = new File(filename); file.createNewFile(); file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); this.client.setBufferSize(4096); this.client.setFileType(FTP.BINARY_FILE_TYPE); boolean retr = this.client.retrieveFile(path, fos); if (!retr) { fos.close(); file.delete(); } fos.close(); this.client.logout(); this.client.disconnect(); return file; }
From source file:com.knowbout.epg.processor.Downloader.java
private void connect() throws IOException { client.connect(server);//from www .j a v a 2 s . c o m boolean loggedIn = client.login(username, password); client.enterLocalPassiveMode(); log.debug("Able to log into " + server + "? " + loggedIn); client.setFileType(FTP.BINARY_FILE_TYPE); client.changeWorkingDirectory(remoteWorkingDirectory); client.setReaderThread(false); log.debug("Working directory: " + client.printWorkingDirectory()); }
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;//from w w w. j a v a2 s . c o m if (enableSSL()) { FTPSClient ftps = new FTPSClient(isImplicit()); ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); ftp = ftps; } 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:it.baywaylabs.jumpersumo.utility.FTPDownloadImage.java
/** * Background thread that download photo from the robot and prepare it for local processing or for Twitter reply.<br /> * This method is called when invoke <b>execute()</b>.<br /> * Do not invoke manually. Use: <i>new FTPDownloadImage().execute("");</i> * * @param params The parameters of the task. They can be <b>"local"</b> or <b>"twitter"</b>. * @return Null if everything was going ok. * @see #onPreExecute()//from w ww . j av a 2s . c om * @see #onPostExecute * @see #publishProgress */ @Override protected String doInBackground(String... params) { String resultFileName = ""; 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, pass); 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(); } if (params.length != 0 && !"".equals(nameFile)) if ("local".equals(params[0])) { 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) { resultFileName = nameFile; ContentResolver contentResolver = context.getContentResolver(); Bitmap bitmap = BitmapFactory.decodeFile(folder.getAbsolutePath() + "/" + nameFile); Log.e(TAG, "FileName: " + folder.getAbsolutePath() + "/" + nameFile); MediaStore.Images.Media.insertImage(contentResolver, bitmap, nameFile, "Jumper Sumo Photo"); mFTPClient.deleteFile(nameFile); File[] list = folder.listFiles(); for (int i = 0; i < list.length; i++) { if (nameFile.equals(list[i].getName())) list[i].delete(); } } } else if ("twitter".equals(params[0])) { 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) { resultFileName = nameFile; mFTPClient.deleteFile(nameFile); } } } } catch (Exception e) { return e.getMessage(); } finally { if (mFTPClient != null) { try { mFTPClient.logout(); mFTPClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } if (!"".equals(resultFileName)) return resultFileName; return null; }
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 va2s . c o m // 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; } }