Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity.

Prototype

public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams) 

Source Link

Usage

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given {@link HttpServletRequest}
 * /*from ww  w  . j a  va 2s .c  o  m*/
 * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod}
 */
private void handleMultipart(EntityEnclosingMethod methodProxyRequest, 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(Utils.DEFAULT_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[] {}), methodProxyRequest.getParams());

        methodProxyRequest.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
        // ////////////////////////////////////////////////////////////////////////

        methodProxyRequest.setRequestHeader(Utils.CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());

    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.kaltura.client.KalturaClientBase.java

private PostMethod getPostMultiPartWithFiles(PostMethod method, KalturaParams kparams, KalturaFiles kfiles) {

    String boundary = "---------------------------" + System.currentTimeMillis();
    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary));

    for (Entry<String, String> itr : kparams.entrySet()) {
        parts.add(new StringPart(itr.getKey(), itr.getValue()));
    }//from   w ww . ja  v a2 s.c o m

    for (String key : kfiles.keySet()) {
        final KalturaFile kFile = kfiles.get(key);
        parts.add(new StringPart(key, "filename=" + kFile.getName()));
        if (kFile.getFile() != null) {
            // use the file
            File file = kFile.getFile();
            try {
                parts.add(new FilePart(key, file));
            } catch (FileNotFoundException e) {
                // TODO this sort of leaves the submission in a weird state... -AZ
                if (logger.isEnabled())
                    logger.error("Exception while iterating over kfiles", e);
            }
        } else {
            // use the input stream
            PartSource fisPS = new PartSource() {
                public long getLength() {
                    return kFile.getSize();
                }

                public String getFileName() {
                    return kFile.getName();
                }

                public InputStream createInputStream() throws IOException {
                    return kFile.getInputStream();
                }
            };
            parts.add(new FilePart(key, fisPS));
        }
    }

    Part allParts[] = new Part[parts.size()];
    allParts = parts.toArray(allParts);

    method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams()));

    return method;
}

From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java

/**
 * This is quite ugly has the code is coming from the HTTPClient.
 *
 * @param params/*from   w ww.  j a va2s .c  o  m*/
 * @param methodParams
 * @return
 * @throws java.io.FileNotFoundException
 */
private MultipartRequestEntity createMultipartRequestEntity(List<Part> params, HttpMethodParams methodParams)
        throws FileNotFoundException {
    org.apache.commons.httpclient.methods.multipart.Part[] parts = new org.apache.commons.httpclient.methods.multipart.Part[params
            .size()];
    int i = 0;

    for (Part part : params) {
        if (part instanceof StringPart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.StringPart(part.getName(),
                    ((StringPart) part).getValue(), "UTF-8");
        } else if (part instanceof FilePart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(),
                    ((FilePart) part).getFile(), ((FilePart) part).getMimeType(),
                    ((FilePart) part).getCharSet());

        } else if (part instanceof ByteArrayPart) {
            PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(),
                    ((ByteArrayPart) part).getData());
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(), source,
                    ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet());

        } else if (part == null) {
            throw new NullPointerException("Part cannot be null");
        } else {
            throw new IllegalArgumentException(
                    String.format("Unsupported part type for multipart parameter %s", part.getName()));
        }
        ++i;
    }
    return new MultipartRequestEntity(parts, methodParams);
}

From source file:com.borhan.client.BorhanClientBase.java

private PostMethod getPostMultiPartWithFiles(PostMethod method, BorhanParams kparams, BorhanFiles kfiles) {

    String boundary = "---------------------------" + System.currentTimeMillis();
    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary));

    parts.add(new StringPart("json", kparams.toString()));

    for (String key : kfiles.keySet()) {
        final BorhanFile kFile = kfiles.get(key);
        parts.add(new StringPart(key, "filename=" + kFile.getName()));
        if (kFile.getFile() != null) {
            // use the file
            File file = kFile.getFile();
            try {
                parts.add(new FilePart(key, file));
            } catch (FileNotFoundException e) {
                // TODO this sort of leaves the submission in a weird
                // state... -AZ
                if (logger.isEnabled())
                    logger.error("Exception while iterating over kfiles", e);
            }// ww  w .  ja  v a 2  s.c  om
        } else {
            // use the input stream
            PartSource fisPS = new PartSource() {
                public long getLength() {
                    return kFile.getSize();
                }

                public String getFileName() {
                    return kFile.getName();
                }

                public InputStream createInputStream() throws IOException {
                    return kFile.getInputStream();
                }
            };
            parts.add(new FilePart(key, fisPS));
        }
    }

    Part allParts[] = new Part[parts.size()];
    allParts = parts.toArray(allParts);

    method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams()));

    return method;
}

From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

public static String sendRequest(String url, String epadSessionID, File dicomsZip, File dsosZip,
        String statusURL) throws Exception {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    if (epadSessionID != null)
        postMethod.setRequestHeader("Cookie", "JSESSIONID=" + epadSessionID);
    try {//  w w  w.ja  va  2 s.c om
        Part[] parts = { new FilePart("dicoms", dicomsZip), new FilePart("dsos", dsosZip),
                new StringPart("statusUrl", statusURL) };

        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

        int response = client.executeMethod(postMethod);
        String responseStr = postMethod.getResponseBodyAsString();
        JSONObject responseJson = new JSONObject(responseStr);

        String instanceId = (String) responseJson.get("workflowInstanceID");

        if (response == HttpServletResponse.SC_OK)
            ;
        return instanceId;

    } catch (Exception e) {
        log.warning("Exception calling ePAD", e);
        return null;
    } finally {
        postMethod.releaseConnection();
    }

}

From source file:com.liferay.portal.util.HttpImpl.java

protected void processPostMethod(PostMethod postMethod, List<Http.FilePart> fileParts,
        Map<String, String> parts) {

    if ((fileParts == null) || fileParts.isEmpty()) {
        if (parts != null) {
            for (Map.Entry<String, String> entry : parts.entrySet()) {
                String value = entry.getValue();

                if (Validator.isNotNull(value)) {
                    postMethod.addParameter(entry.getKey(), value);
                }/*w w w. j  ava2s. c  o m*/
            }
        }
    } else {
        List<Part> partsList = new ArrayList<Part>();

        if (parts != null) {
            for (Map.Entry<String, String> entry : parts.entrySet()) {
                String value = entry.getValue();

                if (Validator.isNotNull(value)) {
                    StringPart stringPart = new StringPart(entry.getKey(), value);

                    partsList.add(stringPart);
                }
            }
        }

        for (Http.FilePart filePart : fileParts) {
            partsList.add(toCommonsFilePart(filePart));
        }

        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                partsList.toArray(new Part[0]), postMethod.getParams());

        postMethod.setRequestEntity(multipartRequestEntity);
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;//  w ww . j a  v  a2s  . co m
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java

/**
 * Makes a Multi-part POST request to the URL. Reads data back and
 * returns the data read. Note that this method only works with text
 * data as it does the byte-to-char conversion. This method will return
 * null for responses with binary MIME types. The addTextType(String)
 * method is used to register additional MIME types as text types.
 * Use getContentSize() to obtain the bytes of binary data read.
 *
 * @param url The URL to read from//from  w w w.  j  av a 2s .c om
 * @param parts The parts list
 * @param headers The request headers
 * @return The StringBuilder buffer containing the resulting document
 * @throws java.io.IOException
 */
public StringBuilder fetchURL(String url, List<Part> parts, Map<String, String> headers) throws IOException {

    Part[] partsArray = parts.toArray(new Part[parts.size()]);
    PostMethod method = new PostMethod(url);
    method.setFollowRedirects(followRedirects);
    setHeaders(method, headers);
    method.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
    try {
        responseCode = hc.executeMethod(method);
        buildResponseHeaders(method);
        return fetchResponse(method);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach)
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        authenticate();//from ww  w. j av a2s .c  o  m
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach,
        IProgressMonitor monitor)//  w w w  .  j a v  a 2 s.co m
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        monitor.subTask("Authenticating request");
        authenticate();
        if (checkMonitor(monitor))
            return null;
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    monitor.subTask("Sending request");
    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}