Example usage for org.apache.commons.httpclient HttpMethodBase getURI

List of usage examples for org.apache.commons.httpclient HttpMethodBase getURI

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getURI.

Prototype

@Override
public URI getURI() throws URIException 

Source Link

Document

Returns the URI of the HTTP method

Usage

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//w  w  w.  j  a v  a2 s  .  c o  m
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Calculates the canonical and signed header strings in a single pass, done in one pass for efficiency
 * @param httpBaseRequest/*from w w  w  . j a v  a  2  s .  c om*/
 * @return Array of 2 elements, first element is the canonicalHeader string, second element is the signedHeaders string
 */
private static String[] getCanonicalAndSignedHeaders(HttpMethodBase httpBaseRequest) {
    /*
     * The host header is required for EucaV2 signing, but it is not constructed by the HttpClient until the method is executed.
     * So, here we add a header with the same value and name so that we can do the proper sigining, but know that this value will
     * be overwritten when HttpMethodBase is executed to send the request.
     * 
     * This code is specific to the jakarta commons httpclient because that client will set the host header to hostname:port rather than
     * just hostname.
     * 
     * Supposedly you can force the value of the Host header with: httpBaseRequest.getParams().setVirtualHost("hostname"), but that was not successful
     */
    try {
        httpBaseRequest.addRequestHeader("Host",
                httpBaseRequest.getURI().getHost() + ":" + httpBaseRequest.getURI().getPort());
    } catch (URIException e) {
        LOG.error(
                "Could not add Host header for canonical headers during authorization header creation in HTTP client: ",
                e);
        return null;
    }

    Header[] headers = httpBaseRequest.getRequestHeaders();
    StringBuilder signedHeaders = new StringBuilder();
    StringBuilder canonicalHeaders = new StringBuilder();

    if (headers != null) {
        Arrays.sort(headers, new Comparator<Header>() {
            @Override
            public int compare(Header arg0, Header arg1) {
                return arg0.getName().toLowerCase().compareTo(arg1.getName().toLowerCase());
            }

        });

        for (Header header : headers) {
            //Add to the signed headers
            signedHeaders.append(header.getName().toLowerCase()).append(';');
            //Add the name and value to the canonical header
            canonicalHeaders.append(header.getName().toLowerCase()).append(':').append(header.getValue().trim())
                    .append('\n');
        }

        if (signedHeaders.length() > 0) {
            signedHeaders.deleteCharAt(signedHeaders.length() - 1); //Delete the trailing semi-colon
        }

        if (canonicalHeaders.length() > 0) {
            canonicalHeaders.deleteCharAt(canonicalHeaders.length() - 1); //Delete the trialing '\n' just to make things clear and consistent
        }
    }
    String[] result = new String[2];
    result[0] = canonicalHeaders.toString();
    result[1] = signedHeaders.toString();
    return result;
}

From source file:com.googlecode.fascinator.common.BasicHttpClient.java

/**
 * Sends an HTTP request// w ww .  j a v  a2 s  . co m
 * 
 * @param method an HTTP method
 * @param auth true to request with authentication, false to request without
 * @return HTTP status code
 * @throws IOException if an error occurred during the HTTP request
 */
public int executeMethod(HttpMethodBase method, boolean auth) throws IOException {
    log.trace("{} {}", method.getName(), method.getURI());
    int status = getHttpClient(auth).executeMethod(method);
    log.trace("{} {}", status, HttpStatus.getStatusText(status));
    return status;
}

From source file:com.assemblade.client.AbstractClient.java

private void generateSignature(HttpMethodBase method) throws URIException {
    if (authentication != null) {
        String verb = method.getName();
        String url = OAuthEncoder.encode(method.getURI().toString());

        List<NameValuePair> queryStrings = new ArrayList<NameValuePair>();
        queryStrings.add(new NameValuePair(OAuthConstants.CONSUMER_KEY, authentication.getToken()));
        queryStrings.add(new NameValuePair(OAuthConstants.NONCE, timestampService.getNonce()));
        queryStrings.add(new NameValuePair(OAuthConstants.SIGN_METHOD, signatureService.getSignatureMethod()));
        queryStrings.add(new NameValuePair(OAuthConstants.TIMESTAMP, timestampService.getTimestampInSeconds()));
        queryStrings.add(new NameValuePair(OAuthConstants.VERSION, "1.0"));
        method.setQueryString(queryStrings.toArray(new NameValuePair[] {}));

        String queryString = OAuthEncoder.encode(method.getQueryString());

        String baseString = verb + "&" + url + "&" + queryString;

        String signature = signatureService.getSignature(baseString, authentication.getSecret(), "");

        queryStrings.add(new NameValuePair(OAuthConstants.SIGNATURE, signature));
        method.setQueryString(queryStrings.toArray(new NameValuePair[] {}));
    }/*from  ww w  . j a v a 2s.  co m*/
}

From source file:com.google.enterprise.connector.sharepoint.wsclient.soap.SPClientFactory.java

public int checkConnectivity(HttpMethodBase method, Credentials credentials) throws IOException {
    Resource resource = reserveResource(credentials);
    String currentWebApp = Util.getWebApp(method.getURI().getURI());
    try {/*from  ww  w  .  j  a  va  2 s . c o  m*/
        int responseCode = resource.httpClient.executeMethod(method);
        if (responseCode == 200) {
            // Add web app entry when response code is 200
            resource.webAppsVisited.add(currentWebApp);
        }
        if (responseCode != 200 && responseCode != 404 && responseCode != 400) {
            LOGGER.log(Level.WARNING,
                    "Http Response Code = " + responseCode + " for Url [ " + method.getURI() + " ].");

            if (responseCode == 401 && resource.webAppsVisited.contains(currentWebApp)) {
                LOGGER.log(Level.WARNING,
                        "Not reinitializing HTTP Client after "
                                + "[ 401 ] response as connection to Web Application [ " + currentWebApp
                                + " ] was successful earlier with existing HTTP Client Object.");
                return responseCode;
            }

            LOGGER.log(Level.WARNING,
                    "Reinitializing HTTP Client as [ " + responseCode + " ] response received.");
            resource = new Resource(createHttpClient(credentials));
            responseCode = resource.httpClient.executeMethod(method);
            if (responseCode == 200) {
                // Add web app entry when response code is 200
                resource.webAppsVisited.add(currentWebApp);
            }
        }
        returnResource(resource);
        return responseCode;
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING,
                "Error Connecting Server for Url [ " + method.getURI() + " ]. Reinitializing HttpClient.", ex);
        resource = new Resource(createHttpClient(credentials));
        int responseCode = resource.httpClient.executeMethod(method);
        if (responseCode == 200) {
            // Add web app entry when response code is 200
            resource.webAppsVisited.add(currentWebApp);
        }
        returnResource(resource);
        return responseCode;
    }
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

protected InputStream execute(HttpMethodBase method) throws IOException {
    try {/*from w  w  w.  j a  v  a  2s  .  c  om*/
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        assertResponseCodeOK(method, statusCode);
        return method.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new IOException("Exception executing http method at " + method.getURI(), e);
    }
}

From source file:com.comcast.cats.jenkins.service.AbstractService.java

/**
 * Sends Http request to Jenkins server and read the respose.
 * /*w ww .  j a v  a2  s .  com*/
 * @param mapperClass
 * @param domainObject
 * @param client
 * @param request
 * @return
 * @throws NumberFormatException
 * @throws IOException
 * @throws HttpException
 * @throws URIException
 */
private Object sendRequestToJenkins(Class<?> mapperClass, Object domainObject, HttpClient client,
        HttpMethodBase request, String apiToken)
        throws NumberFormatException, IOException, HttpException, URIException {
    String passwdord = apiToken;
    if (apiToken.isEmpty()) {
        // Set jenkins password if no API token is present
        passwdord = jenkinsClientProperties.getJenkinsPassword();
    }
    client.getState().setCredentials(
            new AuthScope(jenkinsClientProperties.getJenkinsHost(),
                    new Integer(jenkinsClientProperties.getJenkinsPort()), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(jenkinsClientProperties.getJenkinsUsername(), passwdord));
    if (!apiToken.isEmpty()) {
        client.getParams().setAuthenticationPreemptive(true);
    }

    int responseCode = client.executeMethod(request);

    LOGGER.info("[REQUEST][" + request.getURI().toString() + "]");
    LOGGER.info("[STATUS][" + request.getStatusLine().toString() + "]");

    if (HttpStatus.SC_OK == responseCode) {
        try {
            Serializer serializer = new Persister();
            domainObject = serializer.read(mapperClass, request.getResponseBodyAsStream(), false);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
    return domainObject;
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse executeWithTimeout(final HttpMethodBase httpMethod, int timeoutMillis) {
    client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
    ExecutorService service = Executors.newSingleThreadExecutor();

    Future<HttpResponse> future = service.submit(new Callable<HttpResponse>() {
        @Override/*  w  ww  .ja  v  a2s  .  c  o m*/
        public HttpResponse call() throws IOException {
            return execute(httpMethod);
        }
    });

    try {
        return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        String uriInfo = "";
        try {
            uriInfo = " for " + httpMethod.getURI();
        } catch (Exception ie) {
        }
        LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e);
        return new HttpResponse(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout", null);
    } finally {
        service.shutdownNow();
    }
}

From source file:com.sun.syndication.propono.atom.client.OAuthStrategy.java

public void addAuthentication(HttpClient httpClient, HttpMethodBase method) throws ProponoException {

    if (state != State.ACCESS_TOKEN) {
        throw new ProponoException("ERROR: authentication strategy failed init");
    }/* w w  w  .j  av  a 2s.c  o  m*/

    // add OAuth name/values to request query string

    // wish we didn't have to parse them apart first, ugh
    List originalqlist = null;
    if (method.getQueryString() != null) {
        String qstring = method.getQueryString().trim();
        qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring;
        originalqlist = new ParameterParser().parse(qstring, '&');
    } else {
        originalqlist = new ArrayList();
    }

    // put query string into hashmap form to please OAuth.net classes
    Map params = new HashMap();
    for (Iterator it = originalqlist.iterator(); it.hasNext();) {
        NameValuePair pair = (NameValuePair) it.next();
        params.put(pair.getName(), pair.getValue());
    }

    // add OAuth params to query string
    params.put("xoauth_requestor_id", username);
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_token", accessToken);
    params.put("oauth_token_secret", tokenSecret);

    // sign complete URI
    String finalUri = null;
    OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.tokenSecret = tokenSecret;
    OAuthMessage message;
    try {
        message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet());
        message.sign(accessor);

        finalUri = OAuth.addParameters(message.URL, message.getParameters());

    } catch (Exception ex) {
        throw new ProponoException("ERROR: OAuth signing request", ex);
    }

    // pull query string off and put it back onto method
    method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?")));
}

From source file:com.rometools.propono.atom.client.OAuthStrategy.java

@Override
public void addAuthentication(final HttpClient httpClient, final HttpMethodBase method)
        throws ProponoException {

    if (state != State.ACCESS_TOKEN) {
        throw new ProponoException("ERROR: authentication strategy failed init");
    }/*  ww w.  ja  v a 2s . c  o  m*/

    // add OAuth name/values to request query string

    // wish we didn't have to parse them apart first, ugh
    List<NameValuePair> originalqlist = null;
    if (method.getQueryString() != null) {
        String qstring = method.getQueryString().trim();
        qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring;
        @SuppressWarnings("unchecked")
        final List<NameValuePair> parameters = new ParameterParser().parse(qstring, '&');
        originalqlist = parameters;
    } else {
        originalqlist = new ArrayList<NameValuePair>();
    }

    // put query string into hashmap form to please OAuth.net classes
    final Map<String, String> params = new HashMap<String, String>();
    for (final Object element : originalqlist) {
        final NameValuePair pair = (NameValuePair) element;
        params.put(pair.getName(), pair.getValue());
    }

    // add OAuth params to query string
    params.put("xoauth_requestor_id", username);
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_token", accessToken);
    params.put("oauth_token_secret", tokenSecret);

    // sign complete URI
    String finalUri = null;
    final OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    final OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    final OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.tokenSecret = tokenSecret;
    OAuthMessage message;
    try {
        message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet());
        message.sign(accessor);

        finalUri = OAuth.addParameters(message.URL, message.getParameters());

    } catch (final Exception ex) {
        throw new ProponoException("ERROR: OAuth signing request", ex);
    }

    // pull query string off and put it back onto method
    method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?")));
}