Search in sources :

Example 41 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project camel by apache.

the class MultiPartFormWithCustomFilterTest method testSendMultiPartForm.

@Test
public void testSendMultiPartForm() throws Exception {
    HttpClient httpclient = new HttpClient();
    File file = new File("src/main/resources/META-INF/NOTICE.txt");
    PostMethod httppost = new PostMethod("http://localhost:" + getPort() + "/test");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) };
    MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams());
    httppost.setRequestEntity(reqEntity);
    int status = httpclient.executeMethod(httppost);
    assertEquals("Get a wrong response status", 200, status);
    String result = httppost.getResponseBodyAsString();
    assertEquals("Get a wrong result", "A binary file of some kind", result);
    assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter"));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) File(java.io.File) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Test(org.junit.Test)

Example 42 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project camel by apache.

the class HttpBridgeMultipartRouteTest method testHttpClient.

@Test
public void testHttpClient() throws Exception {
    File jpg = new File("src/test/resources/java.jpg");
    String body = "TEST";
    Part[] parts = new Part[] { new StringPart("body", body), new FilePart(jpg.getName(), jpg) };
    PostMethod method = new PostMethod("http://localhost:" + port2 + "/test/hello");
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(requestEntity);
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String responseBody = method.getResponseBodyAsString();
    assertEquals(body, responseBody);
    String numAttachments = method.getResponseHeader("numAttachments").getValue();
    assertEquals(numAttachments, "2");
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) File(java.io.File) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Test(org.junit.Test)

Example 43 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project xwiki-platform by xwiki.

the class StoreTestUtils method doUpload.

public static HttpMethod doUpload(final String address, final UsernamePasswordCredentials userNameAndPassword, final Map<String, byte[]> uploads) throws IOException {
    final HttpClient client = new HttpClient();
    final PostMethod method = new PostMethod(address);
    if (userNameAndPassword != null) {
        client.getState().setCredentials(AuthScope.ANY, userNameAndPassword);
        client.getParams().setAuthenticationPreemptive(true);
    }
    Part[] parts = new Part[uploads.size()];
    int i = 0;
    for (Map.Entry<String, byte[]> e : uploads.entrySet()) {
        parts[i++] = new FilePart("filepath", new ByteArrayPartSource(e.getKey(), e.getValue()));
    }
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);
    client.executeMethod(method);
    return method;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) Map(java.util.Map) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)

Example 44 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project fabric8 by jboss-fuse.

the class ProxyServlet method handleMultipartPost.

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 */
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // 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(// The field name
                fileItemCurrent.getFieldName(), // The field value
                fileItemCurrent.getString());
                // 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(// The field name
                fileItemCurrent.getFieldName(), new ByteArrayPartSource(// The uploaded file name
                fileItemCurrent.getName(), // The uploaded file contents
                fileItemCurrent.get()));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.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
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}
Also used : ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) ArrayList(java.util.ArrayList) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 45 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUploadWithMimeMultipartFormData.

@Test
public void testUploadWithMimeMultipartFormData() throws Exception {
    new File("target/maven/proxy/tmp/multipart").mkdirs();
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
    addEntry(jas, "META-INF/maven/io.fabric8/mybundle/pom.properties", "groupId=io.fabric8\nartifactId=mybundle\nversion=1.0\n".getBytes());
    jas.close();
    byte[] jarBytes = baos.toByteArray();
    RuntimeProperties props = new MockRuntimeProperties();
    MavenResolver resolver = EasyMock.createMock(MavenResolver.class);
    MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
    servlet.setFileItemFactory(new DiskFileItemFactory(0, new File("target/maven/proxy/tmp/multipart")));
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    FilePart part = new FilePart("file[]", new ByteArrayPartSource("mybundle-1.0.jar", jarBytes));
    MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { part }, new HttpMethodParams());
    final ByteArrayOutputStream requestBytes = new ByteArrayOutputStream();
    entity.writeRequest(requestBytes);
    final byte[] multipartRequestBytes = requestBytes.toByteArray();
    EasyMock.expect(request.getPathInfo()).andReturn("/mybundle-1.0.jar");
    EasyMock.expect(request.getHeader(MavenProxyServletSupport.LOCATION_HEADER)).andReturn(null);
    EasyMock.expect(request.getParameter("profile")).andReturn("my");
    EasyMock.expect(request.getParameter("version")).andReturn("1.0");
    EasyMock.expect(request.getContentType()).andReturn(entity.getContentType()).anyTimes();
    EasyMock.expect(request.getHeader("Content-length")).andReturn(Long.toString(entity.getContentLength())).anyTimes();
    EasyMock.expect(request.getContentLength()).andReturn((int) entity.getContentLength()).anyTimes();
    EasyMock.expect(request.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes();
    Capture<String> location = EasyMock.newCapture(CaptureType.ALL);
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
    EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

        private int pos = 0;

        @Override
        public int read() throws IOException {
            return pos >= multipartRequestBytes.length ? -1 : (multipartRequestBytes[pos++] & 0xFF);
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    });
    Capture<ProjectRequirements> requirementsCapture = EasyMock.newCapture(CaptureType.FIRST);
    EasyMock.expect(projectDeployer.deployProject(EasyMock.capture(requirementsCapture), EasyMock.eq(true))).andReturn(null);
    EasyMock.replay(resolver, request, response, projectDeployer);
    servlet.doPut(request, response);
    FileInputStream fis = new FileInputStream("target/upload/io.fabric8/mybundle/1.0/mybundle-1.0.jar");
    ByteArrayOutputStream storedBundleBytes = new ByteArrayOutputStream();
    IOUtils.copy(fis, storedBundleBytes);
    fis.close();
    Assert.assertArrayEquals(jarBytes, storedBundleBytes.toByteArray());
    ProjectRequirements pr = requirementsCapture.getValue();
    List<String> bundles = pr.getBundles();
    assertThat(bundles.size(), equalTo(1));
    assertThat(bundles.get(0), equalTo("mvn:io.fabric8/mybundle/1.0"));
    assertThat(pr.getProfileId(), equalTo("my"));
    assertThat(pr.getVersion(), equalTo("1.0"));
    assertThat(pr.getGroupId(), nullValue());
    assertThat(pr.getArtifactId(), nullValue());
    EasyMock.verify(resolver, request, response, projectDeployer);
}
Also used : ReadListener(javax.servlet.ReadListener) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) ProjectRequirements(io.fabric8.deployer.dto.ProjectRequirements) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) JarOutputStream(java.util.jar.JarOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) FileInputStream(java.io.FileInputStream) File(java.io.File)

Aggregations

MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)55 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)46 Part (org.apache.commons.httpclient.methods.multipart.Part)46 PostMethod (org.apache.commons.httpclient.methods.PostMethod)45 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)37 IOException (java.io.IOException)20 File (java.io.File)14 ArrayList (java.util.ArrayList)13 HttpClient (org.apache.commons.httpclient.HttpClient)13 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 Test (org.junit.Test)8 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 Map (java.util.Map)6 GetMethod (org.apache.commons.httpclient.methods.GetMethod)6 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)5 FileNotFoundException (java.io.FileNotFoundException)4 Header (org.apache.commons.httpclient.Header)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 EngineException (com.twinsoft.convertigo.engine.EngineException)3