List of usage examples for org.apache.commons.fileupload.util Streams asString
public static String asString(InputStream pStream) throws IOException
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a new file upload handler if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w .j ava 2s . com*/ // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println( "Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out .println("File field " + name + " with file name " + item.getName() + " detected."); DataSource source = createDataSource(item); SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source); } JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(); jsonResponse.put("success", true); jsonResponse.put("error", "Upload successful"); } catch (Exception e) { } Writer w = new OutputStreamWriter(response.getOutputStream()); w.write(jsonResponse.toString()); w.close(); stream.close(); } } catch (Exception ex) { ex.printStackTrace(); } } response.setStatus(HttpServletResponse.SC_OK); }
From source file:com.runwaysdk.web.WebFileUploadServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST); // capture the session id boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); }// w ww.j a va 2 s.co m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); String fileName = null; String extension = null; InputStream stream = null; String uploadPath = null; while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream input = item.openStream(); if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) { uploadPath = Streams.asString(input); } else if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); fileName = fullName.substring(0, extensionInd); extension = fullName.substring(extensionInd + 1); stream = input; } } if (stream != null) { clientRequest.newFile(uploadPath, fileName, extension, stream); } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } }
From source file:edu.isi.wings.portal.servlets.HandleUpload.java
/** * Handle an HTTP POST request from Plupload. *//* www . ja va2 s . co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Config config = new Config(request); if (!config.checkDomain(request, response)) return; Domain dom = config.getDomain(); String name = null; String id = null; String storageDir = dom.getDomainDirectory() + "/"; int chunk = 0; int chunks = 0; boolean isComponent = false; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try { InputStream input = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); String value = Streams.asString(input); if ("name".equals(fieldName)) name = value.replaceAll("[^\\w\\.\\-_]+", "_"); else if ("id".equals(fieldName)) id = value; else if ("type".equals(fieldName)) { if ("data".equals(value)) storageDir += dom.getDataLibrary().getStorageDirectory(); else if ("component".equals(value)) { storageDir += dom.getConcreteComponentLibrary().getStorageDirectory(); isComponent = true; } else { storageDir = System.getProperty("java.io.tmpdir"); } } else if ("chunk".equals(fieldName)) chunk = Integer.parseInt(value); else if ("chunks".equals(fieldName)) chunks = Integer.parseInt(value); } else if (name != null) { File storageDirFile = new File(storageDir); if (!storageDirFile.exists()) storageDirFile.mkdirs(); File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part"); saveUploadFile(input, uploadFile, chunk); } } catch (Exception e) { this.printError(out, e.getMessage()); e.printStackTrace(); } } } catch (FileUploadException e1) { this.printError(out, e1.getMessage()); e1.printStackTrace(); } } else { this.printError(out, "Not multipart data"); } if (chunks == 0 || chunk == chunks - 1) { // Done upload File partUpload = new File(storageDir + File.separator + name + ".part"); File finalUpload = new File(storageDir + File.separator + name); partUpload.renameTo(finalUpload); String mime = new Tika().detect(finalUpload); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload)); // Check if this is a zip file and unzip if needed String location = finalUpload.getAbsolutePath(); if (isComponent && mime.equals("application/zip")) { String dirname = new URI(id).getFragment(); location = StorageHandler.unzipFile(finalUpload, dirname, storageDir); finalUpload.delete(); } this.printOk(out, location); } }
From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {/* w w w . j a v a 2s . co m*/ MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:controllers.UploadController.java
/** * /*from ww w . j ava 2 s. c om*/ * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * @param context * @return * @throws Exception */ public Result uploadFinish(Context context) throws Exception { // we are using a renderable inner class to stream the input again to // the user Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { try { // make sure the context really is a multipart context... if (context.isMultipart()) { // This is the iterator we can use to iterate over the // contents // of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (contentType != null) { result.contentType(contentType); } else { contentType = mimeTypes.getMimeType(name); } ResponseStreams responseStreams = context.finalizeHeaders(result); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println( "File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream ByteStreams.copy(stream, responseStreams.getOutputStream()); } } } } catch (IOException | FileUploadException exception) { throw new InternalServerErrorException(exception); } } }; return new Result(200).render(renderable); }
From source file:de.fhg.iais.model.aip.util.XmlUtilsTest.java
@Test public void testValidator() throws IOException { final String exampleXml = Streams.asString(getClass().getResourceAsStream("/xml/anAddress.xml")); final URL xsd = getClass().getResource("/xml/address.xsd"); parseAndValidate(exampleXml, xsd);/*from w w w. j av a 2 s .co m*/ }
From source file:com.priocept.jcr.server.UploadServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {//w w w .java 2s .c o m if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); if (log.isDebugEnabled()) log.debug(args); InputStream in = null; try { in = item.openStream(); writeToFile(request.getSession().getId() + "/" + fileName, in, true, request.getSession().getServletContext().getRealPath("/")); } catch (Exception e) { // e.printStackTrace(); log.error("Fail to upload " + fileName); response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadFailed) parent.uploadFailed('" + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); return; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } } response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST/*w ww . ja va 2 s . co m*/ @Path("/upload") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String bookId = null; String contentType = null; // String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); // fileItem.get(); size = bytes.length; // data = Base64.encodeBytes(bytes); } } } // Add the logo Book book = bookDAO.getBookById(bookId); // Update the front cover BookCategory cat = holder.getCategoryByName(book.getCategory()); BookCover cover = holder.getCoverByName(book.getCoverName()); String authorName = bookDAO.getAuthorName(book.getAuthorId()); //String frontBookCoverEncoded = imgService // .createDefaultFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes, authorName); //String smallFrontBookCoverEncoded = imgService // .createDefaultSmallFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes, authorName); // Save it // Add the logo book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size, frontBookCoverBytes, frontBookCoverSmallBytes); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:de.fhg.iais.model.aip.util.XmlUtilsTest.java
@Test public void testValidatorIfSchemaIsMissing() throws IOException { final String exampleXml = Streams .asString(getClass().getResourceAsStream("/xml/anAddressWithoutSchemaInfo.xml")); final URL xsd = getClass().getResource("/xml/address.xsd"); parseAndValidate(exampleXml, xsd);/*from ww w.j a v a 2 s .c o m*/ }
From source file:azkaban.jobs.AbstractProcessJob.java
public Props loadOutputFileProps(final File outputPropertiesFile) { InputStream reader = null;//from w w w . ja v a 2s. c o m try { System.err.println("output properties file=" + outputPropertiesFile.getAbsolutePath()); reader = new BufferedInputStream(new FileInputStream(outputPropertiesFile)); Props outputProps = new Props(); final String content = Streams.asString(reader).trim(); if (!content.isEmpty()) { Map<String, Object> propMap = jsonToJava.apply(new JSONObject(content)); for (Map.Entry<String, Object> entry : propMap.entrySet()) { outputProps.put(entry.getKey(), entry.getValue().toString()); } } return outputProps; } catch (FileNotFoundException e) { log.info(String.format("File[%s] wasn't found, returning empty props.", outputPropertiesFile)); return new Props(); } catch (Exception e) { log.error( "Exception thrown when trying to load output file props. Returning empty Props instead of failing. Is this really the best thing to do?", e); return new Props(); } finally { IOUtils.closeQuietly(reader); } }