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:org.pmedv.core.util.UploadUtils.java

public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor,
        String requestParams) {//from  ww w .java 2  s  .co  m

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("remoting.properties");
    Properties uploadProps = new Properties();

    try {
        uploadProps.load(is);
    } catch (IOException e) {
        log.info("Could not load upload.properties, is it in classpath?");
        return false;
    }

    log.info("uploading " + sourceFile + " to " + targetURL);

    PostMethod filePost = new PostMethod(targetURL + requestParams);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    try {

        Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            log.info("Upload failed, response=" + HttpStatus.getStatusText(status));
            return false;
        }

    } catch (Exception ex) {
        log.error("An exception occured :");
        log.error(ResourceUtils.getStackTrace(ex));
        return false;
    } finally {
        filePost.releaseConnection();
    }

    return true;

}

From source file:org.proteomecommons.tranche.modules.bioxmlrender.Main.java

private static void renderBioMLUsingTheGPM(final File file, final boolean delete) throws Exception {

    final IndeterminateProgressBar progress = new IndeterminateProgressBar("Uploading file to the GPM.org...");

    Thread t = new Thread() {
        public void run() {
            progress.setLocationRelativeTo(GUIUtil.getAdvancedGUI());
            progress.start();//from w ww  . j  a v  a  2s. c  om
        }
    };
    SwingUtilities.invokeLater(t);

    PostMethod postMethod = null;
    BufferedReader in = null;
    BufferedWriter out = null;
    File temp = TempFileUtil.createTemporaryFile(".html");
    FileReader reader = null;
    FileWriter writer = null;

    try {
        HttpClient client = new HttpClient();
        postMethod = new PostMethod("http://gpmdb.thegpm.org/thegpm-cgi/upview.pl");

        // Hack for file part
        File normalFileHack = file;

        Part[] parts = { new FilePart("spectrum, path", normalFileHack) };

        postMethod.setRequestHeader("Content-type", "multipart/form-data");
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

        int statusCode1 = client.executeMethod(postMethod);

        if (statusCode1 == 200) {

            in = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
            out = new BufferedWriter(new FileWriter(temp));

            // Write to temp file
            String str = null;
            final String host = "http://gpmdb.thegpm.org/";
            while ((str = in.readLine()) != null) {

                if (str.contains("/thegpm-cgi")) {
                    str = str.replace("/thegpm-cgi", host + "thegpm-cgi");
                }

                if (str.contains("src=\"/")) {
                    str = str.replace("src=\"/", "src=\"" + host);
                }

                if (str.contains("href=\"/")) {
                    str = str.replace("href=\"/", "href=\"" + host);
                }

                out.write(str + Text.getNewLine());
            }

            out.flush();
            IOUtil.safeClose(in);
            IOUtil.safeClose(out);
            in = null;
            out = null; // Already closed

            progress.stop();

            GUIUtil.displayURL(GUIUtil.createSafeURL("file://" + temp.getAbsolutePath()));

            // Give browser chance to read the file
            Thread.sleep(3000);
        }

        else {
            JOptionPane.showMessageDialog(GUIUtil.getAdvancedGUI(),
                    "There was a problem processing your request: " + postMethod.getStatusText(),
                    "Bad request for TheGPM.org", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
    }

    finally {

        progress.stop();

        if (postMethod != null) {
            postMethod.releaseConnection();
        }

        if (in != null) {
            IOUtil.safeClose(in);
        }

        if (out != null) {
            IOUtil.safeClose(out);
        }

        IOUtil.safeDelete(temp);

        if (delete) {
            IOUtil.safeDelete(file);
        }
    }

}

From source file:org.ramadda.util.HttpFormField.java

/**
 * _more_//from  w w  w.j a  v a  2s . c  om
 *
 * @param entries _more_
 * @param urlPath _more_
 *
 * @return _more_
 */
private static PostMethod getMethod(List entries, String urlPath) {
    PostMethod postMethod = new PostMethod(urlPath);
    boolean anyFiles = false;
    int count = 0;
    List goodEntries = new ArrayList();
    for (int i = 0; i < entries.size(); i++) {
        HttpFormField formEntry = (HttpFormField) entries.get(i);
        if (!formEntry.okToPost()) {
            continue;
        }
        goodEntries.add(entries.get(i));
        if (formEntry.type == TYPE_FILE) {
            anyFiles = true;
        }
    }

    if (anyFiles) {
        Part[] parts = new Part[goodEntries.size()];
        for (int i = 0; i < goodEntries.size(); i++) {
            HttpFormField formEntry = (HttpFormField) goodEntries.get(i);
            if (formEntry.type == TYPE_FILE) {
                parts[i] = formEntry.getFilePart();
            } else {
                //Not sure why but we have seen a couple of times
                //the byte value '0' gets into one of these strings
                //This causes an error in the StringPart.
                //                    System.err.println("
                String value = formEntry.getValue();
                char with = new String(" ").charAt(0);
                while (value.indexOf(0) >= 0) {
                    value = value.replace((char) 0, with);
                }
                parts[i] = new StringPart(formEntry.getName(), value);
            }
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
    } else {
        for (int i = 0; i < goodEntries.size(); i++) {
            HttpFormField formEntry = (HttpFormField) goodEntries.get(i);
            postMethod.addParameter(new NameValuePair(formEntry.getName(), formEntry.getValue()));
        }
    }

    return postMethod;
}

From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java

@Override
public void create(String filename, InputStream inputStream, OutputStream outputStream,
        PdfaPilotTransformationOptions options) {
    HttpClient client = getHttpClient();

    String pdfaLevel = options != null ? options.getLevel() : "";
    String variant = StringUtils.isBlank(pdfaLevel) ? "pdf" : "pdfa";
    String url = _serverUrl + "/bapi/v1/create/" + variant;

    if (LOG.isDebugEnabled()) {
        LOG.debug(url);/*  ww  w  .java 2  s.c  o  m*/
    }

    PostMethod method = new PostMethod(url);
    method.getParams().setSoTimeout(_aliveCheckTimeout * 1000);
    method.getHostAuthState().setPreemptive();
    method.getParams().setContentCharset("UTF-8");

    method.addRequestHeader("Accept-Charset", "UTF-8");
    method.addRequestHeader("Accept-Language", "en-ca,en;q=0.8");
    // method.addRequestHeader("Accept-Content", "application/text");

    try {
        JSONObject json = new JSONObject();
        json.put("nodeRef",
                options != null && options.getSourceNodeRef() != null ? options.getSourceNodeRef().toString()
                        : null);

        // create a new array of Part objects
        List<Part> parts = new ArrayList<Part>();

        // add the file part, the actual binary data
        parts.add(new FilePart("file",
                new ByteArrayPartSource(FilenameUtils.getName(filename), IOUtils.toByteArray(inputStream)),
                null, "UTF-8"));

        // add the filename part
        parts.add(new StringPart("filename", FilenameUtils.getName(filename), "UTF-8"));

        // *if* there's a pdfaLavel part, and that
        if (StringUtils.isNotBlank(pdfaLevel)) {
            parts.add(new StringPart("level", pdfaLevel, "UTF-8"));
        }

        // and last, add the data part, this is a json object
        parts.add(new StringPart("data", json.toString(), "UTF-8"));

        method.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), method.getParams()));

        int status = client.executeMethod(method);

        if (status != 200) {
            throw new RuntimeException("Create PDF failed: " + method.getStatusLine() + "\n"
                    + method.getResponseBodyAsString().trim());
        }

        IOUtils.copy(method.getResponseBodyAsStream(), outputStream);
    } catch (Throwable e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        method.releaseConnection();

        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java

@Override
public CreateResult create(String filename, File sourceFile, PdfaPilotTransformationOptions options) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating PDF from '" + sourceFile.getAbsolutePath() + "' with filename '" + filename + "'.");
    }/*from w w  w.j  a v a 2 s .  c  o m*/

    HttpClient client = getHttpClient();

    String pdfaLevel = options != null ? options.getLevel() : null;

    String variant = StringUtils.isNotBlank(pdfaLevel) ? "pdfa" : "pdf";

    PostMethod method = new PostMethod(_serverUrl + "/bapi/v1/create/" + variant);
    method.getParams().setSoTimeout(_aliveCheckTimeout * 1000);
    method.getHostAuthState().setPreemptive();
    method.getParams().setContentCharset("UTF-8");

    method.addRequestHeader("Accept-Charset", "UTF-8");
    method.addRequestHeader("Accept-Language", "en-ca,en;q=0.8");
    method.addRequestHeader("Accept-Content", "application/text");
    method.addRequestHeader("Accept", "application/json, */*");

    try {
        JSONObject json = new JSONObject();
        json.put("nodeRef",
                options != null && options.getSourceNodeRef() != null ? options.getSourceNodeRef().toString()
                        : null);

        // create a new array of Part objects
        List<Part> parts = new ArrayList<Part>();

        parts.add(new FilePart("file", sourceFile, null, "UTF-8"));
        parts.add(new StringPart("filename", filename, "UTF-8"));

        // *if* there's a pdfaLavel part, and that
        if (StringUtils.isNotBlank(pdfaLevel)) {
            parts.add(new StringPart("level", pdfaLevel, "UTF-8"));
        }

        parts.add(new StringPart("data", json.toString(), "UTF-8"));

        method.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), method.getParams()));

        int status = client.executeMethod(method);

        if (status != 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create PDF failed: " + method.getStatusLine() + "\n"
                        + method.getResponseBodyAsString().trim());
            }

            throw new RuntimeException("Create PDF failed: " + method.getStatusLine() + "\n"
                    + method.getResponseBodyAsString().trim());
        }

        File destination = TempFileProvider.createTempFile("pdfaPilot", ".pdf");

        FileUtils.copyInputStreamToFile(method.getResponseBodyAsStream(), destination);
        String id = method.getResponseHeader(PdfaPilotClient.RESPONSE_ID_HEADER).getValue();

        return new CreateResult(destination, id);
    } catch (Exception e) {
        throw new RuntimeException("Create PDF failed\n", e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java

@Override
public String create(String filename, ContentReader contentReader, ContentWriter contentWriter,
        PdfaPilotTransformationOptions options) {
    HttpClient client = getHttpClient();

    String pdfaLevel = options != null ? options.getLevel() : null;

    String variant = StringUtils.isNotBlank(pdfaLevel) ? "pdfa" : "pdf";

    PostMethod method = new PostMethod(_serverUrl + "/bapi/v1/create/" + variant);

    method.getParams().setSoTimeout(_aliveCheckTimeout * 1000);
    method.getHostAuthState().setPreemptive();
    method.getParams().setContentCharset("UTF-8");

    method.addRequestHeader("Accept-Charset", "UTF-8");
    method.addRequestHeader("Accept-Language", "en-ca,en;q=0.8");
    method.addRequestHeader("Accept-Content", "application/text");

    try {//  www . j a v a  2  s  .c  om
        JSONObject json = new JSONObject();
        json.put("nodeRef", options.getSourceNodeRef());

        Part[] parts = new Part[4];

        parts[0] = new FilePart("file", new ContentReaderPartSource(filename, contentReader), null, "UTF-8");
        parts[1] = new StringPart("filename", FilenameUtils.getName(filename), "UTF-8");
        parts[2] = new StringPart("level", pdfaLevel, "UTF-8");
        parts[3] = new StringPart("data", json.toString(), "UTF-8");

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

        int status = client.executeMethod(method);

        if (status != 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create PDF failed: " + method.getStatusLine() + "\n"
                        + method.getResponseBodyAsString().trim());
            }

            throw new RuntimeException("Create PDF failed: " + method.getStatusLine() + "\n"
                    + method.getResponseBodyAsString().trim());
        }

        contentWriter.putContent(method.getResponseBodyAsStream());

        return method.getRequestHeader(RESPONSE_ID_HEADER).getValue();
    } catch (Exception ex) {
        throw new RuntimeException("Create PDF failed\n", ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

public String executePost(String url, Map<String, String> parameters, List<UploadItem> uploadItems,
        IProgressMonitor monitor) throws ReviewboardException {

    PostMethod postRequest = new PostMethod(stripSlash(location.getUrl()) + url);
    configureRequestForJson(postRequest);
    List<Part> parts = new ArrayList<Part>();

    for (Map.Entry<String, String> paramEntry : parameters.entrySet())
        parts.add(new StringPart(paramEntry.getKey(), paramEntry.getValue()));

    for (UploadItem uploadItem : uploadItems) {

        String partName = uploadItem.getName();

        parts.add(new FilePart(partName,
                new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getContent())));
    }/* w  ww .jav a 2s. c  o m*/

    postRequest.setRequestEntity(
            new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postRequest.getParams()));

    return executeMethod(postRequest, monitor);
}

From source file:org.safecreative.api.RegisterWork.java

/**
 * Post data using an instance of <code>PartSource</code>
 * @param uploadUrl//from   w w w .  j  av a2s .c om
 * @param params
 * @param file <code>PartSource</code> to upload
 * @return uploadticket
 */
public String postFile(String uploadUrl, Map<String, String> params, final PartSource file) {
    PostMethod post = null;
    try {
        log.debug(String.format("api request by post: \n%s/%s\n", uploadUrl, file.getFileName()));
        if (client == null) {
            client = new HttpClient();
        }
        post = new PostMethod(uploadUrl);
        Part[] parts = new Part[params.size() + 1];
        int i = 0;
        for (Map.Entry<String, String> param : params.entrySet()) {
            parts[i++] = new StringPart(param.getKey(), param.getValue(), SafeCreativeAPI.DEFAULT_ENCODING);
        }
        parts[i] = new FilePart("file", file, "application/octet-stream", SafeCreativeAPI.DEFAULT_ENCODING) {

            @Override
            protected void sendData(OutputStream out) throws IOException {
                if (uploadProgressListener == null) {
                    super.sendData(out);
                } else {
                    super.sendData(new PostUploadProgressListenerOutputStream(out, uploadProgressListener,
                            file.getLength()));
                }
            }

        };
        MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(entity);
        int status = client.executeMethod(post);
        if (status != HttpURLConnection.HTTP_OK) {
            throw new IOException("Response error " + status);
        }

        return post.getResponseBodyAsString();

    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a map of
 * properties to populate that template with. An example might be a SOAP call.
 *
 * <pre>//from   w w  w  . j av  a  2 s. co  m
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 *
 * </pre>
 *
 * @param resource
 *          the resource containing the proxy end point specification.
 * @param headers
 *          a map of headers to set int the request.
 * @param input
 *          a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *          containing the request body (can be null if the call requires no body or the
 *          template will be used to generate the body)
 * @param requestContentLength
 *          if the requestImputStream is specified, the length specifies the lenght of
 *          the body.
 * @param requerstContentType
 *          the content type of the request, if null the node property
 *          sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            if (isUnsafeProxyDefinition(node)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            // Find all velocity replacement variable(s) in the endpointURL,
            // copy any equivalent keys from the input Map, to a new Map that
            // can be process by Velocity. In the new Map, the Map value field
            // has been changed from RequestParameter[] to String.

            Map<String, String> inputContext = new HashMap<String, String>();

            int startPosition = endpointURL.indexOf("${");
            while (startPosition > -1) {
                int endPosition = endpointURL.indexOf("}", startPosition);
                if (endPosition > -1) {
                    String key = endpointURL.substring(startPosition + 2, endPosition);
                    Object value = input.get(key);
                    if (value instanceof RequestParameter[]) {
                        // now change input value object from RequestParameter[] to String
                        // and add to inputContext Map.
                        RequestParameter[] requestParameters = (RequestParameter[]) value;
                        inputContext.put(key, requestParameters[0].getString());
                    } else {
                        // KERN-1346 regression; see KERN-1409
                        inputContext.put(key, String.valueOf(value));
                    }
                    // look for the next velocity replacement variable
                    startPosition = endpointURL.indexOf("${", endPosition);
                } else {
                    break;
                }
            }

            VelocityContext context = new VelocityContext(inputContext);

            // add in the config properties from the bundle overwriting everythign else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString());
                } catch (Exception e) {
                    logger.debug("The Proxy request specified by  " + node + " failed, cause follows:", e);
                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) {
                    long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong();
                    method = new HeadMethod(endpointURL);
                    HttpMethodParams params = new HttpMethodParams(method.getParams());
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    method.setParams(params);
                    method.setFollowRedirects(true);
                    populateMethod(method, node, headers);
                    int result = httpClient.executeMethod(method);
                    if (externalAuthenticatingProxy && result == 407) {
                        method.releaseConnection();
                        method.setDoAuthentication(true);
                        result = httpClient.executeMethod(method);
                    }
                    if (result == 200) {
                        // Check if the content-length is smaller than the maximum (if any).
                        Header contentLengthHeader = method.getResponseHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", method);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(result, method);
                    }
                }
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case HEAD:
                method = new HeadMethod(endpointURL);
                HttpMethodParams params = new HttpMethodParams(method.getParams());
                // make certain we reject the body of a head
                params.setBooleanParameter("http.protocol.reject-head-body", true);
                method.setParams(params);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case OPTIONS:
                method = new OptionsMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case POST:
                method = new PostMethod(endpointURL);
                break;
            case PUT:
                method = new PutMethod(endpointURL);
                break;
            default:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);

            }

            populateMethod(method, node, headers);

            if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof PostMethod) {
                    PostMethod postMethod = (PostMethod) method;
                    ArrayList<Part> parts = new ArrayList<Part>();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof RequestParameter[]) {
                            for (RequestParameter val : (RequestParameter[]) param.getValue()) {
                                Part part = null;
                                if (val.isFormField()) {
                                    part = new StringPart(param.getKey(), val.getString());
                                } else {
                                    ByteArrayPartSource source = new ByteArrayPartSource(key, val.get());
                                    part = new FilePart(key, source);
                                }
                                parts.add(part);
                            }
                        } else {
                            parts.add(new StringPart(key, value.toString()));
                        }
                        Part[] partsArray = parts.toArray(new Part[parts.size()]);
                        postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
                    }
                }
            } else {

                if (method instanceof EntityEnclosingMethod) {
                    String contentType = requestContentType;
                    if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) {
                        contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString();

                    }
                    if (contentType == null) {
                        contentType = APPLICATION_OCTET_STREAM;
                    }
                    EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method;
                    if (requestInputStream != null) {
                        eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream,
                                requestContentLength, contentType));
                    } else {
                        // build the request
                        Template template = velocityEngine.getTemplate(node.getPath());
                        StringWriter body = new StringWriter();
                        template.merge(context, body);
                        byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                        eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType));

                    }
                }
            }

            int result = httpClient.executeMethod(method);
            if (externalAuthenticatingProxy && result == 407) {
                method.releaseConnection();
                method.setDoAuthentication(true);
                result = httpClient.executeMethod(method);
            }
            if (result == 302 && method instanceof EntityEnclosingMethod) {
                // handle redirects on post and put
                String url = method.getResponseHeader("Location").getValue();
                method = new GetMethod(url);
                method.setFollowRedirects(true);
                method.setDoAuthentication(false);
                result = httpClient.executeMethod(method);
                if (externalAuthenticatingProxy && result == 407) {
                    method.releaseConnection();
                    method.setDoAuthentication(true);
                    result = httpClient.executeMethod(method);
                }
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (ProxyClientException e) {
        throw e;
    } catch (Exception e) {
        throw new ProxyClientException("The Proxy request specified by  " + node + " failed, cause follows:",
                e);
    } finally {
        unbindNode();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + node + " does not contain a valid endpoint specification ");
}

From source file:org.seasar.cubby.controller.impl.MultipartRequestParserImplMultipartRequestTest.java

@Test
public void getParameterMap() throws Exception {
    final PartSource filePartSource = new ByteArrayPartSource("upload.txt", "upload test".getBytes("UTF-8"));
    final PostMethod method = new PostMethod();
    final Part[] parts = new Part[] { new StringPart("a", "12345"), new StringPart("b", "abc"),
            new StringPart("b", "def"), new FilePart("file", filePartSource) };
    this.entity = new MultipartRequestEntity(parts, method.getParams());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    this.entity.writeRequest(out);
    out.flush();/*from  w w w.  ja  v a  2  s  .co m*/
    out.close();
    this.input = new ByteArrayInputStream(out.toByteArray());
    this.attributes.put("c", new String[] { "999" });

    final Map<String, Object[]> parameterMap = requestParser.getParameterMap(request);
    assertEquals("parameterMap.size()", 4, parameterMap.size());
    final Object[] a = parameterMap.get("a");
    assertEquals("a.length", 1, a.length);
    assertEquals("a[0]", "12345", a[0]);
    final Object[] b = parameterMap.get("b");
    assertEquals("b.length", 2, b.length);
    assertEquals("b[0]", "abc", b[0]);
    assertEquals("b[1]", "def", b[1]);
    final Object[] c = parameterMap.get("c");
    assertEquals("c.length", 1, c.length);
    assertEquals("c[0]", "999", c[0]);
    final Object[] file = parameterMap.get("file");
    assertEquals("file.length", 1, file.length);
    assertTrue("file[0]", file[0] instanceof FileItem);
    final FileItem item = (FileItem) file[0];
    assertEquals("upload test", new String(item.get(), "UTF-8"));
}