List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName
String getFieldName();
From source file:org.restlet.example.ext.fileupload.FileUploadServerResource.java
@Post public Representation accept(Representation entity) throws Exception { Representation result = null;// w ww . ja va2s . c o m if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); // 3/ Request is parsed by the handler which generates a // list of FileItems FileItemIterator fileIterator = upload.getItemIterator(entity); // Process only the uploaded item called "fileToUpload" // and return back boolean found = false; while (fileIterator.hasNext() && !found) { FileItemStream fi = fileIterator.next(); if (fi.getFieldName().equals("fileToUpload")) { // For the matter of sample code, it filters the multo // part form according to the field name. found = true; // consume the stream immediately, otherwise the stream // will be closed. StringBuilder sb = new StringBuilder("media type: "); sb.append(fi.getContentType()).append("\n"); sb.append("file name : "); sb.append(fi.getName()).append("\n"); BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } sb.append("\n"); result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return result; }
From source file:org.retrostore.request.RequestDataImpl.java
/** * Parses a multipart request and gets its files and parameters. */// w w w . jav a 2 s . c o m private static void parseMultipartContent(HttpServletRequest request, Map<String, String> formParams, List<UploadFile> uploadFiles) { if (!ServletFileUpload.isMultipartContent(request)) { return; } ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream file = itemIterator.next(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteStreams.copy(file.openStream(), bytesOut); byte[] bytes = bytesOut.toByteArray(); // If an item has a name, we think it's a file, otherwise we treat it as a regular string // parameter. if (!Strings.isNullOrEmpty(file.getName())) { uploadFiles.add(new UploadFile(file.getFieldName(), file.getName(), bytes)); } else { String str = new String(bytes, StandardCharsets.UTF_8); formParams.put(file.getFieldName(), str); } } } catch (FileUploadException | IOException e) { LOG.log(Level.WARNING, "Cannot parse request for filename.", e); } }
From source file:org.sharegov.cirm.utils.PhotoUploadResource.java
/** * Accepts and processes a representation posted to the resource. As * response, the content of the uploaded file is sent back the client. *///from ww w . ja v a 2 s . c o m @Post public Representation accept(Representation entity) { // NOTE: the return media type here is TEXT_HTML because IE opens up a file download box // if it's APPLICATION_JSON as we'd want it. Representation rep = new StringRepresentation(GenUtils.ko("Unable to upload, bad request.").toString(), MediaType.TEXT_HTML); if (entity != null) { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items // DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(); // List<FileItem> items; // // // 3/ Request is parsed by the handler which generates a // // list of FileItems InputStream is = null; Graphics2D g = null; FileOutputStream fos = null; ByteArrayOutputStream baos = null; try { FileItemIterator fit = upload.getItemIterator(entity); while (fit.hasNext()) { FileItemStream stream = fit.next(); if (stream.getFieldName().equals("uploadImage")) { String contentType = stream.getContentType(); if (contentType.startsWith("image")) { String extn = contentType.substring(contentType.indexOf("/") + 1); byte[] data = GenUtils.getBytesFromStream(stream.openStream(), true); String filename = "image_" + Refs.idFactory.resolve().newId(null) + "." + extn; //String filename = "srphoto_123" + "."+extn; // + OWLRefs.idFactory.resolve().newId("Photo"); // may add Photo class to ontology File f = new File(StartUp.config.at("workingDir").asString() + "/src/uploaded", filename); StringBuilder sb = new StringBuilder(""); String hostname = java.net.InetAddress.getLocalHost().getHostName(); boolean ssl = StartUp.config.is("ssl", true); int port = ssl ? StartUp.config.at("ssl-port").asInteger() : StartUp.config.at("port").asInteger(); if (ssl) sb.append("https://"); else sb.append("http://"); sb.append(hostname); if ((ssl && port != 443) || (!ssl && port != 80)) sb.append(":").append(port); sb.append("/uploaded/"); sb.append(filename); //Start : resize Image int rw = 400; int rh = 300; is = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(is); int w = image.getWidth(); int h = image.getHeight(); if (w > rw) { BufferedImage bi = new BufferedImage(rw, rh, image.getType()); g = bi.createGraphics(); g.drawImage(image, 0, 0, rw, rh, null); baos = new ByteArrayOutputStream(); ImageIO.write(bi, extn, baos); data = baos.toByteArray(); } //End: resize Image fos = new FileOutputStream(f); fos.write(data); Json j = GenUtils.ok().set("image", sb.toString()); //Json j = GenUtils.ok().set("image", filename); rep = new StringRepresentation(j.toString(), (MediaType) MediaType.TEXT_HTML); } else { rep = new StringRepresentation(GenUtils.ko("Please upload only Images.").toString(), MediaType.TEXT_HTML); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } if (baos != null) { try { baos.flush(); baos.close(); } catch (IOException e) { } } if (g != null) { g.dispose(); } } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return rep; }
From source file:org.sigmah.server.endpoint.export.sigmah.ExportModelServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { final Authentication authentication = retrieveAuthentication(req); boolean hasPermission = false; if (authentication != null) { final User user = authentication.getUser(); ProfileDTO profile = SigmahAuthDictionaryServlet.aggregateProfiles(user, null, injector); hasPermission = ProfileUtils.isGranted(profile, GlobalPermissionEnum.VIEW_ADMIN); }/* w ww .j av a2s .c o m*/ if (hasPermission) { final ServletFileUpload fileUpload = new ServletFileUpload(); final HashMap<String, String> properties = new HashMap<String, String>(); byte[] data = null; try { final FileItemIterator iterator = fileUpload.getItemIterator(req); // Iterating on the fields sent into the request while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); LOG.debug("field '" + name + "' = '" + value + '\''); // The current field is a property properties.put(name, value); } else { // The current field is a file LOG.debug("field '" + name + "' (FILE)"); final ByteArrayOutputStream serializedData = new ByteArrayOutputStream(); long dataSize = 0L; int b = stream.read(); while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) { serializedData.write(b); dataSize++; b = stream.read(); } stream.close(); data = serializedData.toByteArray(); } } } catch (FileUploadException ex) { LOG.warn("Error while receiving a serialized model.", ex); } if (data != null) { // A file has been received final String type = properties.get("type"); final ModelHandler handler = handlers.get(type); if (handler != null) { if (handler instanceof ProjectModelHandler) { final String projectModelTypeAsString = properties.get("project-model-type"); try { final ProjectModelType projectModelType = ProjectModelType .valueOf(projectModelTypeAsString); ((ProjectModelHandler) handler).setProjectModelType(projectModelType); } catch (IllegalArgumentException e) { LOG.debug("Bad value for project model type: " + projectModelTypeAsString, e); } } final ByteArrayInputStream inputStream = new ByteArrayInputStream(data); try { handler.importModel(inputStream, injector.getInstance(EntityManager.class), authentication); } catch (ExportException ex) { LOG.error("Model import error, type: " + type, ex); resp.sendError(500); } } else { LOG.warn("The asked model type (" + type + ") doesn't have any handler registered."); resp.sendError(501); } } else { LOG.warn("No file has been received."); resp.sendError(400); } } else { LOG.warn("Unauthorized access to the import service from user " + authentication); resp.sendError(401); } } else { LOG.warn("The request doesn't have the correct enctype."); resp.sendError(400); } }
From source file:org.sigmah.server.file.util.MultipartRequest.java
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException { if (!ServletFileUpload.isMultipartContent(request)) { LOGGER.error("Request content is not multipart."); throw new StatusServletException(Response.SC_PRECONDITION_FAILED); }/*ww w .ja v a 2s . c om*/ final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request); while (iterator.hasNext()) { // Gets the first HTTP request element. final FileItemStream item = iterator.next(); if (item.isFormField()) { final String value = Streams.asString(item.openStream(), "UTF-8"); properties.put(item.getFieldName(), value); } else if (callback != null) { callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType()); } } }
From source file:org.sigmah.server.servlet.ImportServlet.java
private byte[] readFileAndProperties(final HttpServletRequest request, final Map<String, String> properties) throws FileUploadException, IOException { byte[] data = null; final ServletFileUpload fileUpload = new ServletFileUpload(); final FileItemIterator iterator = fileUpload.getItemIterator(request); // Iterating on the fields sent into the request while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); LOG.debug("field '" + name + "' = '" + value + '\''); // The current field is a property properties.put(name, value); } else {// w w w. j av a 2 s .com // The current field is a file LOG.debug("field '" + name + "' (FILE)"); final ByteArrayOutputStream serializedData = new ByteArrayOutputStream(); long dataSize = 0L; int b = stream.read(); while (b != -1 && dataSize < MAXIMUM_FILE_SIZE) { serializedData.write(b); dataSize++; b = stream.read(); } stream.close(); data = serializedData.toByteArray(); } } return data; }
From source file:org.sosy_lab.cpachecker.appengine.server.resource.TasksServerResource.java
@Override public Representation createTaskFromHtml(Representation input) throws IOException { List<String> errors = new LinkedList<>(); Map<String, Object> settings = new HashMap<>(); Map<String, String> options = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); try {//from w w w .ja va2s . co m FileItemIterator iter = upload.getItemIterator(ServletUtils.getRequest(getRequest())); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); switch (item.getFieldName()) { case "specification": value = (value.equals("")) ? null : value; settings.put("specification", value); break; case "configuration": value = (value.equals("")) ? null : value; settings.put("configuration", value); break; case "disableOutput": options.put("output.disable", "true"); break; case "disableExportStatistics": options.put("statistics.export", "false"); break; case "dumpConfig": options.put("configuration.dumpFile", "UsedConfiguration.properties"); break; case "logLevel": options.put("log.level", value); break; case "machineModel": options.put("analysis.machineModel", value); break; case "wallTime": options.put("limits.time.wall", value); break; case "instanceType": options.put("gae.instanceType", value); break; case "programText": if (!value.isEmpty()) { settings.put("programName", "program.c"); settings.put("programText", value); } break; } } else { if (settings.get("programText") == null) { settings.put("programName", item.getName()); settings.put("programText", IOUtils.toString(stream)); } } } } catch (FileUploadException | IOException e) { getLogger().log(Level.WARNING, "Could not upload program file.", e); errors.add("task.program.CouldNotUpload"); } settings.put("options", options); Task task = null; if (errors.isEmpty()) { TaskBuilder taskBuilder = new TaskBuilder(); task = taskBuilder.fromMap(settings); errors = taskBuilder.getErrors(); } if (errors.isEmpty()) { try { Configuration config = Configuration.builder().setOptions(task.getOptions()).build(); new GAETaskQueueTaskExecutor(config).execute(task); } catch (InvalidConfigurationException e) { errors.add("error.invalidConfiguration"); } } if (errors.isEmpty()) { getResponse().setStatus(Status.SUCCESS_CREATED); redirectSeeOther("/tasks/" + task.getKey()); return getResponseEntity(); } getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return FreemarkerUtil.templateBuilder().context(getContext()).addData("task", task) .addData("errors", errors).addData("allowedOptions", DefaultOptions.getDefaultOptions()) .addData("defaultOptions", DefaultOptions.getImmutableOptions()) .addData("specifications", DefaultOptions.getSpecifications()) .addData("configurations", DefaultOptions.getConfigurations()) .addData("cpacheckerVersion", CPAchecker.getCPAcheckerVersion()).templateName("root.ftl").build(); }
From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java
/** * <p> Example of parsing the multipart request using commons file upload. In this case the parsing happens in blocking io. * * @param request The {@code HttpServletRequest} * @return The {@code VerificationItems} * @throws Exception if an exception happens during the parsing *//*from w ww . ja va 2s . c om*/ @RequestMapping(value = "/blockingio/fileupload/multipart", method = RequestMethod.POST) public @ResponseBody VerificationItems blockingIoMultipart(final HttpServletRequest request) throws Exception { assertRequestIsMultipart(request); final ServletFileUpload servletFileUpload = new ServletFileUpload(); final FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); final VerificationItems verificationItems = new VerificationItems(); Metadata metadata = null; while (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); if (METADATA_FIELD_NAME.equals(fileItemStream.getFieldName())) { if (metadata != null) { throw new IllegalStateException("Found more than one metadata field"); } metadata = unmarshalMetadata(fileItemStream.openStream()); } else { VerificationItem verificationItem = buildVerificationItem(fileItemStream.openStream(), fileItemStream.getFieldName()); verificationItems.getVerificationItems().add(verificationItem); } } processVerificationItems(verificationItems, metadata, false); return verificationItems; }
From source file:org.synchronoss.cloud.nio.multipart.FunctionalTest.java
NioMultipartParserListener nioMultipartParserListenerVerifier(final FileItemIterator fileItemIterator, final AtomicBoolean finished) { return new NioMultipartParserListener() { AtomicInteger partIndex = new AtomicInteger(0); @Override/*from ww w . j a v a 2s. c om*/ public void onPartFinished(StreamStorage partBodyStreamStorage, Map<String, List<String>> headersFromPart) { log.info("<<<<< On part complete [" + (partIndex.addAndGet(1)) + "] >>>>>>"); assertFileItemIteratorHasNext(true); final FileItemStream fileItemStream = fileItemIteratorNext(); assertHeadersAreEqual(fileItemStream.getHeaders(), headersFromPart); assertInputStreamsAreEqual(fileItemStreamInputStream(fileItemStream), partBodyStreamStorage.getInputStream()); } @Override public void onFormFieldPartFinished(String fieldName, String fieldValue, Map<String, List<String>> headersFromPart) { log.info("<<<<< On form field complete [" + (partIndex.addAndGet(1)) + "] >>>>>>"); assertFileItemIteratorHasNext(true); final FileItemStream fileItemStream = fileItemIteratorNext(); assertTrue(fileItemStream.isFormField()); Assert.assertEquals(fieldName, fileItemStream.getFieldName()); try { Assert.assertEquals(fieldValue, IOUtils.toString(fileItemStream.openStream())); } catch (Exception e) { throw new IllegalStateException("Unable to assert field value", e); } } @Override public void onNestedPartStarted(Map<String, List<String>> headersFromParentPart) { log.info("<<<<< On form field complete [" + (partIndex) + "] >>>>>>"); } @Override public void onAllPartsFinished() { log.info("<<<<< On all parts read: Number of parts [" + partIndex.get() + "] >>>>>>"); assertFileItemIteratorHasNext(false); finished.set(true); } @Override public void onNestedPartFinished() { log.info("<<<<< On form field complete [" + (partIndex) + "] >>>>>>"); } @Override public void onError(String message, Throwable cause) { log.info("<<<<< On error. Part " + partIndex.get() + "] >>>>>>"); finished.set(true); log.error(message, cause); fail("Got an error from the parser"); } InputStream fileItemStreamInputStream(final FileItemStream fileItemStream) { try { return fileItemStream.openStream(); } catch (Exception e) { throw new IllegalStateException("Unable to open the file item inputstream", e); } } void assertFileItemIteratorHasNext(boolean hasNext) { try { assertTrue("File iterator has next is not " + hasNext, hasNext == fileItemIterator.hasNext()); } catch (Exception e) { throw new IllegalStateException("Unable to verify if the FileItemIterator has a next", e); } } FileItemStream fileItemIteratorNext() { try { return fileItemIterator.next(); } catch (Exception e) { throw new IllegalStateException("Unable to retrieve the next FileItemStream", e); } } }; }
From source file:org.tangram.components.servlet.ServletRequestParameterAccess.java
/** * Weak visibility to avoid direct instanciation. *///from w w w . ja v a 2 s. co m @SuppressWarnings("unchecked") ServletRequestParameterAccess(HttpServletRequest request, long uploadFileMaxSize) { final String reqContentType = request.getContentType(); LOG.debug("() uploadFileMaxSize={} request.contentType={}", uploadFileMaxSize, reqContentType); if (StringUtils.isNotBlank(reqContentType) && reqContentType.startsWith("multipart/form-data")) { ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(uploadFileMaxSize); try { for (FileItemIterator itemIterator = upload.getItemIterator(request); itemIterator.hasNext();) { FileItemStream item = itemIterator.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String[] value = parameterMap.get(item.getFieldName()); int i = 0; if (value == null) { value = new String[1]; } else { String[] newValue = new String[value.length + 1]; System.arraycopy(value, 0, newValue, 0, value.length); i = value.length; value = newValue; } // if value[i] = Streams.asString(stream, "UTF-8"); LOG.debug("() request parameter {}='{}'", fieldName, value[0]); parameterMap.put(item.getFieldName(), value); } else { try { LOG.debug("() item {} :{}", item.getName(), item.getContentType()); final byte[] bytes = IOUtils.toByteArray(stream); if (bytes.length > 0) { originalNames.put(fieldName, item.getName()); blobs.put(fieldName, bytes); } // if } catch (IOException ex) { LOG.error("()", ex); if (ex.getCause() instanceof FileUploadBase.FileSizeLimitExceededException) { throw new RuntimeException(ex.getCause().getMessage()); // NOPMD we want to lose parts of our stack trace! } // if } // try/catch } // if } // for } catch (FileUploadException | IOException ex) { LOG.error("()", ex); } // try/catch } else { parameterMap = request.getParameterMap(); } // if }