List of usage examples for org.apache.commons.net.ftp FTPClient storeFile
public boolean storeFile(String remote, InputStream local) throws IOException
From source file:eu.ggnet.dwoss.misc.op.listings.FtpTransfer.java
/** * Uploads a some files to a remove ftp host. * <p/>/* w w w. j a va2 s. com*/ * @param config the config for he connection. * @param uploads the upload commands * @param monitor an optional monitor. * @throws java.net.SocketException * @throws java.io.IOException */ public static void upload(ConnectionConfig config, IMonitor monitor, UploadCommand... uploads) throws SocketException, IOException { if (uploads == null || uploads.length == 0) return; SubMonitor m = SubMonitor.convert(monitor, "FTP Transfer", toWorkSize(uploads) + 4); m.message("verbinde"); m.start(); FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(PROTOCOL_TO_LOGGER); try { ftp.connect(config.getHost(), config.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) throw new IOException("FTPReply.isPositiveCompletion(ftp.getReplyCode()) = false"); if (!ftp.login(config.getUser(), config.getPass())) throw new IOException("Login with " + config.getUser() + " not successful"); L.info("Connected to {} idenfied by {}", config.getHost(), ftp.getSystemType()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); for (UploadCommand upload : uploads) { m.worked(1, "uploading to " + upload.getPath()); ftp.changeWorkingDirectory(upload.getPath()); deleteFilesByType(ftp, upload.getDeleteFileTypes()); for (File file : upload.getFiles()) { m.worked(1, "uploading to " + upload.getPath() + " file " + file.getName()); try (InputStream input = new FileInputStream(file)) { if (!ftp.storeFile(file.getName(), input)) throw new IOException("Cannot store file " + file + " on server!"); } } } m.finish(); } finally { // just cleaning up try { ftp.logout(); } catch (IOException e) { } if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } } }
From source file:beans.BL.java
/** * Upload FTP Server/*www. j a va 2s.c o m*/ * * @param filename * @throws IOException */ public void upload(String filename) throws IOException { FTPClient client = new FTPClient(); FileInputStream fis = null; client.connect("ftp.sunlime.at", 990); client.login("admin", "secret"); fis = new FileInputStream(filename); client.storeFile(filename, fis); client.logout(); fis.close(); }
From source file:com.starr.smartbuilds.service.FileService.java
public String getFile(Build build, ServletContext sc) throws FileNotFoundException, IOException, ParseException { /*if (fileName == null || fileName.equals("") || fileText == null || fileText.equals("")) { resultMsg = "<font color='red'>Fail: File is not created!</font>"; } else {//from www . j ava 2 s.co m try {*/ String path = sc.getRealPath("/"); System.out.println(path); File dir = new File(path + "/builds"); if (!dir.exists() || !dir.isDirectory()) { dir.mkdir(); } String fileName = path + "/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json"; File fileBuild = new File(fileName); if (!fileBuild.exists() || fileBuild.isDirectory()) { String file_data = buildService.buildData(build, buildService.parseBlocks(build.getBlocks())); fileBuild.createNewFile(); FileOutputStream fos = new FileOutputStream(fileBuild, false); fos.write(file_data.getBytes()); fos.close(); } FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("itelit.ftp.ukraine.com.ua"); client.login("itelit_dor", "154896"); // Create an InputStream of the file to be uploaded fis = new FileInputStream(fileBuild.getAbsolutePath()); // Store file to server client.storeFile("builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json", fis); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } /*} catch (IOException ex) { resultMsg = "<font color='red'>Fail: File is not created!</font>"; } }*/ return "http://dor.it-elit.org/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json"; }
From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java
@Nullable private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite, @NonNls final String directory, final ProgressIndicator indicator) { FTPClient ftp = new FTPClient(); ftp.setConnectTimeout(30 * 1000);// www . ja va 2 s.c om try { indicator.setText("Connecting to server..."); ftp.connect(ftpSite); indicator.setText("Connected to server"); if (!ftp.login("anonymous", "anonymous@jetbrains.com")) { return "Failed to login"; } indicator.setText("Logged in"); // After connection attempt, you should check the reply code to verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return "FTP server refused connection: " + reply; } if (!ftp.changeWorkingDirectory(directory)) { return "Failed to change directory"; } // else won't work behind FW ftp.enterLocalPassiveMode(); if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) { return "Failed to switch to binary mode"; } indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")"); FileInputStream readStream = new FileInputStream(reportPath); try { if (!ftp.storeFile(reportPath.getName(), readStream)) { return "Failed to upload file"; } } catch (IOException e) { return "Error during transfer: " + e.getMessage(); } finally { readStream.close(); } ftp.logout(); return null; } catch (IOException e) { return "Failed to upload: " + e.getMessage(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } }
From source file:com.webarch.common.net.ftp.FtpService.java
/** * //from w w w. jav a 2 s . c o m * * @param fileName ?? * @param path ftp? * @param fileStream ? * @return true/false ? */ public boolean uploadFile(String fileName, String path, InputStream fileStream) { boolean success = false; FTPClient ftpClient = new FTPClient(); try { int replyCode; ftpClient.connect(url, port); ftpClient.login(userName, password); replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { return false; } ftpClient.changeWorkingDirectory(path); ftpClient.storeFile(fileName, fileStream); fileStream.close(); ftpClient.logout(); success = true; } catch (IOException e) { logger.error("ftp?", e); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { logger.error("ftp?", e); } } } return success; }
From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java
/** * Creates a mock FTPClient that throws a SocketException * on connect()./*w w w. ja v a2 s .co m*/ * * @return Returns an FtpSession object. * @throws IOException */ FTPClient socketExMockFtpClient() throws IOException { FTPClient client = mock(FTPClient.class); when(client.login(anyString(), anyString())).thenReturn(true); when(client.getReplyCode()).thenReturn(250); when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(true); when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(true); when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$ doThrow(SocketException.class).when(client).connect("ftp.host.com", 21); //$NON-NLS-1$ return client; }
From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java
/** * Creates a mock FTPClient that does not need an FTP server. * /*from w ww .j a va 2 s . c o m*/ * @param succeedOnLogin * Specifies if this FTP client mocks its login method by * imitating a successful or a failed login. * @param succedOnUploadDownload * Specifies if this FTP client mocks the upload and download * operations by imitating successful or failed operations. * * @return Returns an FtpSession object. * @throws IOException */ FTPClient mockFtpClient(boolean succeedOnLogin, boolean succedOnUploadDownload) throws IOException { FTPClient client = mock(FTPClient.class); when(client.login(anyString(), anyString())).thenReturn(succeedOnLogin); when(client.getReplyCode()).thenReturn(250); when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(succedOnUploadDownload); when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(succedOnUploadDownload); when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$ return client; }
From source file:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class); RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response); // prepare dynamic variables Part masterQualityPart = request.getPart("masterFile"); String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf"; // prepare static variables String host = "p4.eurixgroup.com"; int port = 21; String username = "pprime"; String password = "pprime09"; FTPClient client = new FTPClient(); try {// www . j a v a 2 s. c o m client.connect(host, port); if (FTPReply.isPositiveCompletion(client.getReplyCode())) { if (client.login(username, password)) { client.setFileType(FTP.BINARY_FILE_TYPE); // TODO add behavior if file name is already present in // remote ftp folder // now OVERWRITES if (client.storeFile(targetName, masterQualityPart.getInputStream())) { logger.info("Stored file on remote FTP server " + host + ":" + port); request.setAttribute("masterfileName", targetName); } else { logger.error("Unable to store file on remote FTP server"); } } else { logger.error("Unable to login on remote FTP server"); } } else { logger.error("Unable to connect to remote FTP server"); } } catch (IOException e) { e.printStackTrace(); logger.fatal("General exception with FTPClient"); } Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp"); }
From source file:com.jmeter.alfresco.utils.FtpUtils.java
/** * Upload file.//from w w w . j a v a2s . com * * @param ftpClient the ftp client * @param frmLocalFilePath the frm local file path * @param toRemoteFilePath the to remote file path * @return true, if successful * @throws IOException Signals that an I/O exception has occurred. */ private boolean uploadFile(final FTPClient ftpClient, final String frmLocalFilePath, final String toRemoteFilePath) throws IOException { final File localFile = new File(frmLocalFilePath); final InputStream inputStream = new FileInputStream(localFile); try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final boolean isFileUploaded = ftpClient.storeFile(toRemoteFilePath, inputStream); final int replyCode = ftpClient.getReplyCode(); //If reply code is 550 then,Requested action not taken. File unavailable (e.g., file not found, no access). //If reply code is 150 then,File status okay (e.g., File found) //If reply code is 226 then,Closing data connection. //If reply code is 426 then,Connection closed; transfer aborted. LOG.debug("Reply code from remote host after storeFile(..) call: " + replyCode); return isFileUploaded; } finally { inputStream.close(); } }
From source file:jsfml1.NewJFrame.java
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed try {//from www. ja v a2s . c o m // TODO add your handling code here: File f = new File(date + ".html"); FileWriter fw = new FileWriter(f); fw.write("<!--" + date + " " + ose + " " + username + " is good ! -->"); fw.write("<head>"); fw.write("<style>"); fw.write("body {"); fw.write("background: #121212;"); fw.write("color: white;"); fw.write("text-align: center;"); fw.write("}"); fw.write("</style>"); fw.write("<title>Listening on</title>"); fw.write("</head>"); fw.write("<body>"); fw.write("Listening on: <br/><br/>"); fw.write("<audio controls=\"controls\"> <source src=\"" + date + ".wav\"> </audio>"); fw.write("</body>"); fw.close(); JOptionPane jop = new JOptionPane(); jButton4.setText("Uploaded fine !"); FTPClient ftp = new FTPClient(); ftp.connect("ftp.cluster1.easy-hebergement.net", 21); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.user("toNSite"); ftp.pass("tonMotDePasse"); InputStream is0 = new FileInputStream(date + ".html"); InputStream is = new FileInputStream(date + ".wav"); ftp.storeFile("/uploads/" + date + ".html", is0); ftp.storeFile("/uploads/" + date + ".wav", is); is.close(); Desktop.getDesktop().browse(new URI("http://focaliser.fr/uploads/" + date + ".html")); } catch (MalformedURLException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } }