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

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

Introduction

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

Prototype

public abstract String getName();

Source Link

Usage

From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java

/**
 * Does a basic HTTP GET and returns Http Status code + response body
 * Will add the dummy user query string//from w  w  w . j a v a2  s  .c  o  m
 */
private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data,
        NameValuePair[] params) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod method;
    switch (type) {
    case GET:
        method = new GetMethod(uri);
        break;
    case DELETE:
        method = new DeleteMethod(uri);
        break;
    case PUT:
        method = new PutMethod(uri);
        if (data == null) {
            break;
        }
        String msgBody = JsonBuilder.mapToJson(data);
        LOG.info("Msg Body: " + msgBody);
        StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet);
        ((PutMethod) method).setRequestEntity(sre);
        break;
    default:
        throw new IllegalArgumentException("Unsupported method type: " + type);
    }
    if (params == null) {
        method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) });
    } else {
        NameValuePair[] newParams = new NameValuePair[params.length + 1];
        System.arraycopy(params, 0, newParams, 1, params.length);
        newParams[0] = new NameValuePair("user.name", username);
        method.setQueryString(newParams);
    }
    String actualUri = "no URI";
    try {
        actualUri = method.getURI().toString();//should this be escaped string?
        LOG.debug(type + ": " + method.getURI().getEscapedURI());
        int httpStatus = client.executeMethod(method);
        LOG.debug("Http Status Code=" + httpStatus);
        String resp = method.getResponseBodyAsString();
        LOG.debug("response: " + resp);
        return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName());
    } catch (IOException ex) {
        LOG.error("doHttpCall() failed", ex);
    } finally {
        method.releaseConnection();
    }
    return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri,
            method.getName());
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

protected static void initMethod(HttpMethod method, SessionInfo sessionInfo) throws RepositoryException {

    boolean isReadAccess = readMethods.contains(method.getName());
    boolean needsSessionId = !isReadAccess || "POLL".equals(method.getName());

    if (sessionInfo instanceof SessionInfoImpl && needsSessionId) {
        StringBuilder linkHeaderField = new StringBuilder();

        String sessionIdentifier = ((SessionInfoImpl) sessionInfo).getSessionIdentifier();
        linkHeaderField.append("<").append(sessionIdentifier).append(">; rel=\"")
                .append(JcrRemotingConstants.RELATION_REMOTE_SESSION_ID).append("\"");

        String userdata = ((SessionInfoImpl) sessionInfo).getUserData();
        if (userdata != null && !isReadAccess) {
            String escaped = Text.escape(userdata);
            linkHeaderField.append(", <data:,").append(escaped).append(">; rel=\"")
                    .append(JcrRemotingConstants.RELATION_USER_DATA).append("\"");
        }//from  w w w .  j  a  va  2 s.  c  o m

        method.addRequestHeader("Link", linkHeaderField.toString());
    }
}

From source file:org.apache.jmeter.protocol.http.control.CacheManager.java

/**
 * Check the cache, and if there is a match, set the headers:
 * <ul>/*from w  w w.  j  ava2  s.c  o  m*/
 * <li>If-Modified-Since</li>
 * <li>If-None-Match</li>
 * </ul>
 * Commons HttpClient version
 * @param url URL to look up in cache
 * @param method where to set the headers
 * @deprecated HC3.1 will be dropped in upcoming version
 */
@Deprecated
public void setHeaders(URL url, HttpMethod method) {
    CacheEntry entry = getCache().get(url.toString());
    if (log.isDebugEnabled()) {
        log.debug(method.getName() + "(OACH) " + url.toString() + " " + entry);
    }
    if (entry != null) {
        final String lastModified = entry.getLastModified();
        if (lastModified != null) {
            method.setRequestHeader(HTTPConstants.IF_MODIFIED_SINCE, lastModified);
        }
        final String etag = entry.getEtag();
        if (etag != null) {
            method.setRequestHeader(HTTPConstants.IF_NONE_MATCH, etag);
        }
    }
}

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

public static String requestToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {//from w  w  w . j a  v  a 2  s. c  om
        sb.append("HTTP Request Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nRequest Headers:");
    Header[] headers = m.getRequestHeaders();
    if (headers.length == 0)
        sb.append(" n/a");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    if (m instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) m;
        if (eem.getRequestEntity() != null) {
            sb.append("\nRequest Entity:");
            sb.append("\n\tContent-Type:").append(eem.getRequestEntity().getContentType());
            sb.append("\n\tContent-Length:").append(eem.getRequestEntity().getContentLength());
            if (eem.getRequestEntity() instanceof StringRequestEntity) {
                StringRequestEntity sre = (StringRequestEntity) eem.getRequestEntity();
                sb.append("\n\tContent-Charset:").append(sre.getCharset());
                sb.append("\n\tRequest Entity:\n").append(sre.getContent());
            }
        }
    }
    return sb.toString();
}

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

public static String responseToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {//  w ww. j  a v a 2  s  .com
        sb.append("HTTP Response Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nStatus-Line: ").append(m.getStatusLine());
    Header[] headers = m.getResponseHeaders();
    if (headers.length != 0)
        sb.append("\nResponse Headers: ");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    try {
        if (StringUtils.isNotEmpty(m.getResponseBodyAsString())) {
            sb.append("\nResponse Entity:\n").append(m.getResponseBodyAsString());
        }
    } catch (IOException e) {
        log.error(e);
    }
    Header[] footers = m.getResponseFooters();
    if (footers.length != 0)
        sb.append("\nResponse Footers: ");
    for (int i = 0; i < footers.length; i++) {
        Header h = footers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    return sb.toString();
}

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

public void testGetTag() throws Exception {
    String uri = ((HTTPAddress) deliciousPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/tag/java";
    Element msgEl;/*from   ww  w. java  2  s . co  m*/
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "TagPart");
        partEl.setTextContent("java");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = deliciousBinding.getBindingOperation("getTag", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = deliciousBuilder.createHttpRequest(odeMex, new DefaultHttpParams());

    assertTrue("GET".equalsIgnoreCase(httpMethod.getName()));
    assertTrue(expectedUri.equalsIgnoreCase(httpMethod.getURI().toString()));
}

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

public void testHello() throws Exception {
    String uri = ((HTTPAddress) dummyPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/" + "DummyService/hello";
    Element msgEl, helloEl;/*from www.  j  a  va2s  .c  o  m*/
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "parameters");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
        helloEl = odeMsg.createElementNS(null, "hello");
        helloEl.setTextContent("This is a test. How is it going so far?");
        partEl.appendChild(helloEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = dummyBinding.getBindingOperation("hello", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = dummyBuilder.createHttpRequest(odeMex, new DefaultHttpParams());
    assertTrue("POST".equalsIgnoreCase(httpMethod.getName()));
    assertEquals("Generated URI does not match", expectedUri, httpMethod.getURI().toString());

    String b = ((StringRequestEntity) ((PostMethod) httpMethod).getRequestEntity()).getContent();
    assertEquals("Invalid body in generated http query", DOMUtils.domToString(helloEl), b);
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java

private void doRequest(Returned out, RequestMethod method_type, String uri, RequestDataSource src,
        CSPRequestCredentials creds, CSPRequestCache cache) throws ConnectionException {
    InputStream body_data = null;
    if (src != null) {
        body_data = src.getStream();// w  ww . ja  va2  s . co  m
    }
    try {
        HttpMethod method = createMethod(method_type, uri, body_data);
        if (body_data != null) {
            method.setRequestHeader("Content-Type", src.getMIMEType());
            // XXX Not sure if or when this ever actually writes to stderr?
            body_data = new TeeInputStream(body_data, System.err);
        }
        try {
            HttpClient client = makeClient(creds, cache);

            String requestContext = null;
            if (perflog.isDebugEnabled()) {
                // TODO add more context, e.g. session id?
                requestContext = "HttpClient@" + Integer.toHexString(client.hashCode());
                requestContext += "/CSPRequestCache@" + Integer.toHexString(cache.hashCode()) + ",";
                //String queryString = method.getQueryString();
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",app,svc," + requestContext + method.getName() + " " + method.getURI()
                //+ (queryString!=null ? queryString : "")
                );
            }

            int response = client.executeMethod(method);

            if (perflog.isDebugEnabled()) {
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",svc,app," + requestContext + "HttpClient.executeMethod done");
            }

            out.setResponse(method, response);
        } catch (ConnectionException e) {
            throw new ConnectionException(e.getMessage(), e.status, base_url + "/" + uri, e);
        } catch (Exception e) {
            throw new ConnectionException(e.getMessage(), 0, base_url + "/" + uri, e);
        } finally {
            method.releaseConnection();

            if (log.isWarnEnabled()) {
                if (manager.getConnectionsInPool() >= MAX_SERVICES_CONNECTIONS) {
                    log.warn("reached max services connection limit of " + MAX_SERVICES_CONNECTIONS);

                    // Delete closed connections from the pool, so that the warning will cease
                    // once a connection becomes available.
                    manager.deleteClosedConnections();
                }
            }
        }
    } finally {
        closeStream(body_data);
    }
}

From source file:org.cruk.genologics.api.debugging.HttpClientTimingAspect.java

/**
 * Join point that, if the logging is set to DEBUG, will report on the
 * call made with the HttpClient and the time taken to get a response.
 *
 * @param pjp The AspectJ join point object. One of the arguments in
 * this object must be the HttpMethod being invoked.
 *
 * @return The result of proceeding with the join point.
 *
 * @throws Throwable if there is any failure.
 *
 * @see HttpClient#executeMethod(HttpMethod)
 *///  w  w  w .  j ava2s  . c  om
public Object timeCall(ProceedingJoinPoint pjp) throws Throwable {
    if (!logger.isDebugEnabled()) {
        return pjp.proceed();
    }

    String uri = "<no url>";
    String method = "<unknown>";

    for (Object arg : pjp.getArgs()) {
        if (arg instanceof HttpMethod) {
            HttpMethod httpMethod = (HttpMethod) arg;
            uri = httpMethod.getURI().getEscapedURI();
            method = httpMethod.getName();
            break;
        }
    }

    long startTime = System.currentTimeMillis();

    try {
        return pjp.proceed();
    } finally {
        long endTime = System.currentTimeMillis();

        double timeTaken = (endTime - startTime) / 1000.0;

        logger.debug("HTTP " + method + " call to " + uri + " took " + timeTaken + " seconds.");
    }
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Delegates execution of the HttpMethod to the underlying HttpClient.
 * //from   ww w  . j ava 2  s.  co  m
 * @param method
 *            The HttpMethod to execute.
 * @return The method's response code.
 * @throws HttpException
 *             If an I/O (transport) error occurs.
 * @throws IOException
 *             If a protocol exception occurs.
 */
public int executeMethod(HttpMethod method) throws HttpException, IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("exec: " + method.getName() + " " + method.getURI());
    // use delegate
    return this.httpClient_.executeMethod(method);
}