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

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

Introduction

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

Prototype

public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);

Source Link

Usage

From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java

protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {/*from  w w  w. j ava 2  s .c o  m*/
    byte[] result = super.doPreemptiveAuthentication(client, method, request, response);
    if (result != null) {
        // already handled
        return result;
    }

    // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication...");

    PortletPreferences prefs = request.getPreferences();
    String type = getSingleSignOnAuthType(prefs);

    if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) {
        // Preemptive, basic authentication
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";

        // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password);
        method.setDoAuthentication(true);
        method.getHostAuthState().setPreemptive();
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        // handled!
        return result;

    } else if (type.startsWith(SSO_TYPE_FORM)) {
        try {
            Boolean formAuth = (Boolean) PortletMessaging.receive(request, FORM_AUTH_STATE);
            if (formAuth != null) {
                // already been here, done that
                return (formAuth.booleanValue() ? result : null);
            } else {
                // stop recursion, but assume failure, ...for now
                PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE);
            }

            String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, "");
            if (formAction == null || formAction.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_ACTION_URL
                        + ", action was specified - unable to preemptively authenticate by form.");
                return null;
            }
            String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, "");
            if (userNameField == null || userNameField.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_USERNAME_FIELD
                        + ", username field was specified - unable to preemptively authenticate by form.");
                return null;
            }
            String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password");
            if (passwordField == null || passwordField.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_PASSWORD_FIELD
                        + ", password field was specified - unable to preemptively authenticate by form.");
                return null;
            }

            String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
            if (userName == null)
                userName = "";
            String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
            if (password == null)
                password = "";

            // get submit method
            int i = type.indexOf('.');
            boolean isPost = i > 0 ? type.substring(i + 1).equalsIgnoreCase("post") : true; // default to post, since it is a form 

            // get parameter map
            HashMap formParams = new HashMap();
            formParams.put(userNameField, new String[] { userName });
            formParams.put(passwordField, new String[] { password });
            String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, "");
            if (formArgs != null && formArgs.length() > 0) {
                StringTokenizer iter = new StringTokenizer(formArgs, ";");
                while (iter.hasMoreTokens()) {
                    String pair = iter.nextToken();
                    i = pair.indexOf('=');
                    if (i > 0)
                        formParams.put(pair.substring(0, i), new String[] { pair.substring(i + 1) });
                }
            }

            // resuse client - in case new cookies get set - but create a new method (for the formAction)
            String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD;
            method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams,
                    formMethod, request);
            // System.out.println("...posting credentials");
            result = doHttpWebContent(client, method, 0, request, response);
            // System.out.println("Result of attempted authorization: "+success);
            PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null));
            return result;
        } catch (Exception ex) {
            // bad
            log.error("Form-based authentication failed", ex);
        }
    } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
        // set user name and password parameters in the HttpMethod
        String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, "");
        if (userNameParam == null || userNameParam.length() == 0) {
            log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_USERNAME_PARAM
                    + ", username parameter was specified - unable to preemptively authenticate by URL.");
            return null;
        }
        String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, "");
        if (passwordParam == null || passwordParam.length() == 0) {
            log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_PASSWORD_PARAM
                    + ", password parameter was specified - unable to preemptively authenticate by URL.");
            return null;
        }
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";
        if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
            Base64 encoder = new Base64();
            userName = new String(encoder.encode(userName.getBytes()));
            password = new String(encoder.encode(password.getBytes()));
        }

        // GET and POST accept args differently
        if (method instanceof PostMethod) {
            // add POST data
            PostMethod postMethod = (PostMethod) method;
            postMethod.addParameter(userNameParam, userName);
            postMethod.addParameter(passwordParam, password);
        } else {
            // augment GET query string
            NameValuePair[] authPairs = new NameValuePair[] { new NameValuePair(userNameParam, userName),
                    new NameValuePair(passwordParam, password) };
            String existingQuery = method.getQueryString();
            method.setQueryString(authPairs);
            if (existingQuery != null && existingQuery.length() > 0) {
                // augment existing query with new auth query
                existingQuery = existingQuery + '&' + method.getQueryString();
                method.setQueryString(existingQuery);
            }
        }

        return result;
    }
    // else System.out.println("...sso.type: "+type+", no pre-emptive authentication");

    // not handled
    return null;
}

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

/**
 * create and initialize the http method.
 * Http Headers that may been passed in the params are not set in this method.
 * Headers will be automatically set by HttpClient.
 * See usages of HostParams.DEFAULT_HEADERS
 * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod)
 *//*from ww w.  java 2  s .c om*/
protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues,
        Map<String, Node> headers, final String rootUri, HttpParams params)
        throws UnsupportedEncodingException {
    if (log.isDebugEnabled())
        log.debug("Preparing http request...");
    // convenience variables...
    BindingInput bindingInput = opBinding.getBindingInput();
    HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding);
    MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements());
    String contentType = content == null ? null : content.getType();
    boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput)
            || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType);
    boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput);

    // the http method to be built and returned
    HttpMethod method = null;

    // the 4 elements the http method may be made of
    String relativeUri = httpOperation.getLocationURI();
    String queryPath = null;
    RequestEntity requestEntity;
    String encodedParams = null;

    // ODE supports uri template in both port and operation location.
    // so assemble the final url *before* replacement
    String completeUri = rootUri;
    if (StringUtils.isNotEmpty(relativeUri)) {
        completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/")
                + relativeUri;
    }

    if (useUrlReplacement) {
        // insert part values in the url
        completeUri = new UrlReplacementTransformer().transform(completeUri, partValues);
    } else if (useUrlEncoded) {
        // encode part values
        encodedParams = new URLEncodedTransformer().transform(partValues);
    }

    // http-client api is not really neat
    // something similar to the following would save some if/else manipulations.
    // But we have to deal with it as-is.
    //
    //  method = new Method(verb);
    //  method.setRequestEnity(..)
    //  etc...
    if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) {
        if ("GET".equalsIgnoreCase(verb)) {
            method = new GetMethod();
        } else if ("DELETE".equalsIgnoreCase(verb)) {
            method = new DeleteMethod();
        }
        method.getParams().setDefaults(params);
        if (useUrlEncoded) {
            queryPath = encodedParams;
        }

        // Let http-client manage the redirection
        // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS
        // default is 100
        method.setFollowRedirects(true);
    } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) {

        if ("POST".equalsIgnoreCase(verb)) {
            method = new PostMethod();
        } else if ("PUT".equalsIgnoreCase(verb)) {
            method = new PutMethod();
        }
        method.getParams().setDefaults(params);
        // some body-building...
        final String contentCharset = method.getParams().getContentCharset();
        if (log.isDebugEnabled())
            log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]");
        if (useUrlEncoded) {
            requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE,
                    contentCharset);
        } else {
            // get the part to be put in the body
            Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart());
            Element partValue = partValues.get(part.getName());

            if (part.getElementName() == null) {
                String errMsg = "XML Types are not supported. Parts must use elements.";
                if (log.isErrorEnabled())
                    log.error(errMsg);
                throw new RuntimeException(errMsg);
            } else if (HttpUtils.isXml(contentType)) {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'");
                // stringify the first element
                String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue));
                requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType
                            + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text");
                // encoding conversion is managed by StringRequestEntity if necessary
                requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType,
                        contentCharset);
            }
        }

        // cast safely, PUT and POST are subclasses of EntityEnclosingMethod
        final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method;
        enclosingMethod.setRequestEntity(requestEntity);
        enclosingMethod
                .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false));

    } else {
        // should not happen because of HttpBindingValidator, but never say never
        throw new IllegalArgumentException("Unsupported HTTP method: " + verb);
    }

    method.setPath(completeUri); // assumes that the path is properly encoded (URL safe).
    method.setQueryString(queryPath);

    // set headers
    setHttpRequestHeaders(method, opBinding, partValues, headers, params);
    return method;
}

From source file:org.apache.roller.weblogger.util.Trackback.java

/**
 * Sends trackback from entry to remote URL.
 * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec
 *///  ww w . j  a  v a  2 s.c  om
public RollerMessages send() throws WebloggerException {

    RollerMessages messages = new RollerMessages();

    log.debug("Sending trackback to url - " + trackbackURL);

    // Construct data
    String title = entry.getTitle();
    String excerpt = StringUtils.left(Utilities.removeHTML(entry.getDisplayContent()), 255);
    String url = entry.getPermalink();
    String blog_name = entry.getWebsite().getName();

    // build trackback post parameters as query string
    Map params = new HashMap();
    params.put("title", URLUtilities.encode(title));
    params.put("excerpt", URLUtilities.encode(excerpt));
    params.put("url", URLUtilities.encode(url));
    params.put("blog_name", URLUtilities.encode(blog_name));
    String queryString = URLUtilities.getQueryString(params);

    log.debug("query string - " + queryString);

    // prepare http request
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(45 * 1000);
    HttpMethod method = new PostMethod(trackbackURL);
    method.setQueryString(queryString);

    try {
        // execute trackback
        int statusCode = client.executeMethod(method);

        // read response
        byte[] response = method.getResponseBody();
        String responseString = Utilities.escapeHTML(new String(response, "UTF-8"));

        log.debug("result = " + statusCode + " " + method.getStatusText());
        log.debug("response:\n" + responseString);

        if (statusCode == HttpStatus.SC_OK) {
            // trackback request succeeded, message will give details
            try {
                messages = parseTrackbackResponse(new String(response, "UTF-8"), messages);
            } catch (Exception e) {
                // Cannot parse response, indicates failure
                messages.addError("weblogEdit.trackbackErrorParsing", responseString);
            }
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            // 404, invalid trackback url
            messages.addError("weblogEdit.trackbackError404");
        } else {
            // some other kind of error with url, like 500, 403, etc
            // just provide a generic error message and give the http response text
            messages.addError("weblogEdit.trackbackErrorResponse",
                    new String[] { "" + statusCode, method.getStatusText() });
        }

    } catch (IOException e) {
        // some kind of transport error sending trackback post
        log.debug("Error sending trackback", e);
        messages.addError("weblogEdit.trackbackErrorTransport");
    } finally {
        // release used connection
        method.releaseConnection();
    }

    return messages;
}

From source file:org.apache.wink.itest.addressbook.StringTest.java

/**
 * This will drive a POST request with parameters from the query string
 *///w ww. ja va  2  s.c o  m
public void testPostWithQueryParams() {
    HttpMethod method = null;
    HttpMethod getMethod = null;
    try {

        // make sure everything is clear before testing
        HttpClient client = new HttpClient();
        method = new PostMethod(getBaseURI());
        method.setQueryString("entryName=newAddress&streetAddress=1234+Any+Street&city="
                + "AnyTown&zipCode=90210&state=TX&country=US");
        client.executeMethod(method);

        // now let's see if the address we just created is available
        getMethod = new GetMethod(getBaseURI() + "/newAddress");
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        String responseBody = getMethod.getResponseBodyAsString();
        assertNotNull(responseBody);
        assertTrue(responseBody, responseBody.contains("newAddress"));
        assertTrue(responseBody, responseBody.contains("1234 Any Street"));
        assertTrue(responseBody, responseBody.contains("AnyTown"));
        assertTrue(responseBody, responseBody.contains("90210"));
        assertTrue(responseBody, responseBody.contains("TX"));
        assertTrue(responseBody, responseBody.contains("US"));

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}

From source file:org.biomart.martservice.MartServiceUtils.java

/**
 * Sends a registry request to the Biomart webservice and constructs a
 * MartRegistry from the XML returned by the webservice.
 * //from   w ww .j  a va 2s .  c  o  m
 * @param martServiceLocation
 *            the URL of the Biomart webservice
 * @return a MartRegistry
 * @throws MartServiceException
 *             if the Biomart webservice returns an error or is unavailable
 */
public static MartRegistry getRegistry(String martServiceLocation, String requestId)
        throws MartServiceException {
    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new NameValuePair(TYPE_ATTRIBUTE, REGISTRY_VALUE));
    if (requestId != null) {
        data.add(new NameValuePair(REQUEST_ID_ATTRIBUTE, requestId));
    }
    HttpMethod method = new GetMethod(martServiceLocation);
    method.setQueryString(data.toArray(new NameValuePair[data.size()]));
    try {
        InputStream in = executeMethod(method, martServiceLocation);
        Document document = new SAXBuilder().build(in);
        Element root = document.getRootElement();
        return MartServiceXMLHandler.elementToRegistry(root, Namespace.NO_NAMESPACE);
    } catch (IOException e) {
        String errorMessage = "Error getting registry from " + martServiceLocation;
        throw new MartServiceException(errorMessage, e);
    } catch (JDOMException e) {
        String errorMessage = "Error getting registry from " + martServiceLocation;
        throw new MartServiceException(errorMessage, e);
    } finally {
        method.releaseConnection();
    }

}

From source file:org.biomart.martservice.MartServiceUtils.java

public static String getVersion(String martServiceLocation, String requestId, MartURLLocation mart)
        throws MartServiceException {
    String errorMessage = "Error getting version from " + martServiceLocation;

    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new NameValuePair(TYPE_ATTRIBUTE, VERSION_VALUE));
    if (mart.getVirtualSchema() != null) {
        data.add(new NameValuePair(SCHEMA_ATTRIBUTE, mart.getVirtualSchema()));
    }//from www.  j a  va 2  s .  co m
    data.add(new NameValuePair(MART_ATTRIBUTE, mart.getName()));
    if (requestId != null) {
        data.add(new NameValuePair(REQUEST_ID_ATTRIBUTE, requestId));
    }
    if (requestId != null) {
        data.add(new NameValuePair(REQUEST_ID_ATTRIBUTE, requestId));
    }
    HttpMethod method = new GetMethod(martServiceLocation);
    method.setQueryString(data.toArray(new NameValuePair[data.size()]));
    try {
        InputStream in = executeMethod(method, martServiceLocation);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
        String version = bufferedReader.readLine();
        if (version == null) {
            throw new MartServiceException(errorMessage + ": No version returned");
        }
        version = version.trim();
        // fix for biomart's 'let's add a blank line' thing
        if ("".equals(version)) {
            version = bufferedReader.readLine();
            if (version == null) {
                throw new MartServiceException(errorMessage + ": No version returned");
            }
            version = version.trim();
        }
        bufferedReader.close();
        return version;
    } catch (IOException e) {
        throw new MartServiceException(errorMessage, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.biomart.martservice.MartServiceUtils.java

/**
 * Sends a datasets request to the Biomart webservice and constructs an
 * array of MartDataset from the tab separated rows of data returned by the
 * webservice.//from w  w  w.  j av  a2  s. com
 * 
 * @param martServiceLocation
 *            the URL of the Biomart webservice
 * @param mart
 *            the mart to get datasets from
 * @return an array of MartDataset
 * @throws MartServiceException
 *             if the Biomart webservice returns an error or is unavailable
 */
public static MartDataset[] getDatasets(String martServiceLocation, String requestId, MartURLLocation mart)
        throws MartServiceException {
    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new NameValuePair(TYPE_ATTRIBUTE, DATASETS_VALUE));
    if (mart.getVirtualSchema() != null) {
        data.add(new NameValuePair(SCHEMA_ATTRIBUTE, mart.getVirtualSchema()));
    }
    data.add(new NameValuePair(MART_ATTRIBUTE, mart.getName()));
    if (mart.getMartUser() != null) {
        data.add(new NameValuePair(MART_USER_ATTRIBUTE, mart.getMartUser()));
    }
    if (requestId != null) {
        data.add(new NameValuePair(REQUEST_ID_ATTRIBUTE, requestId));
    }
    HttpMethod method = new GetMethod(martServiceLocation);
    method.setQueryString(data.toArray(new NameValuePair[data.size()]));
    try {
        InputStream in = executeMethod(method, martServiceLocation);

        MartDataset[] datasets = tabSeparatedReaderToDatasets(new InputStreamReader(in), mart);
        in.close();
        return datasets;
    } catch (IOException e) {
        String errorMessage = "Error getting datasets from " + martServiceLocation;
        throw new MartServiceException(errorMessage, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.biomart.martservice.MartServiceUtils.java

/**
 * Sends a configuration request to the Biomart webservice and constructs a
 * DatasetConfig from the XML returned by the webservice.
 * /*from w  w  w.  jav  a 2  s  .c o m*/
 * @param martServiceLocation
 *            the URL of the Biomart webservice
 * @param dataset
 *            the dataset to get the configuration for
 * @return a DatasetConfig
 * @throws MartServiceException
 *             if the Biomart webservice returns an error or is unavailable
 */
public static DatasetConfig getDatasetConfig(String martServiceLocation, String requestId, MartDataset dataset)
        throws MartServiceException {
    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new NameValuePair(TYPE_ATTRIBUTE, CONFIGURATION_VALUE));
    MartURLLocation mart = dataset.getMartURLLocation();
    // if the dataset has a location specify the virtual schema to uniquely
    // identify the dataset
    if (mart != null && mart.getVirtualSchema() != null) {
        data.add(new NameValuePair(SCHEMA_ATTRIBUTE, mart.getVirtualSchema()));
    }
    data.add(new NameValuePair(DATASET_VALUE, dataset.getName()));
    //      if (dataset.getInterface() != null) {
    //         data.add(new NameValuePair(INTERFACE_ATTRIBUTE, dataset
    //               .getInterface()));
    //      }
    if (mart != null && mart.getMartUser() != null) {
        data.add(new NameValuePair(MART_USER_ATTRIBUTE, mart.getMartUser()));
    }
    if (requestId != null) {
        data.add(new NameValuePair(REQUEST_ID_ATTRIBUTE, requestId));
    }
    HttpMethod method = new GetMethod(martServiceLocation);
    method.setQueryString(data.toArray(new NameValuePair[data.size()]));

    try {
        InputStream in = executeMethod(method, martServiceLocation);

        DatasetConfigXMLUtils datasetConfigXMLUtils = new DatasetConfigXMLUtils(true);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new InputSource(in));
        // Document doc = datasetConfigXMLUtils.getDocumentForXMLStream(in);

        DatasetConfig datasetConfig = datasetConfigXMLUtils.getDatasetConfigForDocument(doc);
        datasetConfigXMLUtils.loadDatasetConfigWithDocument(datasetConfig, doc);
        return datasetConfig;
    } catch (ConfigurationException e) {
        String errorMessage = "Error parsing configuration from " + martServiceLocation;
        logger.debug(errorMessage, e);
        throw new MartServiceException(errorMessage, e);
    } catch (JDOMException e) {
        String errorMessage = "Error parsing configuration from " + martServiceLocation;
        logger.debug(errorMessage, e);
        throw new MartServiceException(errorMessage, e);
    } catch (IOException e) {
        String errorMessage = "Error getting configuration from " + martServiceLocation;
        logger.debug(errorMessage, e);
        throw new MartServiceException(errorMessage, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.cancergrid.ws.util.HttpContentReader.java

public static String getHttpContent(String httpUrl, String query, Method method) {
    LOG.debug("getHttpContent(httpUrl): " + httpUrl);
    LOG.debug("getHttpContent(query): " + query);
    LOG.debug("getHttpContent(method): " + method);

    HttpMethod httpMethod = null;
    if (httpUrl.contains("&amp;")) {
        httpUrl = httpUrl.replace("&amp;", "&");
    }/*from  www  .  j a  va2s.c  o m*/

    if (query != null && query.length() > 0 && query.startsWith("?") && query.contains("&amp;")) {
        query = query.replace("&amp;", "&");
    }

    try {
        //LOG.debug("Querying: " + httpUrl);
        if (method == Method.GET) {
            httpMethod = new GetMethod(httpUrl);
            if (query != null && query.length() > 0) {
                httpMethod.setQueryString(query);
            }
        } else if (method == Method.POST) {
            httpMethod = new PostMethod(httpUrl);
            if (query != null && query.length() > 0) {
                RequestEntity entity = new StringRequestEntity(query, "text/xml", "UTF-8");
                ((PostMethod) httpMethod).setRequestEntity(entity);
            }
        }

        httpMethod.setFollowRedirects(true);

        httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        Protocol.registerProtocol("https", new Protocol("https",
                new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 443));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + httpMethod.getStatusLine());
            LOG.error("Error querying: " + httpMethod.getURI().toString());
            throw new Exception("Method failed: " + httpMethod.getStatusLine());
        }

        byte[] responseBody = httpMethod.getResponseBody();
        return new String(responseBody, "UTF-8");
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
    } catch (Exception e) {
        LOG.error(e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();/* w w  w.  ja  va 2s  .co m*/
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}