List of usage examples for org.apache.commons.fileupload FileUpload FileUpload
public FileUpload()
FileItem
instances. From source file:com.fizzbuzz.vroom.extension.googlecloudstorage.api.resource.GcsFilesResource.java
/** * * @param rep//from w w w . j a v a 2 s .co m */ public void postResource(final Representation rep) { if (rep == null) setStatus(Status.CLIENT_ERROR_BAD_REQUEST); else { try { FileUpload fileUpload = new FileUpload(); FileItemIterator fileItemIterator = fileUpload.getItemIterator(new RepresentationContext(rep)); if (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); validateFileItemStream(fileItemStream); String fileName = fileItemStream.getName(); byte[] bytes = ByteStreams.toByteArray(fileItemStream.openStream()); F file = createFile(fileName); mBiz.create(file, bytes); // we're not going to send a representation of the file back to the client, since they probably // don't want that. Instead, we'll send them a 201, with the URL to the created file in the // Location header of the response. getResponse().setStatus(Status.SUCCESS_CREATED); // set the Location response header String uri = getElementUri(file); getResponse().setLocationRef(uri); mLogger.info("created new file resource at: {}", uri); } } catch (FileUploadException e) { throw new IllegalArgumentException( "caught FileUploadException while attempting to parse " + "multipart form", e); } catch (IOException e) { throw new IllegalArgumentException( "caught IOException while attempting to parse multipart " + "form", e); } } }
From source file:at.gv.egiz.bku.binding.MultiPartFormDataInputDecoder.java
@Override public Iterator<FormParameter> getFormParameterIterator() { try {/*from w ww . j a v a 2 s. c om*/ FileUpload fup = new FileUpload(); FileItemIterator fit = fup.getItemIterator(this); return new IteratorDelegator(fit); } catch (Exception iox) { log.error("Cannot decode multipart form data stream " + iox); throw new SLRuntimeException(iox); } }
From source file:hk.hku.cecid.corvus.http.PartnershipSenderUnitTest.java
/** * A Helper method which assert whether the HTTP content received in the HTTP monitor * is a multi-part form data, with basic-auth and well-formed partnership operation request. *//*from ww w .ja v a 2 s . c o m*/ private void assertHttpRequestReceived() throws Exception { // Debug print information. Map headers = monitor.getHeaders(); // #0 Assertion assertFalse("No HTTP header found in the captured data.", headers.isEmpty()); Map.Entry tmp = null; Iterator itr = null; itr = headers.entrySet().iterator(); logger.info("Header information"); while (itr.hasNext()) { tmp = (Map.Entry) itr.next(); logger.info(tmp.getKey() + " : " + tmp.getValue()); } // #1 Check BASIC authentication value. String basicAuth = (String) headers.get("Authorization"); // #1 Assertion assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth); String[] authToken = basicAuth.split(" "); // There are 2 token, one is the "Basic" and another is the base64 auth value. assertTrue(authToken.length == 2); assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic")); // #1 Decode the base64 authentication value to see whether it is "corvus:corvus". String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8"); assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential); // #2 Check content Type String contentType = monitor.getContentType(); String mediaType = contentType.split(";")[0]; assertEquals("Invalid content type", "multipart/form-data", mediaType); // #3 Check the multi-part content. // Make a request context that bridge the content from our monitor to FileUpload library. RequestContext rc = new RequestContext() { public String getCharacterEncoding() { return "charset=ISO-8859-1"; } public int getContentLength() { return monitor.getContentLength(); } public String getContentType() { return monitor.getContentType(); } public InputStream getInputStream() { return monitor.getInputStream(); } }; FileUpload multipartParser = new FileUpload(); FileItemIterator item = multipartParser.getItemIterator(rc); FileItemStream fstream = null; /* * For each field in the partnership, we have to check the existence of the * associated field in the HTTP request. Also we check whether the content * of that web form field has same data to the field in the partnership. */ itr = this.target.getPartnershipMapping().entrySet().iterator(); Map data = ((KVPairData) this.target.properties).getProperties(); Map.Entry e; // an entry representing the partnership data to web form name mapping. String formParamName; // a temporary pointer pointing to the value in the entry. Object dataValue; // a temporary pointer pointing to the value in the partnership data. while (itr.hasNext()) { e = (Map.Entry) itr.next(); formParamName = (String) e.getValue(); // Add new part if the mapped key is not null. if (formParamName != null) { assertTrue("Insufficient number of web form parameter hit.", item.hasNext()); // Get the next multi-part element. fstream = item.next(); // Assert field name assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName()); // Assert field content dataValue = data.get(e.getKey()); if (dataValue instanceof String) { // Assert content equal. assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null)); } else if (dataValue instanceof byte[]) { byte[] expectedBytes = (byte[]) dataValue; byte[] actualBytes = IOHandler.readBytes(fstream.openStream()); // Assert byte length equal assertEquals(expectedBytes.length, actualBytes.length); for (int j = 0; j < expectedBytes.length; j++) assertEquals(expectedBytes[j], actualBytes[j]); } else { throw new IllegalArgumentException("Invalid content found in multipart."); } // Log information. logger.info("Field name found and verifed: " + fstream.getFieldName() + " content type:" + fstream.getContentType()); } } /* Check whether the partnership operation in the HTTP request is expected as i thought */ assertTrue("Missing request_action ?!", item.hasNext()); fstream = item.next(); assertEquals("request_action", fstream.getFieldName()); // Assert the request_action has same content the operation name. Map partnershipOpMap = this.target.getPartnershipOperationMapping(); assertEquals(partnershipOpMap.get(new Integer(this.target.getExecuteOperation())), IOHandler.readString(fstream.openStream(), null)); }
From source file:com.google.enterprise.adaptor.experimental.Sim.java
static Map<String, byte[]> splitMultipartRequest(RequestContext req) throws IOException { Map<String, byte[]> parts = new HashMap<String, byte[]>(); try {//from ww w .jav a2s .c o m FileUpload upload = new FileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String field = item.getFieldName(); byte value[] = IOHelper.readInputStreamToByteArray(item.openStream()); parts.put(field, value); } return parts; } catch (FileUploadException e) { throw new IOException("caught FileUploadException", e); } }
From source file:org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider.java
protected FileUpload createFileUploadInstance() { return new FileUpload(); }
From source file:org.cellprofiler.subimager.ImageWriterHandler.java
public void handle(HttpExchange exchange) throws IOException { if (!exchange.getRequestMethod().equals("POST")) { reportError(exchange, HttpURLConnection.HTTP_BAD_METHOD, "<html><body>writeimage only accepts HTTP post</body></html>"); return;//from w w w.ja v a 2 s . c om } final String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>No Content-type request header</body></html>"); return; } if (!contentType.startsWith(MULTIPART_FORM_DATA)) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Content type must be " + MULTIPART_FORM_DATA + ".</body></html>"); return; } int idx = contentType.indexOf(BOUNDARY_EQUALS, MULTIPART_FORM_DATA.length()); if (idx == -1) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Did not find boundary identifier in multipart/form-data content type.</body></html>"); return; } final String contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding"); String contentLengthString = exchange.getRequestHeaders().getFirst("Content-Length"); if (contentLengthString == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>No Content-Length request header</body></html>"); return; } try { Integer.parseInt(contentLengthString); } catch (NumberFormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String .format("<html><body>Content length was not a number: %s</body></html>", contentLengthString)); return; } final int contentLength = Integer.parseInt(contentLengthString); final InputStream requestBodyStream = exchange.getRequestBody(); FileUpload upload = new FileUpload(); FileItemIterator fileItemIterator; String omeXML = null; URI uri = null; int index = 0; NDImage ndimage = null; String compression = DEFAULT_COMPRESSION; try { fileItemIterator = upload.getItemIterator(new RequestContext() { public String getCharacterEncoding() { return contentEncoding; } public String getContentType() { return contentType; } public int getContentLength() { return contentLength; } public InputStream getInputStream() throws IOException { return requestBodyStream; } }); while (fileItemIterator.hasNext()) { FileItemStream fis = fileItemIterator.next(); String name = fis.getFieldName(); if (name.equals(NAME_IMAGE)) { String imageContentType = fis.getContentType(); if (imageContentType == null) { reportError(exchange, HttpURLConnection.HTTP_UNSUPPORTED_TYPE, "<html><body>Image form-data field must have a content type.</body></html>"); return; } try { InputStream is = SubimagerUtils.getInputStream(exchange, fis); if (is == null) return; ndimage = NDImage.decode(is); } catch (MalformedStreamException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Failed to read body for part, " + name + ".</body></html>"); } catch (IOException e) { reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "<html><body>Failed to read multipart body data</body></html>"); return; } catch (org.cellprofiler.subimager.NDImage.FormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Image data was not in correct format: " + e.getMessage() + "</body></html>"); return; } } else { String partDataString = SubimagerUtils.readFully(exchange, fis); if (partDataString == null) return; if (name.equals(NAME_INDEX)) { try { index = Integer.parseInt(partDataString); } catch (NumberFormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Index form-data field must be a number: " + partDataString + ".</body></html>"); return; } } else if (name.equals(NAME_OMEXML)) { omeXML = partDataString; } else if (name.equals(NAME_URL)) { try { uri = new URI(partDataString); } catch (URISyntaxException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Improperly formatted URL: " + partDataString + ".</body></html>"); return; } } else if (name.equals(NAME_COMPRESSION)) { compression = partDataString; } } } if (ndimage == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have an image part</body></html>"); return; } if (uri == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have a URL part</body></html>"); return; } if (omeXML == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have an omexml part</body></html>"); return; } writeImage(exchange, ndimage, uri, omeXML, index, compression); } catch (FileUploadException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String .format("<html><body>Parsing error in multipart message: %s</body></html>", e.getMessage())); return; } }
From source file:org.cellprofiler.subimager.TestImageJHandlerBase.java
protected Response post(Request request, Map<String, NDImage> ndimagesIn, Map<String, NDImage> ndimagesOut) { StringWriter writer = new StringWriter(); try {//from ww w .j a va2s . c o m Marshaller marshaller = new Marshaller(writer); marshaller.marshal(request); } catch (MarshalException e2) { throw new AssertionError(e2.getMessage()); } catch (ValidationException e2) { throw new AssertionError(e2.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block throw new AssertionError(e.getMessage()); } String xml = writer.toString(); ArrayList<Part> parts = new ArrayList<Part>(); parts.add(new StringPart(ImageJHandler.NAME_REQUEST, xml)); String sURL = String.format("http://localhost:%d/imagej", getPort()); final PostMethod post = new PostMethod(sURL); for (Map.Entry<String, NDImage> entry : ndimagesIn.entrySet()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entry.getValue().encode(bos); } catch (IOException e1) { e1.printStackTrace(); throw new AssertionError("Failed to encode image: " + e1.getMessage()); } ByteArrayPartSource src = new ByteArrayPartSource(entry.getKey(), bos.toByteArray()); FilePart filePart = new FilePart(entry.getKey(), src, "application/octet-stream", "binary"); parts.add(filePart); } post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), post.getParams())); HttpClient client = new HttpClient(); int responseCode; try { responseCode = client.executeMethod(post); } catch (HttpException e) { throw new AssertionError(e.getMessage()); } catch (IOException e) { throw new AssertionError(e.getMessage()); } assertEquals(HttpURLConnection.HTTP_OK, responseCode); final String contentType = post.getResponseHeader("Content-Type").getValue(); assertTrue(contentType.startsWith("multipart/form-data")); final long contentLength = post.getResponseContentLength(); try { final InputStream responseBodyStream = post.getResponseBodyAsStream(); FileUpload upload = new FileUpload(); FileItemIterator fileItemIterator; fileItemIterator = upload.getItemIterator(new RequestContext() { public String getCharacterEncoding() { if (post.getResponseHeader("Content-Encoding") == null) return null; return post.getResponseHeader("Content-Encoding").getValue(); } public String getContentType() { return contentType; } public int getContentLength() { return (int) contentLength; } InputStream tmpStream = null; public InputStream getInputStream() throws IOException { if (tmpStream == null) { byte[] buf = new byte[(int) contentLength]; int offset = 0; while (offset < buf.length) { offset += responseBodyStream.read(buf, offset, buf.length - offset); } tmpStream = new ByteArrayInputStream(buf); } return tmpStream; } }); assertTrue(fileItemIterator.hasNext()); FileItemStream fis = fileItemIterator.next(); assertEquals(fis.getFieldName(), ImageJHandler.NAME_RESPONSE); Reader rdr = new InputStreamReader(fis.openStream(), "utf-8"); Unmarshaller unmarshaller = new Unmarshaller(Response.class); unmarshaller.setProperty(XMLProperties.LENIENT_INTEGER_VALIDATION, "true"); Object oresponse = unmarshaller.unmarshal(rdr); assertTrue(oresponse instanceof Response); Response response = (Response) oresponse; while (fileItemIterator.hasNext()) { fis = fileItemIterator.next(); String name = fis.getFieldName(); NDImage ndimage = NDImage.decode(fis.openStream()); ndimagesOut.put(name, ndimage); } return response; } catch (IOException e) { e.printStackTrace(); throw new AssertionError(e.getMessage()); } catch (FileUploadException e) { e.printStackTrace(); throw new AssertionError(e.getMessage()); } catch (MarshalException e) { e.printStackTrace(); throw new AssertionError(e.getMessage()); } catch (ValidationException e) { e.printStackTrace(); throw new AssertionError(e.getMessage()); } catch (FormatException e) { e.printStackTrace(); throw new AssertionError(e.getMessage()); } }
From source file:org.gatein.wsrp.consumer.handlers.MultiPartUtil.java
public static MultiPartResult getMultiPartContent(RequestContext requestContext) { RequestContextWrapper requestContextWrapper = new RequestContextWrapper(requestContext); MultiPartResult result = null;/*w w w . j ava 2 s.co m*/ try { if (FileUpload.isMultipartContent(requestContextWrapper)) { result = new MultiPartResult(); // content is multipart, we need to parse it (that includes form parameters) FileUpload upload = new FileUpload(); FileItemIterator iter = upload.getItemIterator(requestContextWrapper); List<UploadContext> uploadContexts = new ArrayList<UploadContext>(7); List<NamedString> formParameters = new ArrayList<NamedString>(7); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (!item.isFormField()) { String contentType = item.getContentType(); if (log.isDebugEnabled()) { log.debug("File field " + item.getFieldName() + " with file name " + item.getName() + " and content type " + contentType + " detected."); } BufferedInputStream bufIn = new BufferedInputStream(stream); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); int c = bufIn.read(); while (c != -1) { bos.write(c); c = bufIn.read(); } bos.flush(); baos.flush(); bufIn.close(); bos.close(); final byte[] uploadData = baos.toByteArray(); if (uploadData.length != 0) { UploadContext uploadContext = WSRPTypeFactory.createUploadContext(contentType, uploadData); List<NamedString> mimeAttributes = new ArrayList<NamedString>(2); String value = FileUpload.FORM_DATA + ";" + " name=\"" + item.getFieldName() + "\";" + " filename=\"" + item.getName() + "\""; NamedString mimeAttribute = WSRPTypeFactory .createNamedString(FileUpload.CONTENT_DISPOSITION, value); mimeAttributes.add(mimeAttribute); mimeAttribute = WSRPTypeFactory.createNamedString(FileUpload.CONTENT_TYPE, item.getContentType()); mimeAttributes.add(mimeAttribute); uploadContext.getMimeAttributes().addAll(mimeAttributes); uploadContexts.add(uploadContext); } else { log.debug("Ignoring empty file " + item.getName()); } } else { NamedString formParameter = WSRPTypeFactory.createNamedString(item.getFieldName(), Streams.asString(stream)); formParameters.add(formParameter); } } result.getUploadContexts().addAll(uploadContexts); result.getFormParameters().addAll(formParameters); } } catch (Exception e) { log.debug("Couldn't create UploadContext", e); } return result; }
From source file:org.jwifisd.eyefi.Main3.java
public static void main(String[] args) throws Exception { MultipartStream stream = new MultipartStream( new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"), "---------------------------02468ace13579bdfcafebabef00d".getBytes()); ByteArrayOutputStream output = new ByteArrayOutputStream(); String readHeaders = stream.readHeaders(); System.out.println(readHeaders.toString()); stream.readBodyData(output);/* w ww.j av a 2 s.c o m*/ output = new ByteArrayOutputStream(); readHeaders = stream.readHeaders(); System.out.println(readHeaders.toString()); stream.readBodyData(output); final InputStream in = new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"); FileItemIterator iter = new FileUpload().getItemIterator(new RequestContext() { @Override public InputStream getInputStream() throws IOException { return in; } @Override public String getContentType() { // TODO Auto-generated method stub return "multipart/form-data; boundary=---------------------------02468ace13579bdfcafebabef00d"; } @Override public int getContentLength() { return 4237763; } @Override public String getCharacterEncoding() { // TODO Auto-generated method stub return "UTF-8"; } }); while (iter.hasNext()) { FileItemStream item = iter.next(); System.out.println("name:" + item.getName()); System.out.println("name:" + item.getContentType()); //item.openStream(); } }
From source file:org.restlet.ext.jaxrs.internal.provider.FileUploadProvider.java
/** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream)//from ww w . ja v a2 s. co m */ public List<FileItem> readFrom(Class<List<FileItem>> type, Type genericType, Annotation[] annotations, MediaType mediaType, final MultivaluedMap<String, String> respHeaders, final InputStream entityStream) throws IOException { final FileUpload rfu = new FileUpload(); final RequestContext requCtx = new RequestContext(entityStream, respHeaders); try { return rfu.parseRequest(requCtx); } catch (FileUploadException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } final IOException ioExc = new IOException("Could not read the multipart/form-data"); ioExc.initCause(e); throw ioExc; } }