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

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

Introduction

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

Prototype

public abstract String getQueryString();

Source Link

Usage

From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java

/**
 * Forwards the request and returns the response.
 * //  w w  w. jav  a  2 s .  c  o  m
 * The rest is probably out of date:
 * Will use a UrlGetMethod to benefit the cacheing mechanism
 * and intermediate proxy servers.
 * It is potentially possible that the size of the request
 * may grow beyond a certain limit for GET and it will require POST instead.
 *
 * @return byte[] XML response
 */
public byte[] fetch() throws ProcessingException {
    HttpMethod method = null;

    // check which method (GET or POST) to use.
    if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) {
        method = new PostMethod(this.source);
    } else {
        method = new GetMethod(this.source);
    }

    if (this.getLogger().isDebugEnabled()) {
        this.getLogger().debug("request HTTP method: " + method.getName());
    }

    // this should probably be exposed as a sitemap option
    method.setFollowRedirects(true);

    // copy request parameters and merge with URL parameters
    Request request = ObjectModelHelper.getRequest(objectModel);

    ArrayList paramList = new ArrayList();
    Enumeration enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String pname = (String) enumeration.nextElement();
        String[] paramsForName = request.getParameterValues(pname);
        for (int i = 0; i < paramsForName.length; i++) {
            NameValuePair pair = new NameValuePair(pname, paramsForName[i]);
            paramList.add(pair);
        }
    }

    if (paramList.size() > 0) {
        NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()];
        paramList.toArray(allSubmitParams);

        String urlQryString = method.getQueryString();

        // use HttpClient encoding routines
        method.setQueryString(allSubmitParams);
        String submitQryString = method.getQueryString();

        // set final web service query string

        // sometimes the querystring is null here...
        if (null == urlQryString) {
            method.setQueryString(submitQryString);
        } else {
            method.setQueryString(urlQryString + "&" + submitQryString);
        }

    } // if there are submit parameters

    byte[] response = null;
    try {
        int httpStatus = httpClient.executeMethod(method);
        if (httpStatus < 400) {
            if (this.getLogger().isDebugEnabled()) {
                this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus);
            }
        } else {
            throw new ProcessingException("The remote returned error " + httpStatus
                    + " when attempting to access remote URL:" + method.getURI());
        }
    } catch (URIException e) {
        throw new ProcessingException("There is a problem with the URI: " + this.source, e);
    } catch (IOException e) {
        try {
            throw new ProcessingException(
                    "Exception when attempting to access the remote URL: " + method.getURI(), e);
        } catch (URIException ue) {
            throw new ProcessingException("There is a problem with the URI: " + this.source, ue);
        }
    } finally {
        /* It is important to always read the entire response and release the
         * connection regardless of whether the server returned an error or not.
         * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html}
         */
        response = method.getResponseBody();
        method.releaseConnection();
    }

    return response;
}

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

protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {/*  w w  w . j av a  2  s .  c  om*/
    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.biomart.martservice.MartServiceUtils.java

private static MartServiceException constructException(HttpMethod method, String martServiceLocation,
        Exception cause) {//from   w  w  w. j  a v a2  s .c  o m
    StringBuffer errorMessage = new StringBuffer();
    errorMessage.append("Error posting to " + martServiceLocation + lineSeparator);
    if (cause == null) {
        errorMessage.append(" " + method.getStatusLine() + lineSeparator);
    }
    if (method instanceof PostMethod) {
        PostMethod postMethod = (PostMethod) method;
        NameValuePair[] data = postMethod.getParameters();
        for (int i = 0; i < data.length; i++) {
            errorMessage.append(" " + data[i].getName() + " = " + data[i].getValue() + lineSeparator);
        }

    } else {
        errorMessage.append(method.getQueryString());
    }
    return new MartServiceException(errorMessage.toString(), cause);
}

From source file:org.encuestame.core.util.SocialUtils.java

/**
 * Get TinyUrl./*  w w w .  j a  v a2 s  . co m*/
 * @param url
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static String getYourls(final String url) {
    String yourlsShortUrl = url;
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    HttpClient httpclient = new HttpClient(params); //TODO: time out??
    HttpMethod method = new GetMethod(EnMePlaceHolderConfigurer.getProperty("short.yourls.path"));
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", url),
            new NameValuePair("action", "shorturl"), new NameValuePair("format", "json"),
            new NameValuePair("signature", EnMePlaceHolderConfigurer.getProperty("short.yourls.key")) });
    System.out.println("method--->" + method.getPath());
    System.out.println("method--->" + method.getQueryString());
    try {
        httpclient.executeMethod(method);
        final Object jsonObject = JSONValue.parse(method.getResponseBodyAsString());
        final JSONObject o = (JSONObject) jsonObject;
        //{"message":"Please log in","errorCode":403}"
        Long errorCode = (Long) o.get("errorCode");
        if (errorCode != null) {
            throw new EnMeException("Yourls error: " + errorCode);
        }
        yourlsShortUrl = (String) o.get("shorturl");
    } catch (HttpException e) {
        log.error("HttpException " + e);
        yourlsShortUrl = url;
    } catch (IOException e) {
        log.error("IOException" + e);
        yourlsShortUrl = url;
    } catch (Exception e) {
        //e.printStackTrace();
        log.error("IOException" + e);
        yourlsShortUrl = url;
    } finally {
        RequestSessionMap.setErrorMessage("short url is not well configured");
        method.releaseConnection();
    }
    return yourlsShortUrl;
}

From source file:org.infoscoop.request.OAuth2Authenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuth2Config oauthConfig = request.getOauth2Config();
    try {//from www . j  av a2s  .  c o m
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig, getCallbackURL(request));
        if (oauthConfig.accessToken == null) {
            returnApprovalUrl(request, consumer);
        }

        if (oauthConfig.validityPeriodUTC != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            if (cal.getTimeInMillis() > oauthConfig.validityPeriodUTC) {
                if (oauthConfig.refreshToken == null) {
                    OAuthService.getHandle().deleteOAuth2Token(request.getPortalUid(), oauthConfig.gadgetUrl,
                            oauthConfig.serviceName);
                    returnApprovalUrl(request, consumer);
                } else {
                    log.error(
                            "AccessToken was expired, try re-get the token. [" + oauthConfig.serviceName + "]");
                    getAccessTokenByRefreshToken(request, consumer);
                    OAuth2Token token2 = OAuth2TokenDAO.newInstance().getAccessToken(request.getPortalUid(),
                            oauthConfig.gadgetUrl, oauthConfig.serviceName);
                    oauthConfig.setAccessToken(token2.getAccessToken());
                    oauthConfig.setRefreshToken(token2.getRefreshToken());
                    oauthConfig.setValidityPeriodUTC(token2.getValidityPeriodUTC());
                }
            }
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }

        if ("Bearer".equalsIgnoreCase(oauthConfig.tokenType)) {
            method.addRequestHeader("Authorization", oauthConfig.tokenType + " " + oauthConfig.accessToken);
        } else {
            method.addRequestHeader("Authorization", "OAuth " + oauthConfig.accessToken);

            String queryString = method.getQueryString();
            queryString = "access_token=" + oauthConfig.accessToken + "&" + queryString;
            method.setQueryString(queryString);
        }
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

@Test
public void testUrlWithoutQuery() throws Exception {
    MuleMessage message = setupRequestContext("http://localhost:8080/services", HttpConstants.METHOD_GET);
    // transforming NullPayload will make sure that no body=xxx query is added
    message.setPayload(NullPayload.getInstance());

    ObjectToHttpClientMethodRequest transformer = createTransformer();
    Object response = transformer.transform(message);

    assertTrue(response instanceof HttpMethod);
    HttpMethod httpMethod = (HttpMethod) response;

    assertEquals(null, httpMethod.getQueryString());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

@Test
public void testUrlWithQuery() throws Exception {
    MuleMessage message = setupRequestContext("http://localhost:8080/services?method=echo",
            HttpConstants.METHOD_GET);//from  w w w.  j  a  v  a2  s  .com
    // transforming NullPayload will make sure that no body=xxx query is added
    message.setPayload(NullPayload.getInstance());

    ObjectToHttpClientMethodRequest transformer = createTransformer();
    Object response = transformer.transform(message);

    assertTrue(response instanceof HttpMethod);
    HttpMethod httpMethod = (HttpMethod) response;

    assertEquals("method=echo", httpMethod.getQueryString());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

@Test
public void testUrlWithUnescapedQuery() throws Exception {
    MuleMessage message = setupRequestContext("http://mycompany.com/test?fruits=apple%20orange",
            HttpConstants.METHOD_GET);/*www . j  ava  2s .co  m*/
    // transforming NullPayload will make sure that no body=xxx query is added
    message.setPayload(NullPayload.getInstance());

    ObjectToHttpClientMethodRequest transformer = createTransformer();
    Object response = transformer.transform(message);

    assertTrue(response instanceof HttpMethod);
    HttpMethod httpMethod = (HttpMethod) response;

    assertEquals("fruits=apple%20orange", httpMethod.getQueryString());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

@Test
public void testAppendedUrl() throws Exception {
    MuleMessage message = setupRequestContext("http://mycompany.com/test?fruits=apple%20orange",
            HttpConstants.METHOD_GET);// w w w.j a v  a2  s  .c  o  m
    // transforming a payload here will add it as body=xxx query parameter
    message.setPayload("test");
    message.setOutboundProperty(HttpConnector.HTTP_GET_BODY_PARAM_PROPERTY, "body");

    ObjectToHttpClientMethodRequest transformer = createTransformer();
    Object response = transformer.transform(message);

    assertTrue(response instanceof HttpMethod);
    HttpMethod httpMethod = (HttpMethod) response;

    assertEquals("fruits=apple%20orange&body=test", httpMethod.getQueryString());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

public void testPostMethod() throws Exception {
    final MuleMessage message = setupRequestContext("http://localhost:8080/services",
            HttpConstants.METHOD_POST);/*from w  w  w .j  a  v a2 s. c o m*/
    final String contentType = "text/plain";

    message.setPayload("I'm a payload");
    message.setInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE, contentType);

    final ObjectToHttpClientMethodRequest transformer = createTransformer();
    final Object response = transformer.transform(message);

    assertTrue(response instanceof PostMethod);
    final HttpMethod httpMethod = (HttpMethod) response;
    assertEquals(null, httpMethod.getQueryString());

    assertEquals(contentType, httpMethod.getRequestHeader(HttpConstants.HEADER_CONTENT_TYPE).getValue());
}