Example usage for org.apache.commons.httpclient.params HttpParams getParameter

List of usage examples for org.apache.commons.httpclient.params HttpParams getParameter

Introduction

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

Prototype

public abstract Object getParameter(String paramString);

Source Link

Usage

From source file:CustomAuthenticationExample.java

public static void main(String[] args) {

    // register the auth scheme
    AuthPolicy.registerAuthScheme(SecretAuthScheme.NAME, SecretAuthScheme.class);

    // include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference,
    // this can be done on a per-client or per-method basis but we'll do it
    // globally for this example
    HttpParams params = DefaultHttpParams.getDefaultParams();
    ArrayList schemes = new ArrayList();
    schemes.add(SecretAuthScheme.NAME);//from w w  w .  ja va2  s . c o m
    schemes.addAll((Collection) params.getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY));
    params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);

    // now that our scheme has been registered we can execute methods against
    // servers that require "Secret" authentication... 
}

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

public static void configure(HostConfiguration hostConfig, HttpState state, URI targetURI, HttpParams params)
        throws URIException {
    if (log.isDebugEnabled())
        log.debug("Configuring http client...");
    // proxy configuration
    if (ProxyConf.isProxyEnabled(params, targetURI.getHost())) {
        if (log.isDebugEnabled())
            log.debug("ProxyConf");
        ProxyConf.configure(hostConfig, state, (HttpTransportProperties.ProxyProperties) params
                .getParameter(Properties.PROP_HTTP_PROXY_PREFIX));
    }//from  w  w w  .  ja  v  a  2 s. c  o  m

    // security
    // ...

}

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

public void invoke(PartnerRoleMessageExchange odeMex) {
    if (log.isDebugEnabled())
        log.debug("Preparing " + getClass().getSimpleName() + " invocation...");
    try {//from w  w  w  .  ja  va 2s. c  o m
        // note: don't make this map an instance attribute, so we always get the latest version
        final Map<String, String> properties = pconf.getEndpointProperties(endpointReference);
        final HttpParams params = Properties.HttpClient.translate(properties);

        // base baseUrl
        String mexEndpointUrl = ((MutableEndpoint) odeMex.getEndpointReference()).getUrl();
        String baseUrl = mexEndpointUrl;
        // The endpoint URL might be overridden from the properties file(s)
        // The order of precedence is (in descending order): process, property, wsdl.
        if (endpointUrl.equals(new URL(mexEndpointUrl))) {
            String address = (String) params.getParameter(Properties.PROP_ADDRESS);
            if (address != null) {
                if (log.isDebugEnabled())
                    log.debug(
                            "Endpoint URL overridden by property files. " + mexEndpointUrl + " => " + address);
                baseUrl = address;
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Endpoint URL overridden by process. " + endpointUrl + " => " + mexEndpointUrl);
        }

        baseUrl = clusterUrlTransformer.rewriteOutgoingClusterURL(baseUrl);

        // build the http method
        final HttpMethod method = httpMethodConverter.createHttpRequest(odeMex, params, baseUrl);

        // create a client
        HttpClient client = new HttpClient(connections);

        // configure the client (proxy, security, etc)
        Element message = odeMex.getRequest().getMessage();
        Element authenticatePart = message == null ? null
                : DOMUtils.findChildByName(message, new QName(null, "WWW-Authenticate"));
        HttpHelper.configure(client, method.getURI(), authenticatePart, params);

        // this callable encapsulates the http method execution and the process of the response
        final Callable executionCallable;

        // execute it
        boolean isTwoWay = odeMex
                .getMessageExchangePattern() == MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
        if (isTwoWay) {
            // two way
            executionCallable = new HttpExternalService.TwoWayCallable(client, method,
                    odeMex.getMessageExchangeId(), odeMex.getOperation());
            scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
                public void afterCompletion(boolean success) {
                    // If the TX is rolled back, then we don't send the request.
                    if (!success)
                        return;
                    // The invocation must happen in a separate thread
                    executorService.submit(executionCallable);
                }

                public void beforeCompletion() {
                }
            });
            odeMex.replyAsync();
        } else {
            // one way, just execute and forget
            executionCallable = new HttpExternalService.OneWayCallable(client, method,
                    odeMex.getMessageExchangeId(), odeMex.getOperation());
            executorService.submit(executionCallable);
            odeMex.replyOneWayOk();
        }
    } catch (UnsupportedEncodingException e) {
        String errmsg = "The returned HTTP encoding isn't supported " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
    } catch (URIException e) {
        String errmsg = "Error sending message to " + getClass().getSimpleName() + " for ODE mex " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.FORMAT_ERROR, errmsg, null);
    } catch (Exception e) {
        String errmsg = "Unknown HTTP call error for ODE mex " + odeMex;
        log.error("[Service: " + serviceName + ", Port: " + portName + ", Operation: "
                + odeMex.getOperationName() + "] " + errmsg, e);
        odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null);
    }
}

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")/* w w  w  .  j  a  v  a 2  s .com*/
     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/>// w w  w  . ja v  a  2s  .  co  m
 * 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());
    }

}