List of usage examples for org.apache.commons.fileupload.util Streams asString
public static String asString(InputStream pStream) throws IOException
From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java
/** * Receive an upload book assest/*from w ww. java2s .c o m*/ * * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest) */ @Override @POST @Path("/upload2") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process2(@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 description = null; String descriptionDetail = null; String hoursOfWorkStr = null; String bookId = null; String action = null; String dataType = 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()) { // description if (item.getFieldName().equals("description")) { description = Streams.asString(stream); } // detail if (item.getFieldName().equals("descriptionDetail")) { descriptionDetail = Streams.asString(stream); } // Work hours if (item.getFieldName().equals("hoursOfWork")) { hoursOfWorkStr = Streams.asString(stream); } // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } // action if (item.getFieldName().equals("action")) { action = Streams.asString(stream); } // datatype if (item.getFieldName().equals("dataType")) { dataType = 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(); size = bytes.length; } } } // convert the hoursOfWork int hoursOfWork = 0; if (hoursOfWorkStr != null) { try { hoursOfWork = Integer.parseInt(hoursOfWorkStr); } catch (Exception e) { log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr + " to an int in BookAssetUploadServiceImpl. Converting to 0."); hoursOfWork = 0; } } // Verify that the session user is the author or co-author of // the book. They would be the only ones who could add to the // book. String userId = userToken.getUserId(); boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId); if (isAuthor == false) { throw new Exception("The user " + userId + " is not the author or co-author of the book."); } // Add to the database bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType, BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size, hoursOfWork, userId); // Tell Solr about the update queueBookEvent.fire(new QueueBookEvent(bookId, userId)); } 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:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
private static void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer, Consumer<BinaryFile> fileConsumer) { try {//from w w w .j ava 2s . c o m if (fileItem.isFormField()) { InputStream stream = fileItem.getInputStream(); valueConsumer.accept(Streams.asString(stream)); } else { BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(), fileItem.getContentType(), fileItem.getName()); fileConsumer.accept(binaryFile); } } catch (IOException ioe) { throw new BadRequestException("Invalid body", ioe); } }
From source file:controllers.PictureController.java
@FilterWith(SecureFilter.class) public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception { String fileLocation = ""; // Make sure the context really is a multipart context... if (context.isMultipart()) { Picture pic = new Picture(); // 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 (item.isFormField()) { String value = Streams.asString(stream); switch (name) { case "name": pic.setName(value);//from w w w . j a v a2 s . c om break; case "about": pic.setAbout(value); break; } } else { OutputStream outputStream = null; try { fileLocation = "public/pictures/" + item.getName(); outputStream = new FileOutputStream(new File(fileLocation)); int read = 0; byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } pic.setFile(item.getName()); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { // outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } pictureDao.postArticlePicture(username, pic); } reziseImage(fileLocation); // We always return ok. You don't want to do that in production ;) return Results.redirect("/picture/all"); }
From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); boolean isGWT = true; try {//from ww w. j av a 2 s . co 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); // upload requests can come from smartGWT (args) or // FCKEditor (request) String contextName = args.get("context"); String model = args.get("model"); String path = args.get("path"); if (contextName == null) { isGWT = false; contextName = request.getParameter("context"); model = request.getParameter("model"); path = request.getParameter("path"); if (log.isDebugEnabled()) log.debug("query=" + request.getQueryString()); } else if (log.isDebugEnabled()) log.debug(args); // the following code stores the file based on your parameters /* ProjectContext context = ContextService.get().getContext( contextName); ProjectState state = (ProjectState) request.getSession() .getAttribute(contextName); InputStream in = null; try { in = item.openStream(); state.getFileManager().storeFile( context.getModel(model), path + fileName, in); } catch (Exception e) { e.printStackTrace(); log.error("Fail to upload " + fileName + " to " + path); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } */ } } // TODO: need to handle conversion options and error reporting 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>"); if (isGWT) { out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); } else out.println(getEditorResponse()); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:azkaban.flow.ImmutableFlowManager.java
@Override public FlowExecutionHolder loadExecutableFlow(long id) { File storageFile = new File(storageDirectory, String.format("%s.json", id)); if (!storageFile.exists()) { return null; }/*from w w w . ja va2 s. co m*/ BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(storageFile)); JSONObject jsonObj = new JSONObject(Streams.asString(in)); return deserializer.apply(jsonToJava.apply(jsonObj)); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {/*from w ww .j a v a2 s. c o m*/ ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); FileItemStream fileItem = null; // 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 { fileItem = item; } } if (fileItem != null) { args.put("contentType", fileItem.getContentType()); args.put("fileName", FileUtils.filename(fileItem.getName())); System.out.println("uploading args " + args); String context = args.get("context"); String model = args.get("model"); String xq = args.get("xq"); System.out.println(context + "," + model + "," + xq); File f = new File(args.get("fileName")); System.out.println(f.getAbsolutePath()); /* * TODO: pboysen get the state, context and fileManager and store the * stream in fileName. Parameters should be passed to locate state * and conversion options. */ 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>"); out.println("top.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } else { //TODO: add error code } } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods * adapted from Jason Pell's multipart classes (see class description). * /* www . ja v a 2 s . com*/ * @param saveDir * the directory to save off the file * @param servletRequest * the request containing the multipart * @throws java.io.IOException * is thrown if encoding fails. * @throws */ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { Integer delay = 3; UploadListener listener = null; DiskFileItemFactory fac = null; // Parse the request try { if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) { servletRequest.setAttribute("error", "size"); FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (item.isFormField()) { List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } InputStream stream = item.openStream(); values.add(Streams.asString(stream)); params.put(item.getFieldName(), values); } } return; } else { listener = new UploadListener(servletRequest, delay); fac = new MonitoredDiskFileItemFactory(listener); } // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (log.isDebugEnabled()) log.debug("Found item " + item.getFieldName()); if (item.isFormField()) { log.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { log.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning // that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { log.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } String targetFileName = item.getName(); if (!targetFileName.contains(":")) item.write(new File(targetDirectory + targetFileName)); //?Action List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (Exception e) { log.error(e); errors.add(e.getMessage()); } }
From source file:com.sonatype.nexus.repository.nuget.internal.NugetPushHandlerTest.java
private void checkResponse(Response response, int expectedCode, String expectedContentType, String expectedSubstring) throws Exception { assertThat(response.getStatus().getCode(), is(expectedCode)); assertThat(response instanceof PayloadResponse, is(true)); Payload responsePayload = ((PayloadResponse) response).getPayload(); assertThat(responsePayload.getContentType(), is(expectedContentType)); String responseBody = Streams.asString(responsePayload.openInputStream()); assertThat(responseBody.contains(expectedSubstring), is(true)); }
From source file:azkaban.jobExecutor.AbstractProcessJob.java
public Props loadOutputFileProps(final File outputPropertiesFile) { InputStream reader = null;/*from w w w .j a v a2 s .co 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()) { @SuppressWarnings("unchecked") Map<String, Object> propMap = (Map<String, Object>) JSONUtils.parseJSONFromString(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); } }
From source file:n3phele.backend.RepoProxy.java
@POST @Path("{id}/upload/{bucket}") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket, @QueryParam("name") String destination, @QueryParam("expires") long expires, @QueryParam("signature") String signature, @Context HttpServletRequest request) throws NotFoundException { Repository repo = Dao.repository().load(id); if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(), bucket + ":" + destination)) { log.severe("Expired temporary authorization"); throw new NotFoundException(); }//from w w w . ja v a2 s .co m try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding " + upload.getHeaderEncoding()); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream())); } else { InputStream stream = item.openStream(); log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName() + " content " + item.getContentType()); URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination); Response.created(target).build(); } } } catch (Exception e) { log.log(Level.WARNING, "Processing error", e); } return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build(); }