Example usage for org.apache.commons.httpclient.params HostParams DEFAULT_HEADERS

List of usage examples for org.apache.commons.httpclient.params HostParams DEFAULT_HEADERS

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HostParams DEFAULT_HEADERS.

Prototype

String DEFAULT_HEADERS

To view the source code for org.apache.commons.httpclient.params HostParams DEFAULT_HEADERS.

Click Source Link

Usage

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static void configure(HttpClient client, URI targetURI, Element authPart, HttpParams params)
        throws URIException {
    if (log.isDebugEnabled())
        log.debug("Configuring http client...");

    /* Do not forget to wire params so that endpoint properties are passed around
       Down the road, when the request will be executed, the hierarchy of parameters will be the following:
     (-> means "is parent of")/*from www  .ja  v a  2s. c o m*/
     default params -> params from endpoint properties -> HttpClient -> HostConfig -> Method
       This wiring is done by HttpClient.
    */
    client.getParams().setDefaults(params);

    // Here we make sure HttpClient will not handle the default headers.
    // Actually HttpClient *appends* default headers while we want them to be ignored if the process assign them
    client.getParams().setParameter(HostParams.DEFAULT_HEADERS, Collections.EMPTY_LIST);

    // proxy configuration
    if (ProxyConf.isProxyEnabled(params, targetURI.getHost())) {
        if (log.isDebugEnabled())
            log.debug("ProxyConf");
        ProxyConf.configure(client.getHostConfiguration(), client.getState(),
                (HttpTransportProperties.ProxyProperties) params
                        .getParameter(Properties.PROP_HTTP_PROXY_PREFIX));
    }

    // security
    // ...

    // authentication
    /*
    We're expecting the following element:
    <xs:complexType name="credentialType">
    <xs:attribute name="scheme" type="xs:string" default="server-decide" />
    <xs:attribute name="username" type="xs:string" />
    <xs:attribute name="password" type="xs:string" />
    </xs:complexType>
    <xs:element type="rest_connector:credentialType" name="credentials" />
     */
    if (authPart != null) {
        // the part must be defined with an element, so take the fist child
        Element credentialsElement = DOMUtils.getFirstChildElement(authPart);
        if (credentialsElement != null && credentialsElement.getAttributes().getLength() != 0) {
            String scheme = DOMUtils.getAttribute(credentialsElement, "scheme");
            String username = DOMUtils.getAttribute(credentialsElement, "username");
            String password = DOMUtils.getAttribute(credentialsElement, "password");

            if (scheme != null && !"server-decides".equalsIgnoreCase(scheme)
                    && !"basic".equalsIgnoreCase(scheme) && !"digest".equalsIgnoreCase(scheme)) {
                throw new IllegalArgumentException("Unknown Authentication scheme: [" + scheme
                        + "] Accepted values are: Basic, Digest, Server-Decides");
            } else {
                if (log.isDebugEnabled())
                    log.debug("credentials provided: scheme=" + scheme + " user=" + username
                            + " password=********");
                client.getState().setCredentials(
                        new AuthScope(targetURI.getHost(), targetURI.getPort(), AuthScope.ANY_REALM, scheme),
                        new UsernamePasswordCredentials(username, password));
                // save one round trip if basic
                client.getParams().setAuthenticationPreemptive("basic".equalsIgnoreCase(scheme));
            }
        }
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * First go through the list of default headers set in the method params. This param is then remove to avoid interference with HttpClient.
 * Actually the default headers should be overriden by any headers set from the process.
 * Not to mention that, for a given header, HttpClient do not overwrite any previous values but simply append the default value.<br/>
 *  See {@link see org.apache.commons.httpclient.params.HostParams.DEFAULT_HEADERS}
 * <p/>/*from   w ww . j  a  v a2s  .  c om*/
 * Then go through the list of message headers and set them if empty.
 * <p/>
 * Finally go through the list of {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :header} elements included in the input binding.
 * For each of them, set the HTTP Request Header with the static value defined by the attribute {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :value},
 * or the part value mentioned in the attribute {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :part}.
 * <p/>
 * Finally, set the 'Accept' header if the output content type of the operation exists.
 * <p/>
 * Notice that the last header value overrides any values set previoulsy. Meaning that message headers might get overriden by parts bound to headers.
 *
 */
public void setHttpRequestHeaders(HttpMethod method, BindingOperation opBinding,
        Map<String, Element> partValues, Map<String, Node> headers, HttpParams params) {
    BindingInput inputBinding = opBinding.getBindingInput();
    Message inputMessage = opBinding.getOperation().getInput().getMessage();

    // Do not let HttpClient manage the default headers
    // Actually the default headers should be overriden by any headers set from the process.
    // (Not to mention that, for a given header, HttpClient do not overwrite any previous values but simply append the default value)
    Collection defaultHeaders = (Collection) params.getParameter(HostParams.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        Iterator i = defaultHeaders.iterator();
        while (i.hasNext()) {
            method.setRequestHeader((Header) i.next());
        }
    }

    // process message headers
    for (Iterator<Map.Entry<String, Node>> iterator = headers.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Node> e = iterator.next();
        String headerName = e.getKey();
        Node headerNode = e.getValue();
        String headerValue = DOMUtils.domToString(headerNode);
        method.setRequestHeader(headerName, HttpHelper.replaceCRLFwithLWS(headerValue));
    }

    // process parts that are bound to message parts
    Collection<UnknownExtensibilityElement> headerBindings = WsdlUtils
            .getHttpHeaders(inputBinding.getExtensibilityElements());
    for (Iterator<UnknownExtensibilityElement> iterator = headerBindings.iterator(); iterator.hasNext();) {
        Element binding = iterator.next().getElement();
        String headerName = binding.getAttribute("name");
        String partName = binding.getAttribute("part");
        String value = binding.getAttribute("value");

        /* Header binding may use a part or a static value */
        String headerValue;
        if (StringUtils.isNotEmpty(partName)) {
            // 'part' attribute is used
            // get the part to be put in the header
            Part part = inputMessage.getPart(partName);
            Element partWrapper = partValues.get(part.getName());
            if (DOMUtils.isEmptyElement(partWrapper)) {
                headerValue = "";
            } else {
                /*
                The expected part value could be a simple type
                or an element of a simple type.
                So if a element is there, take its text content
                else take the text content of the part element itself
                */
                Element childElement = DOMUtils.getFirstChildElement(partWrapper);
                if (childElement != null) {
                    if (DOMUtils.getFirstChildElement(childElement) != null) {
                        String errMsg = "Complex types are not supported. Header Parts must be simple types or elements of a simple type.";
                        if (log.isErrorEnabled())
                            log.error(errMsg);
                        throw new RuntimeException(errMsg);
                    } else {
                        headerValue = DOMUtils.getTextContent(childElement);
                    }
                } else {
                    headerValue = DOMUtils.getTextContent(partWrapper);
                }
            }
        } else if (StringUtils.isNotEmpty(value)) {
            // 'value' attribute is used, this header is a static value
            headerValue = value;
        } else {
            String errMsg = "Invalid binding: missing attribute! Expecting "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "part") + " or "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "value");
            if (log.isErrorEnabled())
                log.error(errMsg);
            throw new RuntimeException(errMsg);
        }
        // do not set the header isf the value is empty
        if (StringUtils.isNotEmpty(headerValue))
            method.setRequestHeader(headerName, HttpHelper.replaceCRLFwithLWS(headerValue));
    }

    MIMEContent outputContent = WsdlUtils
            .getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
    // set Accept header if output content type is set
    if (outputContent != null) {
        method.setRequestHeader("Accept", outputContent.getType());
    }

}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static void setCredentials(final @NotNull HttpClient httpClient, final @NotNull Credentials credentials,
        final @NotNull URI serverUri) {
    if (credentials.getType() == Credentials.Type.Alternate) {
        HostParams parameters = httpClient.getHostConfiguration().getParams();
        Collection<Header> headers = (Collection<Header>) parameters.getParameter(HostParams.DEFAULT_HEADERS);

        if (headers == null) {
            headers = new ArrayList<Header>();
            parameters.setParameter(HostParams.DEFAULT_HEADERS, headers);
        }/*from www.ja v a  2 s  .com*/

        Header authHeader = ContainerUtil.find(headers, new Condition<Header>() {
            @Override
            public boolean value(Header header) {
                return header.getName().equals(HTTPConstants.HEADER_AUTHORIZATION);
            }
        });

        if (authHeader == null) {
            authHeader = new Header(HTTPConstants.HEADER_AUTHORIZATION, "");
            headers.add(authHeader);
        }

        authHeader.setValue(BasicScheme.authenticate(
                new UsernamePasswordCredentials(credentials.getUserName(), credentials.getPassword()),
                "UTF-8"));
    } else {
        final NTCredentials ntCreds = new NTCredentials(credentials.getUserName(), credentials.getPassword(),
                serverUri.getHost(), credentials.getDomain());
        httpClient.getState().setCredentials(AuthScope.ANY, ntCreds);
        httpClient.getParams().setBooleanParameter(USE_NATIVE_CREDENTIALS,
                credentials.getType() == Credentials.Type.NtlmNative);
    }
}