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

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

Introduction

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

Prototype

@Override
public void setURI(URI uri) throws URIException 

Source Link

Document

Sets the URI for this method.

Usage

From source file:fr.openwide.talendalfresco.rest.client.AlfrescoRestClient.java

public void execute(ClientCommand clientCommand) throws RestClientException {

    int statusCode = -1;
    HttpMethodBase method = null;
    try {//from w  w  w. j a  v a  2s .  co m
        // building method (and body entity if any)
        method = clientCommand.createMethod();

        // setting server URL
        method.setURI(new URI(restCommandUrlPrefix + clientCommand.getName(), false));
        method.getParams().setContentCharset(this.restEncoding);

        // building params (adding ticket)
        List<NameValuePair> params = clientCommand.getParams();
        params.add(new NameValuePair(TICKET_PARAM, ticket));
        method.setQueryString(params.toArray(EMPTY_NAME_VALUE_PAIR));

        // Execute the method.
        statusCode = client.executeMethod(method);

        // checking HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new RestClientException("Bad HTTP Status : " + statusCode);
        }

        // parsing response
        XMLEventReader xmlReader = null;
        try {
            xmlReader = XmlHelper.createXMLEventReader(method.getResponseBodyAsStream(), this.restEncoding);

            clientCommand.handleResponse(xmlReader);

            if (!RestConstants.CODE_OK.equals(clientCommand.getResultCode())) {
                //String msg = "Business error in command " + clientCommand.toString();
                //logger.error(msg, e);
                throw new RestClientException(clientCommand.getResultMessage(),
                        new RestClientException(clientCommand.getResultError()));
            }
        } catch (XMLStreamException e) {
            String msg = "XML parsing error on response body : ";
            try {
                msg += new String(method.getResponseBody());
            } catch (IOException ioex) {
                msg += "[unreadable]";
            }
            ;
            //logger.error(msg, e);
            throw new RestClientException(msg, e);
        } catch (IOException e) {
            String msg = "IO Error when parsing XML response body : ";
            //logger.error(msg, e);
            throw new RestClientException(msg, e);

        } finally {
            if (xmlReader != null) {
                try {
                    xmlReader.close();
                } catch (Throwable t) {
                }
            }
        }

    } catch (RestClientException rcex) {
        throw rcex;
    } catch (URIException e) {
        throw new RestClientException("URI error while executing command " + clientCommand, e);
    } catch (HttpException e) {
        throw new RestClientException("HTTP error while executing command " + clientCommand, e);
    } catch (IOException e) {
        throw new RestClientException("IO error while executing command " + clientCommand, e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.xerox.amazonws.common.AWSQueryConnection.java

/**
 * Make a http request and process the response. This method also performs automatic retries.
*
 * @param method The HTTP method to use (GET, POST, DELETE, etc)
 * @param action the name of the action for this query request
 * @param params map of request params//from  www .  j a v a  2  s . com
 * @param respType the class that represents the desired/expected return type
 */
protected <T> T makeRequest(HttpMethodBase method, String action, Map<String, String> params, Class<T> respType)
        throws HttpException, IOException, JAXBException {

    // add auth params, and protocol specific headers
    Map<String, String> qParams = new HashMap<String, String>(params);
    qParams.put("Action", action);
    qParams.put("AWSAccessKeyId", getAwsAccessKeyId());
    qParams.put("SignatureVersion", "" + sigVersion);
    qParams.put("Timestamp", httpDate());
    if (headers != null) {
        for (Iterator<String> i = headers.keySet().iterator(); i.hasNext();) {
            String key = i.next();
            for (Iterator<String> j = headers.get(key).iterator(); j.hasNext();) {
                qParams.put(key, j.next());
            }
        }
    }
    // sort params by key
    ArrayList<String> keys = new ArrayList<String>(qParams.keySet());
    Collator stringCollator = Collator.getInstance();
    stringCollator.setStrength(Collator.PRIMARY);
    Collections.sort(keys, stringCollator);

    // build param string
    StringBuilder resource = new StringBuilder();
    if (sigVersion == 0) { // ensure Action, Timestamp come first!
        resource.append(qParams.get("Action"));
        resource.append(qParams.get("Timestamp"));
    } else {
        for (String key : keys) {
            resource.append(key);
            resource.append(qParams.get(key));
        }
    }

    // calculate signature
    String encoded = urlencode(encode(getSecretAccessKey(), resource.toString(), false));

    // build param string, encoding values and adding request signature
    resource = new StringBuilder();
    for (String key : keys) {
        resource.append("&");
        resource.append(key);
        resource.append("=");
        resource.append(urlencode(qParams.get(key)));
    }
    resource.setCharAt(0, '?'); // set first param delimeter
    resource.append("&Signature=");
    resource.append(encoded);

    // finally, build request object
    URL url = makeURL(resource.toString());
    method.setURI(new URI(url.toString(), true));
    method.setRequestHeader(new Header("User-Agent", userAgent));
    if (sigVersion == 0) {
        method.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
    }
    Object response = null;
    boolean done = false;
    int retries = 0;
    boolean doRetry = false;
    String errorMsg = "";
    do {
        int responseCode = 600; // default to high value, so we don't think it is valid
        try {
            responseCode = getHttpClient().executeMethod(method);
        } catch (SocketException ex) {
            // these can generally be retried. Treat it like a 500 error
            doRetry = true;
            errorMsg = ex.getMessage();
        }
        // 100's are these are handled by httpclient
        if (responseCode < 300) {
            // 200's : parse normal response into requested object
            if (respType != null) {
                InputStream iStr = method.getResponseBodyAsStream();
                response = JAXBuddy.deserializeXMLStream(respType, iStr);
            }
            done = true;
        } else if (responseCode < 400) {
            // 300's : what to do?
            throw new HttpException("redirect error : " + responseCode);
        } else if (responseCode < 500) {
            // 400's : parse client error message
            String body = getStringFromStream(method.getResponseBodyAsStream());
            throw new HttpException("Client error : " + getErrorDetails(body));
        } else if (responseCode < 600) {
            // 500's : retry...
            doRetry = true;
            String body = getStringFromStream(method.getResponseBodyAsStream());
            errorMsg = getErrorDetails(body);
        }
        if (doRetry) {
            retries++;
            if (retries > maxRetries) {
                throw new HttpException("Number of retries exceeded : " + action + ", " + errorMsg);
            }
            doRetry = false;
            try {
                Thread.sleep((int) Math.pow(2.0, retries) * 1000);
            } catch (InterruptedException ex) {
            }
        }
    } while (!done);
    return (T) response;
}

From source file:org.eclipse.swordfish.plugins.resolver.proxy.impl.HttpCilentProxy.java

@Override
public ClientResponse invoke(ClientRequest request) {
    ClientResponse response = new ClientResponseImpl();
    HttpMethodBase method = getMethod(request.getMethod());

    try {/*  w w  w . j av a 2s. c  om*/
        method.setURI(new URI(request.getURI().toString(), true));
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            Reader responseReader = new StringReader(responseBody);
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                response.setEntity(JAXB.unmarshal(responseReader, request.getEntityType()));
            } finally {
                Thread.currentThread().setContextClassLoader(cl);
            }
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.httpobjects.proxy.Proxy.java

protected Response proxyRequest(Request req, final HttpMethodBase method) {
    method.setFollowRedirects(false);//  w  w w  .ja  va 2s .c om

    String path = req.path().valueFor("path");
    if (!path.startsWith("/"))
        path = "/" + path;
    String query = getQuery(req);
    if (query == null) {
        query = "";
    } else {
        query = "?" + query;
    }
    String url = base + path + query;
    log.debug("doing a " + method.getClass().getSimpleName() + " for " + url);
    //      log.debug("Content type is " + req.representation().contentType());
    try {
        method.setURI(new URI(processUrl(url), true));
    } catch (URIException e1) {
        throw new RuntimeException("Error with uri: " + url, e1);
    }

    addRequestHeaders(req, method);

    if (req.representation().contentType() != null) {
        method.addRequestHeader("Content-Type", req.representation().contentType());
    }

    for (Header next : method.getRequestHeaders()) {
        log.debug("Sending header: " + next);
    }

    HttpClient client = createHttpClient();

    return executeMethod(client, method, req);

}