List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity getContentType
public String getContentType()
From source file:net.formio.portlet.MockPortletRequests.java
/** * Creates new portlet request that contains given resource as multi part. * @param paramName//from www . j a v a 2s . co m * @param resourceName * @return */ public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockMultipartActionRequest request = new MockMultipartActionRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:net.formio.servlet.MockServletRequests.java
/** * Creates new servlet request that contains given resource as multi part. * @param paramName//w w w. j a v a2 s . co m * @param resourceName * @return */ public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockHttpServletRequest request = new MockHttpServletRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); request.setMethod("POST"); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:edu.unc.lib.dl.cdr.sword.server.test.DepositClientsByHand.java
@Test public void testUpload() throws Exception { String user = ""; String password = ""; String pid = "uuid:c9aba0a2-12e9-4767-822e-b285a37b07d7"; String payloadMimeType = "text/xml"; String payloadPath = "src/test/resources/dcDocument.xml"; String metadataPath = "src/test/resources/atompubMODS.xml"; String depositPath = "https://localhost:444/services/sword/collection/"; String testSlug = "ingesttestslug"; HttpClient client = HttpClientUtil.getAuthenticatedClient(depositPath + pid, user, password); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(depositPath + pid); File payload = new File(payloadPath); File atom = new File(metadataPath); FilePart payloadPart = new FilePart("payload", payload); payloadPart.setContentType(payloadMimeType); payloadPart.setTransferEncoding("binary"); Part[] parts = { payloadPart, new FilePart("atom", atom, "application/atom+xml", "utf-8") }; MultipartRequestEntity mpEntity = new MultipartRequestEntity(parts, post.getParams()); String boundary = mpEntity.getContentType(); boundary = boundary.substring(boundary.indexOf("boundary=") + 9); Header header = new Header("Content-type", "multipart/related; type=application/atom+xml; boundary=" + boundary); post.addRequestHeader(header);// ww w .j ava2s . c om Header slug = new Header("Slug", testSlug); post.addRequestHeader(slug); post.setRequestEntity(mpEntity); LOG.debug("" + client.executeMethod(post)); }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */// w ww .ja v a 2s. c o m @SuppressWarnings("unchecked") public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string // part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:net.sf.j2ep.test.PostTest.java
public void beginSendMultipart(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/POST/multipart.jsp", null, null); theRequest.addParameter("tmp", "", WebRequest.POST_METHOD); try {//from ww w . java2 s . co m PostMethod post = new PostMethod(); FilePart filePart = new FilePart("theFile", new File("WEB-INF/classes/net/sf/j2ep/test/POSTdata")); StringPart stringPart = new StringPart("testParam", "123456"); Part[] parts = new Part[2]; parts[0] = stringPart; parts[1] = filePart; MultipartRequestEntity reqEntitiy = new MultipartRequestEntity(parts, post.getParams()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); reqEntitiy.writeRequest(outStream); theRequest.setUserData(new ByteArrayInputStream(outStream.toByteArray())); theRequest.addHeader("content-type", reqEntitiy.getContentType()); } catch (FileNotFoundException e) { fail("File was not found " + e.getMessage()); } catch (IOException e) { fail("IOException"); e.printStackTrace(); } }
From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java
private MockHttpServletRequest getMultipartRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); byte[] fileContent = new byte[] { 1, 2, 3 }; Part[] parts = new Part[] { new FilePart("file1", new ByteArrayPartSource("file1", fileContent)) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); // Serialize request body ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); // Set request body to HTTP servlet request request.setContent(requestContent.toByteArray()); // Set content type to HTTP servlet request (important, includes Mime boundary string) request.setContentType(multipartRequestEntity.getContentType()); request.setMethod("POST"); return request; }
From source file:ch.sportchef.business.event.bundary.EventImageResourceTest.java
@Test public void uploadImageWithOK() throws IOException, ServletException { // arrange// ww w . ja v a 2 s .c om final byte[] fileContent = readTestImage(); final Part[] parts = new Part[] { new FilePart(TEST_IMAGE_NAME, new ByteArrayPartSource(TEST_IMAGE_NAME, fileContent)) }; final MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); final ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); final ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.toByteArray()); final ServletInputStreamMock inputStreamMock = new ServletInputStreamMock(inputStream); final String contentType = multipartRequestEntity.getContentType(); expect(httpServletRequest.getContentType()).andStubReturn(contentType); expect(httpServletRequest.getInputStream()).andStubReturn(inputStreamMock); eventImageServiceMock.uploadImage(anyLong(), anyObject()); mockProvider.replayAll(); // act final Response response = eventImageResource.uploadImage(httpServletRequest); // assert assertThat(response.getStatus(), is(OK.getStatusCode())); mockProvider.verifyAll(); }
From source file:eu.impact_project.iif.t2.client.HelperTest.java
/** * Test of parseRequest method, of class Helper. *//*www. j a v a 2 s .c o m*/ @Test public void testParseRequest() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); URL url = this.getClass().getResource("/prueba.txt"); File testFile = new File(url.getFile()); Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile), new FilePart("comon_file", testFile) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray()); when(request.getInputStream()).thenReturn(new ServletInputStream() { @Override public int read() throws IOException { return inputContent.read(); } }); when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType()); Helper.parseRequest(request); }
From source file:info.magnolia.cms.filters.MultipartRequestFilterTest.java
public void doTest(Filter filter, final String expectedDocumentType) throws Throwable { final MultipartRequestEntity multipart = newMultipartRequestEntity(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); multipart.writeRequest(output);/* w ww . jav a 2 s. c o m*/ final byte[] bytes = output.toByteArray(); final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes); final ServletInputStream servletInputStream = new ServletInputStream() { @Override public int read() throws IOException { return delegateStream.read(); } }; req.setAttribute(isA(String.class), isA(Boolean.class)); expect(req.getContentType()).andReturn(multipart.getContentType()).anyTimes(); expect(req.getHeader("Content-Type")).andReturn(multipart.getContentType()).anyTimes(); expect(req.getCharacterEncoding()).andReturn("UTF-8").anyTimes(); expect(req.getQueryString()).andReturn("").anyTimes(); expect(req.getContentLength()).andReturn(Integer.valueOf((int) multipart.getContentLength())).anyTimes(); expect(req.getInputStream()).andReturn(servletInputStream); req.setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { final Object[] args = getCurrentArguments(); checkMultipartForm((MultipartForm) args[1], expectedDocumentType); return null; } }); webCtx.pop(); replay(req, res, filterChain, webCtx); filter.doFilter(req, res, filterChain); verify(req, res, filterChain, webCtx); }
From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java
@SuppressWarnings("deprecation") HttpRequest construct(Request request, HttpMethod m, Url url) throws IOException { String host = url.getHost();/*w ww . jav a 2s .c om*/ if (request.getVirtualHost() != null) { host = request.getVirtualHost(); } HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, url.getPath()); nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + url.getPort()); Headers h = request.getHeaders(); if (h != null) { Iterator<Pair<String, String>> i = h.iterator(); Pair<String, String> p; while (i.hasNext()) { p = i.next(); if ("host".equalsIgnoreCase(p.getFirst())) { continue; } String key = p.getFirst() == null ? "" : p.getFirst(); String value = p.getSecond() == null ? "" : p.getSecond(); nettyRequest.setHeader(key, value); } } String ka = config.getKeepAlive() ? "keep-alive" : "close"; nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka); if (config.getProxyServer() != null) { nettyRequest.setHeader("Proxy-Connection", ka); } if (config.getUserAgent() != null) { nettyRequest.setHeader("User-Agent", config.getUserAgent()); } if (request.getCookies() != null && !request.getCookies().isEmpty()) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } if (config.isCompressionEnabled()) { nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } switch (request.getType()) { case POST: if (request.getByteData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData())); } else if (request.getStringData() != null) { // TODO: Not sure we need to reconfigure that one. nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().length())); nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8")); } else if (request.getStreamData() != null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStreamData().available())); byte[] b = new byte[(int) request.getStreamData().available()]; request.getStreamData().read(b); nettyRequest.setContent(ChannelBuffers.copiedBuffer(b)); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Entry<String, String> param : request.getParams().entrySet()) { sb.append(param.getKey()); sb.append("="); sb.append(param.getValue()); sb.append("&"); } sb.deleteCharAt(sb.length() - 1); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes())); } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERRED_BYTES; } /** * This is quite ugly to mix and match with Apache Client, * but the fastest way for now * TODO: Remove this dependency. */ PostMethod post = new PostMethod(request.getUrl()); MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), post.getParams()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) lenght); mre.writeRequest(new ChannelBufferOutputStream(b)); nettyRequest.setContent(b); } else if (request.getEntityWriter() != null) { computeAndSetContentLength(request, nettyRequest); ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) request.getLength()); request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b)); nettyRequest.setContent(b); } break; case PUT: if (request.getByteData() != null) { nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8")); } break; } if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) { nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "txt/html; charset=utf-8"); } if (log.isDebugEnabled()) log.debug("Constructed request: " + nettyRequest); return nettyRequest; }