org.apache.commons.fileupload.FileUpload Java Examples

The following examples show how to use org.apache.commons.fileupload.FileUpload. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonsFileUploadSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Determine an appropriate FileUpload instance for the given encoding.
 * <p>Default implementation returns the shared FileUpload instance
 * if the encoding matches, else creates a new FileUpload instance
 * with the same configuration other than the desired encoding.
 * @param encoding the character encoding to use
 * @return an appropriate FileUpload instance.
 */
protected FileUpload prepareFileUpload(String encoding) {
	FileUpload fileUpload = getFileUpload();
	FileUpload actualFileUpload = fileUpload;

	// Use new temporary FileUpload instance if the request specifies
	// its own encoding that does not match the default encoding.
	if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
		actualFileUpload = newFileUpload(getFileItemFactory());
		actualFileUpload.setSizeMax(fileUpload.getSizeMax());
		actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());
		actualFileUpload.setHeaderEncoding(encoding);
	}

	return actualFileUpload;
}
 
Example #2
Source File: CommonsFileUploadSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine an appropriate FileUpload instance for the given encoding.
 * <p>Default implementation returns the shared FileUpload instance
 * if the encoding matches, else creates a new FileUpload instance
 * with the same configuration other than the desired encoding.
 * @param encoding the character encoding to use
 * @return an appropriate FileUpload instance.
 */
protected FileUpload prepareFileUpload(@Nullable String encoding) {
	FileUpload fileUpload = getFileUpload();
	FileUpload actualFileUpload = fileUpload;

	// Use new temporary FileUpload instance if the request specifies
	// its own encoding that does not match the default encoding.
	if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
		actualFileUpload = newFileUpload(getFileItemFactory());
		actualFileUpload.setSizeMax(fileUpload.getSizeMax());
		actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());
		actualFileUpload.setHeaderEncoding(encoding);
	}

	return actualFileUpload;
}
 
Example #3
Source File: CommonsFileUploadSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine an appropriate FileUpload instance for the given encoding.
 * <p>Default implementation returns the shared FileUpload instance
 * if the encoding matches, else creates a new FileUpload instance
 * with the same configuration other than the desired encoding.
 * @param encoding the character encoding to use
 * @return an appropriate FileUpload instance.
 */
protected FileUpload prepareFileUpload(String encoding) {
	FileUpload fileUpload = getFileUpload();
	FileUpload actualFileUpload = fileUpload;

	// Use new temporary FileUpload instance if the request specifies
	// its own encoding that does not match the default encoding.
	if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
		actualFileUpload = newFileUpload(getFileItemFactory());
		actualFileUpload.setSizeMax(fileUpload.getSizeMax());
		actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());
		actualFileUpload.setHeaderEncoding(encoding);
	}

	return actualFileUpload;
}
 
Example #4
Source File: InMemoryMultipartFormDataEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type,
                                   Type genericType,
                                   Annotation[] annotations,
                                   MediaType mediaType,
                                   MultivaluedMap<String, String> httpHeaders,
                                   InputStream entityStream) throws IOException {
    try {
        ApplicationContext context = ApplicationContext.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        FileItemFactory factory = new InMemoryItemFactory(bufferSize);
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException(String.format("Can't process multipart data item, %s", e));
    }
}
 
Example #5
Source File: MultipartFormDataEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type,
                                   Type genericType,
                                   Annotation[] annotations,
                                   MediaType mediaType,
                                   MultivaluedMap<String, String> httpHeaders,
                                   InputStream entityStream) throws IOException {
    try {
        ApplicationContext context = ApplicationContext.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        DefaultFileItemFactory factory = new DefaultFileItemFactory(bufferSize, FileCollector.getInstance().getStore());
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException(String.format("Can't process multipart data item, %s", e));
    }
}
 
Example #6
Source File: WebServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * respond to an HTTP POST request; only to handle the login process
 * 
 * @param req
 *        HttpServletRequest object with the client request
 * @param res
 *        HttpServletResponse object back to the client
 * @exception ServletException
 *            in case of difficulties
 * @exception IOException
 *            in case of difficulties
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
	// catch the login helper posts
	String option = req.getPathInfo();
	String[] parts = option.split("/");
	if ((parts.length == 2) && ((parts[1].equals("login"))))
	{
		doLogin(req, res, null);
	}

	else if (FileUpload.isMultipartContent(req))
	{
		setSession(req);
		postUpload(req, res);
	}

	else
	{
		sendError(res, HttpServletResponse.SC_NOT_FOUND);
	}
}
 
Example #7
Source File: UploadUtil.java    From mumu with Apache License 2.0 6 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example #8
Source File: CommonsFileUploadSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Determine an appropriate FileUpload instance for the given encoding.
 * <p>Default implementation returns the shared FileUpload instance
 * if the encoding matches, else creates a new FileUpload instance
 * with the same configuration other than the desired encoding.
 * @param encoding the character encoding to use
 * @return an appropriate FileUpload instance.
 */
protected FileUpload prepareFileUpload(@Nullable String encoding) {
	FileUpload fileUpload = getFileUpload();
	FileUpload actualFileUpload = fileUpload;

	// Use new temporary FileUpload instance if the request specifies
	// its own encoding that does not match the default encoding.
	if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
		actualFileUpload = newFileUpload(getFileItemFactory());
		actualFileUpload.setSizeMax(fileUpload.getSizeMax());
		actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());
		actualFileUpload.setHeaderEncoding(encoding);
	}

	return actualFileUpload;
}
 
Example #9
Source File: WebServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * respond to an HTTP POST request; only to handle the login process
 * 
 * @param req
 *        HttpServletRequest object with the client request
 * @param res
 *        HttpServletResponse object back to the client
 * @exception ServletException
 *            in case of difficulties
 * @exception IOException
 *            in case of difficulties
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
	// catch the login helper posts
	String option = req.getPathInfo();
	String[] parts = option.split("/");
	if ((parts.length == 2) && ((parts[1].equals("login"))))
	{
		doLogin(req, res, null);
	}

	else if (FileUpload.isMultipartContent(req))
	{
		setSession(req);
		postUpload(req, res);
	}

	else
	{
		sendError(res, HttpServletResponse.SC_NOT_FOUND);
	}
}
 
Example #10
Source File: ClassifyUtils.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) {
  // Handle file upload
  String contentType = request.getHeader("content-type");
  // out.write("CT: " + contentType + " " + tm + " " + id);
  if (contentType != null && contentType.startsWith("multipart/form-data")) {
    try {
      FileUpload upload = new FileUpload(new DefaultFileItemFactory());
      for (FileItem item : upload.parseRequest(request)) {
        if (item.getSize() > 0) {
          // ISSUE: could make use of content type if known
          byte[] content = item.get();
          ClassifiableContent cc = new ClassifiableContent();
          String name = item.getName();
          if (name != null)
            cc.setIdentifier("fileupload:name:" + name);
          else
            cc.setIdentifier("fileupload:field:" + item.getFieldName());              
          cc.setContent(content);
          return cc;
        }      
      }
    } catch (Exception e) {
      throw new OntopiaRuntimeException(e);
    }
  }
  return null;
}
 
Example #11
Source File: CommonsMultipartResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<FileItem>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example #12
Source File: FunctionalTest.java    From nio-multipart with Apache License 2.0 5 votes vote down vote up
@Test
public void blockingIOAdapterFunctionalTest() throws Exception {

    log.info("BLOCKING IO ADAPTER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]");

    if (log.isDebugEnabled()){
        log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream()));
    }

    final FileUpload fileUpload = new FileUpload();
    final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext());

    try(final CloseableIterator<ParserToken> parts = Multipart.multipart(testCase.getMultipartContext()).forBlockingIO(testCase.getBodyInputStream())) {

        while (parts.hasNext()) {

            ParserToken parserToken = parts.next();
            ParserToken.Type partItemType = parserToken.getType();
            if (ParserToken.Type.NESTED_END.equals(partItemType) || ParserToken.Type.NESTED_START.equals(partItemType)) {
                // Commons file upload is not returning an item representing the start/end of a nested multipart.
                continue;
            }
            assertTrue(fileItemIterator.hasNext());
            FileItemStream fileItemStream = fileItemIterator.next();
            assertEquals(parserToken, fileItemStream);
        }
    }

}
 
Example #13
Source File: CommonsMultipartResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example #14
Source File: CommonsMultipartResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example #15
Source File: MultipartPayloadProvider.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) {
  try {
    FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext);
    while (itemIterator.hasNext()) {
      FileItemStream stream = itemIterator.next();
      multipartFormData.addPart(new FormPart(stream));
    }
  } catch (Exception e) {
    throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed");

  }
}
 
Example #16
Source File: StandardMultipartResolver.java    From AndServer with Apache License 2.0 4 votes vote down vote up
public StandardMultipartResolver() {
    this.mFileItemFactory = new DiskFileItemFactory();
    this.mFileUpload = new FileUpload(mFileItemFactory);
}
 
Example #17
Source File: ReqParamUtils.java    From ontopia with Apache License 2.0 4 votes vote down vote up
/**
 * INTERNAL: Builds the Parameters object from an HttpServletRequest
 * object.
 * @since 2.0
 */
public static Parameters decodeParameters(HttpServletRequest request,
                                          String charenc)
  throws ServletException, IOException {

  String ctype = request.getHeader("content-type");
  log.debug("Content-type: " + ctype);
  Parameters params = new Parameters();      
  
  if (ctype != null && ctype.startsWith("multipart/form-data")) {
    // special file upload request, so use FileUpload to decode
    log.debug("Decoding with FileUpload; charenc="+ charenc);
    try {
      FileUpload upload = new FileUpload(new DefaultFileItemFactory());
      Iterator iterator = upload.parseRequest(request).iterator();
      while (iterator.hasNext()) {
        FileItem item = (FileItem) iterator.next();
        log.debug("Reading: " + item);
        if (item.isFormField()) {
          if (charenc != null)
            params.addParameter(item.getFieldName(), item.getString(charenc));
          else
            params.addParameter(item.getFieldName(), item.getString());
        } else
          params.addParameter(item.getFieldName(), new FileParameter(item));
      }
    } catch (FileUploadException e) {
      throw new ServletException(e);
    } 
    
  } else {
    // ordinary web request, so retrieve info and stuff into Parameters object
    log.debug("Normal parameter decode, charenc=" + charenc);
    if (charenc != null)
      request.setCharacterEncoding(charenc);
    Enumeration enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
      String param = (String) enumeration.nextElement();
      params.addParameter(param, request.getParameterValues(param));
    }
  }

  return params;
}
 
Example #18
Source File: FunctionalTest.java    From nio-multipart with Apache License 2.0 4 votes vote down vote up
@Test
public void nioParserFunctionalTest() throws Exception {

    log.info("NIO PARSER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]");

    if (log.isDebugEnabled()){
        log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream()));
    }

    final AtomicBoolean finished = new AtomicBoolean(false);
    final FileUpload fileUpload = new FileUpload();
    final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext());
    final NioMultipartParserListener nioMultipartParserListener = nioMultipartParserListenerVerifier(fileItemIterator, finished);


    // Comment out the NioMultipartParserListener above and uncomment the next two lines to
    // skip validation and just print the parts as extracted by the 2 frameworks.
    //dumpFileIterator(fileItemIterator);
    //final NioMultipartParserListener nioMultipartParserListener = nioMultipartParserListenerDumper();

    final MultipartContext multipartContext = testCase.getMultipartContext();
    final ChunksFileReader chunksFileReader = new ChunksFileReader(testCase.getBodyInputStream(), 5, 10);
    final NioMultipartParser parser = new NioMultipartParser(multipartContext, nioMultipartParserListener);

    byte[] chunk;
    while (true) {

        chunk = chunksFileReader.readChunk();
        if (chunk.length <= 0) {
            break;
        }
        parser.write(chunk, 0, chunk.length);
    }

    int attempts = 0;
    while(!finished.get()){
        Thread.sleep(100);
        if (++attempts > 3){
            fail("Parser didn't come back in a reasonable time");
        }
    }
    if (log.isInfoEnabled()){
        List<String> fsmTransitions = parser.geFsmTransitions();
        if (fsmTransitions != null) {
            log.info("TRANSITIONS: \n" + Joiner.on('\n').join(fsmTransitions));
        }else{
            log.info("To see the FSM transitions enable debug on " + NioMultipartParser.class.getName());
        }
    }

}
 
Example #19
Source File: FormHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void writeMultipartOrder() throws Exception {
	MyBean myBean = new MyBean();
	myBean.setString("foo");

	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
	parts.add("part1", myBean);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<MyBean> entity = new HttpEntity<MyBean>(myBean, entityHeaders);
	parts.add("part2", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.setMultipartCharset(UTF_8);
	this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	assertNotNull("No boundary found", contentType.getParameter("boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(2, items.size());

	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("part1", item.getFieldName());
	assertEquals("{\"string\":\"foo\"}", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("part2", item.getFieldName());

	// With developer builds we get: <MyBean><string>foo</string></MyBean>
	// But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
	// So... we make a compromise:
	assertThat(item.getString(),
			allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}
 
Example #20
Source File: FormHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void writeMultipart() throws Exception {
	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
	parts.add("name 1", "value 1");
	parts.add("name 2", "value 2+1");
	parts.add("name 2", "value 2+2");
	parts.add("name 3", null);

	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("logo", logo);

	// SPR-12108
	Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
		@Override
		public String getFilename() {
			return "Hall\u00F6le.jpg";
		}
	};
	parts.add("utf8", utf8);

	Source xml = new StreamSource(new StringReader("<root><child/></root>"));
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<Source> entity = new HttpEntity<Source>(xml, entityHeaders);
	parts.add("xml", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.setMultipartCharset(UTF_8);
	this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	assertNotNull("No boundary found", contentType.getParameter("boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(6, items.size());
	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("name 1", item.getFieldName());
	assertEquals("value 1", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+1", item.getString());

	item = items.get(2);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+2", item.getString());

	item = items.get(3);
	assertFalse(item.isFormField());
	assertEquals("logo", item.getFieldName());
	assertEquals("logo.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(4);
	assertFalse(item.isFormField());
	assertEquals("utf8", item.getFieldName());
	assertEquals("Hall\u00F6le.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(5);
	assertEquals("xml", item.getFieldName());
	assertEquals("text/xml", item.getContentType());
	verify(outputMessage.getBody(), never()).close();
}
 
Example #21
Source File: MultipartPayloadProvider.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
protected FileUpload createFileUploadInstance() {
  return new FileUpload();
}
 
Example #22
Source File: FormHttpMessageConverterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void writeMultipart() throws Exception {
	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("name 1", "value 1");
	parts.add("name 2", "value 2+1");
	parts.add("name 2", "value 2+2");
	parts.add("name 3", null);

	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("logo", logo);

	// SPR-12108
	Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
		@Override
		public String getFilename() {
			return "Hall\u00F6le.jpg";
		}
	};
	parts.add("utf8", utf8);

	Source xml = new StreamSource(new StringReader("<root><child/></root>"));
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
	parts.add("xml", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	// SPR-17030
	assertThat(contentType.getParameters().keySet(), Matchers.contains("charset", "boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(6, items.size());
	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("name 1", item.getFieldName());
	assertEquals("value 1", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+1", item.getString());

	item = items.get(2);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+2", item.getString());

	item = items.get(3);
	assertFalse(item.isFormField());
	assertEquals("logo", item.getFieldName());
	assertEquals("logo.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(4);
	assertFalse(item.isFormField());
	assertEquals("utf8", item.getFieldName());
	assertEquals("Hall\u00F6le.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(5);
	assertEquals("xml", item.getFieldName());
	assertEquals("text/xml", item.getContentType());
	verify(outputMessage.getBody(), never()).close();
}
 
Example #23
Source File: FormHttpMessageConverterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void writeMultipartOrder() throws Exception {
	MyBean myBean = new MyBean();
	myBean.setString("foo");

	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("part1", myBean);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders);
	parts.add("part2", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.setMultipartCharset(StandardCharsets.UTF_8);
	this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	assertNotNull("No boundary found", contentType.getParameter("boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(2, items.size());

	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("part1", item.getFieldName());
	assertEquals("{\"string\":\"foo\"}", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("part2", item.getFieldName());

	// With developer builds we get: <MyBean><string>foo</string></MyBean>
	// But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
	// So... we make a compromise:
	assertThat(item.getString(),
			allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}
 
Example #24
Source File: FormHttpMessageConverterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void writeMultipartOrder() throws Exception {
	MyBean myBean = new MyBean();
	myBean.setString("foo");

	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("part1", myBean);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders);
	parts.add("part2", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.setMultipartCharset(StandardCharsets.UTF_8);
	this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	assertNotNull("No boundary found", contentType.getParameter("boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(2, items.size());

	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("part1", item.getFieldName());
	assertEquals("{\"string\":\"foo\"}", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("part2", item.getFieldName());

	// With developer builds we get: <MyBean><string>foo</string></MyBean>
	// But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
	// So... we make a compromise:
	assertThat(item.getString(),
			allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}
 
Example #25
Source File: FormHttpMessageConverterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void writeMultipart() throws Exception {
	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("name 1", "value 1");
	parts.add("name 2", "value 2+1");
	parts.add("name 2", "value 2+2");
	parts.add("name 3", null);

	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("logo", logo);

	// SPR-12108
	Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
		@Override
		public String getFilename() {
			return "Hall\u00F6le.jpg";
		}
	};
	parts.add("utf8", utf8);

	Source xml = new StreamSource(new StringReader("<root><child/></root>"));
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
	parts.add("xml", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	// SPR-17030
	assertThat(contentType.getParameters().keySet(), Matchers.contains("charset", "boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(6, items.size());
	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("name 1", item.getFieldName());
	assertEquals("value 1", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+1", item.getString());

	item = items.get(2);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+2", item.getString());

	item = items.get(3);
	assertFalse(item.isFormField());
	assertEquals("logo", item.getFieldName());
	assertEquals("logo.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(4);
	assertFalse(item.isFormField());
	assertEquals("utf8", item.getFieldName());
	assertEquals("Hall\u00F6le.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(5);
	assertEquals("xml", item.getFieldName());
	assertEquals("text/xml", item.getContentType());
	verify(outputMessage.getBody(), never()).close();
}
 
Example #26
Source File: MultipartPayloadProvider.java    From camunda-bpm-platform with Apache License 2.0 3 votes vote down vote up
public MultipartFormData readFrom(Class<MultipartFormData> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {

  final MultipartFormData multipartFormData = createMultipartFormDataInstance();
  final FileUpload fileUpload = createFileUploadInstance();

  String contentType = httpHeaders.getFirst("content-type");
  RestMultipartRequestContext requestContext = createRequestContext(entityStream, contentType);

  // parse the request (populates the multipartFormData)
  parseRequest(multipartFormData, fileUpload, requestContext);

  return multipartFormData;

}
 
Example #27
Source File: CommonsFileUploadSupport.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Factory method for a Commons FileUpload instance.
 * <p><b>To be implemented by subclasses.</b>
 * @param fileItemFactory the Commons FileItemFactory to build upon
 * @return the Commons FileUpload instance
 */
protected abstract FileUpload newFileUpload(FileItemFactory fileItemFactory);
 
Example #28
Source File: CommonsFileUploadSupport.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return the underlying {@code org.apache.commons.fileupload.FileUpload}
 * instance. There is hardly any need to access this.
 * @return the underlying FileUpload instance
 */
public FileUpload getFileUpload() {
	return this.fileUpload;
}
 
Example #29
Source File: CommonsMultipartResolver.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Initialize the underlying {@code org.apache.commons.fileupload.servlet.ServletFileUpload}
 * instance. Can be overridden to use a custom subclass, e.g. for testing purposes.
 * @param fileItemFactory the Commons FileItemFactory to use
 * @return the new ServletFileUpload instance
 */
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload(fileItemFactory);
}
 
Example #30
Source File: CommonsFileUploadSupport.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Return the underlying {@code org.apache.commons.fileupload.FileUpload}
 * instance. There is hardly any need to access this.
 * @return the underlying FileUpload instance
 */
public FileUpload getFileUpload() {
	return this.fileUpload;
}