List of usage examples for org.apache.commons.net.ftp FTPClient setFileType
public boolean setFileType(int fileType) throws IOException
From source file:com.rvl.android.getnzb.LocalNZB.java
public void uploadLocalFileFTP(String filename) { UPLOADFILENAME = filename;/* www . j a v a 2s . co m*/ UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server."); SharedPreferences prefs = GetNZB.preferences; if (prefs.getString("FTPHostname", "") == "") { uploadDialogHandler.sendEmptyMessage(0); Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.", Toast.LENGTH_LONG).show(); return; } new Thread() { public void run() { SharedPreferences prefs = GetNZB.preferences; FTPClient ftp = new FTPClient(); String replycode = ""; String FTPHostname = prefs.getString("FTPHostname", ""); String FTPUsername = prefs.getString("FTPUsername", "anonymous"); String FTPPassword = prefs.getString("FTPPassword", "my@email.address"); String FTPPort = prefs.getString("FTPPort", "21"); String FTPUploadPath = prefs.getString("FTPUploadPath", "~/"); if (!FTPUploadPath.matches("$/")) { Log.d(Tags.LOG, "Adding trailing slash"); FTPUploadPath += "/"; } String targetFile = FTPUploadPath + UPLOADFILENAME; try { ftp.connect(FTPHostname, Integer.parseInt(FTPPort)); if (ftp.login(FTPUsername, FTPPassword)) { ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); File file = new File(getFilesDir() + "/" + UPLOADFILENAME); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file)); Log.d(Tags.LOG, "Saving file to:" + targetFile); if (ftp.storeFile(targetFile, buffIn)) { Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: " + Integer.toString(ftp.getReplyCode())); isUploadedFTP = true; } else { Log.d(Tags.LOG, "FTP: Could not upload file Replycode: " + Integer.toString(ftp.getReplyCode())); FTPErrorCode = Integer.toString(ftp.getReplyCode()); isUploadedFTP = false; } buffIn.close(); ftp.logout(); ftp.disconnect(); } else { Log.d(Tags.LOG, "No ftp login"); } } catch (SocketException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } catch (IOException e) { Log.d(Tags.LOG, "ftp(): " + e.getMessage()); return; } if (isUploadedFTP) { removeLocalNZBFile(UPLOADFILENAME); } UPLOADFILENAME = ""; uploadDialogHandlerFTP.sendEmptyMessage(0); } }.start(); }
From source file:lucee.runtime.tag.Ftp.java
/** * gets a file from server and copy it local * @return FTPCLient/*from w w w.ja va 2s.co m*/ * @throws PageException * @throws IOException */ private FTPClient actionGetFile() throws PageException, IOException { required("remotefile", remotefile); required("localfile", localfile); FTPClient client = getClient(); Resource local = ResourceUtil.toResourceExistingParent(pageContext, localfile);//new File(localfile); pageContext.getConfig().getSecurityManager().checkFileLocation(local); if (failifexists && local.exists()) throw new ApplicationException("File [" + local + "] already exist, if you want to overwrite, set attribute failIfExists to false"); OutputStream fos = null; client.setFileType(getType(local)); try { fos = IOUtil.toBufferedOutputStream(local.getOutputStream()); client.retrieveFile(remotefile, fos); } finally { IOUtil.closeEL(fos); } writeCfftp(client); return client; }
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 ww. j av a 2 s. co 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 Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;// w w w. j a va2 s.c om try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(SourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); Report = "Server Error"; jLabel6.setText(Report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.hackengine_er.muslumyusuf.DBOperations.java
private boolean uploadToFTP(String username, String fileName, InputStream inputStream) { FTPClient client = new FTPClient(); try {/*from w ww .j a v a2s. co m*/ client.connect(Configuration.FTPClient()); if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) { client.setDefaultTimeout(10000); client.setFileType(FTPClient.BINARY_FILE_TYPE); if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) { return true; } } } catch (IOException e) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e); } finally { if (client.isConnected()) { try { client.logout(); client.disconnect(); } catch (IOException ex) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex); } } } return false; }
From source file:com.muslumyusuf.DBOperations.java
private boolean uploadToFTP(String username, String fileName, InputStream inputStream) { FTPClient client = new FTPClient(); try {//from ww w. j av a2 s .c o m client.connect(Initialize.FTPClient()); if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) { client.setDefaultTimeout(10000); client.setFileType(FTPClient.BINARY_FILE_TYPE); if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) { return true; } } } catch (IOException e) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e); } finally { if (client.isConnected()) { try { client.logout(); client.disconnect(); } catch (IOException ex) { Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex); } } } return false; }
From source file:convcao.com.agent.ConvcaoNeptusInteraction.java
private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName, String password, String filename) { FTPClient client = new FTPClient(); FileInputStream fis = null;/*from w w w . ja va2s. c o m*/ try { client.connect(ftpServer); client.login(userName, password); client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); fis = new FileInputStream(sourcePathDirectory + filename); client.changeWorkingDirectory("/" + pathDirectory); client.storeFile(filename, fis); System.out.println( "The file " + sourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename); client.logout(); //Report = "File: " + filename + " Uploaded Successfully "; } catch (Exception exp) { exp.printStackTrace(); report = "Server Error"; jLabel6.setText(report); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.cladonia.xngreditor.URLUtilities.java
public static void save(URL url, InputStream input, String encoding) throws IOException { // System.out.println( "URLUtilities.save( "+url+", "+encoding+")"); String password = URLUtilities.getPassword(url); String username = URLUtilities.getUsername(url); String protocol = url.getProtocol(); if (protocol.equals("ftp")) { FTPClient client = null; String host = url.getHost(); client = new FTPClient(); // System.out.println( "Connecting ..."); client.connect(host);/*from w w w. j av a 2 s . com*/ // System.out.println( "Connected."); // After connection attempt, you should check the reply code to verify // success. int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { // System.out.println( "Disconnecting..."); client.disconnect(); throw new IOException("FTP Server \"" + host + "\" refused connection."); } // System.out.println( "Logging in ..."); if (!client.login(username, password)) { // System.out.println( "Could not log in."); // TODO bring up login dialog? client.disconnect(); throw new IOException("Could not login to FTP Server \"" + host + "\"."); } // System.out.println( "Logged in."); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); // System.out.println( "Writing output ..."); OutputStream output = client.storeFileStream(url.getFile()); // if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) { // output.close(); // client.disconnect(); // throw new IOException( "Could not transfer file \""+url.getFile()+"\"."); // } InputStreamReader reader = new InputStreamReader(input, encoding); OutputStreamWriter writer = new OutputStreamWriter(output, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); output.close(); // Must call completePendingCommand() to finish command. if (!client.completePendingCommand()) { client.disconnect(); throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } else { client.disconnect(); } } else if (protocol.equals("http") || protocol.equals("https")) { WebdavResource webdav = createWebdavResource(toString(url), username, password); if (webdav != null) { webdav.putMethod(url.getPath(), input); webdav.close(); } else { throw new IOException("Could not transfer file \"" + url.getFile() + "\"."); } } else if (protocol.equals("file")) { FileOutputStream stream = new FileOutputStream(toFile(url)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding)); InputStreamReader reader = new InputStreamReader(input, encoding); int ch = reader.read(); while (ch != -1) { writer.write(ch); ch = reader.read(); } writer.flush(); writer.close(); } else { throw new IOException("The \"" + protocol + "\" protocol is not supported."); } }
From source file:fr.bmartel.speedtest.SpeedTestTask.java
/** * start FTP download with specific port, user, password. * * @param hostname ftp host/*from w ww. j av a 2s . c o m*/ * @param uri ftp uri * @param user ftp username * @param password ftp password */ public void startFtpDownload(final String hostname, final int port, final String uri, final String user, final String password) { mSpeedTestMode = SpeedTestMode.DOWNLOAD; mErrorDispatched = false; mForceCloseSocket = false; if (mReadExecutorService == null || mReadExecutorService.isShutdown()) { mReadExecutorService = Executors.newSingleThreadExecutor(); } mReadExecutorService.execute(new Runnable() { @Override public void run() { final FTPClient ftpclient = new FTPClient(); try { ftpclient.connect(hostname, port); ftpclient.login(user, password); ftpclient.enterLocalPassiveMode(); ftpclient.setFileType(FTP.BINARY_FILE_TYPE); mDownloadTemporaryPacketSize = 0; mTimeStart = System.currentTimeMillis(); mTimeEnd = 0; if (mRepeatWrapper.isFirstDownload()) { mRepeatWrapper.setFirstDownloadRepeat(false); mRepeatWrapper.setStartDate(mTimeStart); } mDownloadPckSize = new BigDecimal(getFileSize(ftpclient, uri)); if (mRepeatWrapper.isRepeatDownload()) { mRepeatWrapper.updatePacketSize(mDownloadPckSize); } mFtpInputstream = ftpclient.retrieveFileStream(uri); if (mFtpInputstream != null) { final byte[] bytesArray = new byte[SpeedTestConst.READ_BUFFER_SIZE]; int read; while ((read = mFtpInputstream.read(bytesArray)) != -1) { mDownloadTemporaryPacketSize += read; if (mRepeatWrapper.isRepeatDownload()) { mRepeatWrapper.updateTempPacketSize(read); } if (!mReportInterval) { final SpeedTestReport report = mSocketInterface.getLiveDownloadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onDownloadProgress(report.getProgressPercent(), report); } } if (mDownloadTemporaryPacketSize == mDownloadPckSize.longValueExact()) { break; } } mFtpInputstream.close(); mTimeEnd = System.currentTimeMillis(); mReportInterval = false; final SpeedTestReport report = mSocketInterface.getLiveDownloadReport(); for (int i = 0; i < mListenerList.size(); i++) { mListenerList.get(i).onDownloadFinished(report); } } else { mReportInterval = false; SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, "cant create stream " + "from uri " + uri + " with reply code : " + ftpclient.getReplyCode()); } if (!mRepeatWrapper.isRepeatDownload()) { closeExecutors(); } } catch (IOException e) { //e.printStackTrace(); mReportInterval = false; catchError(true, e.getMessage()); } finally { mErrorDispatched = false; mSpeedTestMode = SpeedTestMode.NONE; disconnectFtp(ftpclient); } } }); }
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 a2s . 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; } }