Search in sources :

Example 46 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 47 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 48 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)

Example 49 with MultipartRequestEntity

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

the class TestMultipartPost method testPostFilePartUnknownLength.

public void testPostFilePartUnknownLength() throws Exception {
    this.server.setHttpService(new EchoService());
    String enc = "ISO-8859-1";
    PostMethod method = new PostMethod();
    byte[] content = "Hello".getBytes(enc);
    MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { new FilePart("param1", new TestPartSource("filename.txt", content), "text/plain", enc) }, method.getParams());
    method.setRequestEntity(entity);
    client.executeMethod(method);
    assertEquals(200, method.getStatusCode());
    String body = method.getResponseBodyAsString();
    assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0);
    assertTrue(body.indexOf("Content-Type: text/plain; charset=" + enc) >= 0);
    assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
    assertTrue(body.indexOf("Hello") >= 0);
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Example 50 with MultipartRequestEntity

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

the class MultipartRequest method execute.

/**
 * TODO: make sure we are using the MultipartRequestEntity in the correct
 * manner. The deprecated MultipartPostMethod was very different.
 * @throws IOException
 */
@Override
public void execute() throws IOException {
    ((PostMethod) method).setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));
    super.execute();
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)

Aggregations

MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)63 Part (org.apache.commons.httpclient.methods.multipart.Part)54 PostMethod (org.apache.commons.httpclient.methods.PostMethod)53 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)52 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)44 IOException (java.io.IOException)24 HttpClient (org.apache.commons.httpclient.HttpClient)20 File (java.io.File)16 ArrayList (java.util.ArrayList)16 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)9 Test (org.junit.Test)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 GetMethod (org.apache.commons.httpclient.methods.GetMethod)6 Element (org.jdom.Element)6 HttpException (org.apache.commons.httpclient.HttpException)5 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)5 Map (java.util.Map)4 Header (org.apache.commons.httpclient.Header)4 NameValuePair (org.apache.commons.httpclient.NameValuePair)4