Example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication

List of usage examples for org.apache.commons.httpclient HttpMethod setDoAuthentication

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication.

Prototype

public abstract void setDoAuthentication(boolean paramBoolean);

Source Link

Usage

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, //w  ww. ja  v  a 2  s .  c  o m
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.mule.ibeans.module.http.HttpClientMessageRequester2.java

/**
 * Make a specific request to the underlying transport
 *
 * @param timeout the maximum time the operation should block before returning.
 *                The call should return immediately if there is data available. If
 *                no data becomes available before the timeout elapses, null will be
 *                returned//from  w w  w. ja v  a 2s .  co  m
 * @return the result of the request wrapped in a MuleMessage object. Null will be
 *         returned if no data was avaialable
 * @throws Exception if the call to the underlying protocal cuases an exception
 */
protected MuleMessage doRequest(long timeout) throws Exception {
    HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress());

    if (endpoint.getProperties().containsKey(HttpConstants.HEADER_AUTHORIZATION)) {
        httpMethod.setDoAuthentication(true);
        client.getParams().setAuthenticationPreemptive(true);
        httpMethod.setRequestHeader(HttpConstants.HEADER_AUTHORIZATION,
                (String) endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION));
    }

    boolean releaseConn = false;
    try {
        HttpClient client = new HttpClient();

        if (etag != null && checkEtag) {
            httpMethod.setRequestHeader(HttpConstants.HEADER_IF_NONE_MATCH, etag);
        }
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() < 400) {
            MuleMessage message = new HttpMuleMessageFactory(connector.getMuleContext()).create(httpMethod,
                    null /* encoding */);
            etag = message.getInboundProperty(HttpConstants.HEADER_ETAG, null);

            if (httpMethod.getStatusCode() == HttpStatus.SC_OK
                    || (httpMethod.getStatusCode() != HttpStatus.SC_NOT_MODIFIED || !checkEtag)) {
                if (StringUtils.EMPTY.equals(message.getPayload())) {
                    releaseConn = true;
                }
                return message;
            } else {
                //Not modified, we should really cache the whole message and return it
                return new DefaultMuleMessage(NullPayload.getInstance(), getConnector().getMuleContext());
            }
        } else {
            releaseConn = true;
            throw new ReceiveException(
                    HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint,
                    timeout);
        }

    } catch (ReceiveException e) {
        releaseConn = true;
        throw e;
    } catch (Exception e) {
        releaseConn = true;
        throw new ReceiveException(endpoint, timeout, e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.mule.module.activiti.ActivitiConnector.java

public void prepareMethod(HttpMethod httpMethod, HttpClient client) throws UnsupportedEncodingException {
    httpMethod.setDoAuthentication(true);

    String authScopeHost = url.getHost();
    int authScopePort = url.getPort();
    String authScopeRealm = AuthScope.ANY_REALM;
    String authScopeScheme = AuthScope.ANY_SCHEME;

    client.getState().setCredentials(//  w w w.  j a  v a2 s . c  om
            new AuthScope(authScopeHost, authScopePort, authScopeRealm, authScopeScheme),
            new UsernamePasswordCredentials(this.getUsername(), new String(this.getPassword())));

    client.getParams().setAuthenticationPreemptive(true);
}

From source file:org.mule.transport.http.HttpConnector.java

protected void setupClientAuthorization(MuleEvent event, HttpMethod httpMethod, HttpClient client,
        ImmutableEndpoint endpoint) throws UnsupportedEncodingException {
    httpMethod.setDoAuthentication(true);
    client.getParams().setAuthenticationPreemptive(true);

    if (event != null && event.getCredentials() != null) {
        MuleMessage msg = event.getMessage();
        String authScopeHost = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.host",
                event.getMessageSourceURI().getHost());
        int authScopePort = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.port",
                event.getMessageSourceURI().getPort());
        String authScopeRealm = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.realm", AuthScope.ANY_REALM);
        String authScopeScheme = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.scheme",
                AuthScope.ANY_SCHEME);/*from  w w w .  ja v  a 2  s.  co m*/
        client.getState().setCredentials(
                new AuthScope(authScopeHost, authScopePort, authScopeRealm, authScopeScheme),
                new UsernamePasswordCredentials(event.getCredentials().getUsername(),
                        new String(event.getCredentials().getPassword())));
    } else if (endpoint.getEndpointURI().getUserInfo() != null
            && endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION) == null) {
        // Add User Creds
        StringBuffer header = new StringBuffer(128);
        header.append("Basic ");
        header.append(new String(
                Base64.encodeBase64(endpoint.getEndpointURI().getUserInfo().getBytes(endpoint.getEncoding()))));
        httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, header.toString());
    }
    //TODO MULE-4501 this sohuld be removed and handled only in the ObjectToHttpRequest transformer
    else if (event != null && event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION) != null
            && httpMethod.getRequestHeader(HttpConstants.HEADER_AUTHORIZATION) == null) {
        String auth = event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION);
        httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, auth);
    } else {
        // don't use preemptive if there are no credentials to send
        client.getParams().setAuthenticationPreemptive(false);
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

protected final void setDoAuthentication(HttpMethod method) {
    if (authScope != null && httpClient.getState().getCredentials(authScope) != null) {
        method.setDoAuthentication(true);
    } else {//from   www.  j a  v  a2 s.  c om
        method.setDoAuthentication(false);
    }
}

From source file:org.parosproxy.paros.network.HttpSender.java

public int executeMethod(HttpMethod method, HttpState state) throws IOException {
    int responseCode = -1;

    String hostName;/*from   www  .  j av a 2  s  .c o m*/
    hostName = method.getURI().getHost();
    method.setDoAuthentication(true);
    HostConfiguration hc = null;

    HttpClient requestClient;
    if (param.isUseProxy(hostName)) {
        requestClient = clientViaProxy;

    } else {
        // ZAP: use custom client on upgrade connection and on event-source data type
        Header connectionHeader = method.getRequestHeader("connection");
        boolean isUpgrade = connectionHeader != null
                && connectionHeader.getValue().toLowerCase().contains("upgrade");

        // ZAP: try to apply original handling of ParosProxy
        requestClient = client;
        if (isUpgrade) {
            // Unless upgrade, when using another client that allows us to expose the socket
            // connection.
            requestClient = new HttpClient(new ZapHttpConnectionManager());
        }
    }

    if (this.initiator == CHECK_FOR_UPDATES_INITIATOR) {
        // Use the 'strict' SSLConnector, ie one that performs all the usual cert checks
        // The 'standard' one 'trusts' everything
        // This is to ensure that all 'check-for update' calls are made to the expected https urls
        // without this is would be possible to intercept and change the response which could result
        // in the user downloading and installing a malicious add-on
        hc = new HostConfiguration() {
            @Override
            public synchronized void setHost(URI uri) {
                try {
                    setHost(new HttpHost(uri.getHost(), uri.getPort(), getProtocol()));
                } catch (URIException e) {
                    throw new IllegalArgumentException(e.toString());
                }
            };
        };

        hc.setHost(hostName, method.getURI().getPort(),
                new Protocol("https", (ProtocolSocketFactory) new SSLConnector(false), 443));
        if (param.isUseProxy(hostName)) {
            hc.setProxyHost(new ProxyHost(param.getProxyChainName(), param.getProxyChainPort()));
            if (param.isUseProxyChainAuth()) {
                requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
            }
        }
    }

    // ZAP: Check if a custom state is being used
    if (state != null) {
        // Make sure cookies are enabled
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    responseCode = requestClient.executeMethod(hc, method, state);

    return responseCode;
}

From source file:org.sakaiproject.kernel.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.
 * /*from w ww  .j av a 2s  . c  o  m*/
 * <pre>
 * {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, String> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {

            VelocityContext context = new VelocityContext(input);

            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            Reader urlTemplateReader = new StringReader(endpointURL);
            StringWriter urlWriter = new StringWriter();
            velocityEngine.evaluate(context, urlWriter, "urlprocessing", urlTemplateReader);
            endpointURL = urlWriter.toString();

            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) {

                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                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);
                // 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);

            }
            // follow redirects, but dont auto process 401's and the like.
            // credentials should be provided
            method.setDoAuthentication(false);

            for (Entry<String, String> header : headers.entrySet()) {
                method.addRequestHeader(header.getKey(), header.getValue());
            }

            Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER);
            for (Value v : additionalHeaders) {
                String header = v.getString();
                String[] keyVal = StringUtils.split(header, ':', 2);
                method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim());
            }

            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 (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);
            }

            return new ProxyResponseImpl(result, method);
        }

    } 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.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  ww .  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.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java

/**
 * @param method// ww w  .j ava  2  s  . com
 * @throws RepositoryException
 */
private void populateMethod(HttpMethod method, Node node, Map<String, String> headers)
        throws RepositoryException {
    // follow redirects, but dont auto process 401's and the like.
    // credentials should be provided
    method.setDoAuthentication(false);

    for (Entry<String, String> header : headers.entrySet()) {
        method.addRequestHeader(header.getKey(), header.getValue());
    }

    Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER);
    for (Value v : additionalHeaders) {
        String header = v.getString();
        String[] keyVal = StringUtils.split(header, ':', 2);
        method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim());
    }

}

From source file:org.semispace.google.space.address.FetchAddress.java

public GoogleAddress resolveAddress(String address, GoogleKey key) {
    GoogleAddress result = new GoogleAddress();
    String url = encodeAddressAsHttpParameter(address, key);
    log.debug("Query url: " + url);
    HttpMethod method = new GetMethod(url);
    try {//w w  w.ja va2  s .  c o  m
        result.setAddress(address);
        HttpClient client = new HttpClient();
        method.setFollowRedirects(false);
        method.setDoAuthentication(false);
        client.executeMethod(method);
        byte[] buffer = method.getResponseBody();
        fillResponseInAddress(result, new String(buffer));
    } catch (IOException e) {
        result.setStatusCode("-1");
        log.error("Got exception", e);
    } finally {
        method.releaseConnection();
    }
    return result;
}