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.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

/**
 * Execute method. In case of any exception thrown by HttpClient, it will release the connection. In other cases it
 * is the duty of caller to do it, or process the input stream.
 * /*from www.j a  v  a2 s . c  o  m*/
 * @param method the method
 * @return the int
 */
protected int doExecuteMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    URI methodURI = null;

    try {
        methodURI = method.getURI();
    } catch (URIException e) {
        getLogger().debug("Could not format debug log message", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Invoking HTTP " + method.getName() + " method against remote location " + methodURI);
    }

    RemoteStorageContext ctx = getRemoteStorageContext(repository);

    HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT);

    HostConfiguration httpConfiguration = (HostConfiguration) ctx.getContextObject(CTX_KEY_HTTP_CONFIGURATION);

    method.setRequestHeader(new Header("user-agent", formatUserAgentString(ctx, repository)));
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));

    // HTTP keep alive should not be used, except when NTLM is used
    Boolean isNtlmUsed = (Boolean) ctx.getContextObject(HttpClientProxyUtil.NTLM_IS_IN_USE_KEY);

    if (isNtlmUsed == null || !isNtlmUsed) {
        method.setRequestHeader(new Header("Connection", "close"));
        method.setRequestHeader(new Header("Proxy-Connection", "close"));
    }

    method.setFollowRedirects(true);

    if (StringUtils.isNotBlank(ctx.getRemoteConnectionSettings().getQueryString())) {
        method.setQueryString(ctx.getRemoteConnectionSettings().getQueryString());
    }

    int resultCode;

    try {
        resultCode = httpClient.executeMethod(httpConfiguration, method);

        final Header httpServerHeader = method.getResponseHeader("server");
        checkForRemotePeerAmazonS3Storage(repository,
                httpServerHeader == null ? null : httpServerHeader.getValue());

        Header proxyReturnedErrorHeader = method.getResponseHeader(NEXUS_MISSING_ARTIFACT_HEADER);
        boolean proxyReturnedError = proxyReturnedErrorHeader != null
                && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

        if (resultCode == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteAccessDeniedException(repository, remoteUrl,
                    HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
        } else if (resultCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new RemoteAuthenticationNeededException(repository,
                    HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
        } else if (resultCode == HttpStatus.SC_OK && proxyReturnedError) {
            throw new RemoteStorageException(
                    "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
        }
    } catch (RemoteStorageException e) {
        method.releaseConnection();

        throw e;
    } catch (HttpException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Protocol error while executing " + method.getName()
                + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    } catch (IOException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Transport error while executing " + method.getName()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    }

    return resultCode;
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * {@inheritDoc}/* w w  w  .j a  v a  2s.c  o  m*/
 *
 * @see org.tuleap.mylyn.task.core.internal.client.rest.IRestConnector#sendRequest(org.apache.commons.httpclient.HttpMethod)
 */
@Override
public ServerResponse sendRequest(HttpMethod method) {
    // debug mode
    boolean debug = false;
    IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ITuleapConstants.TULEAP_PREFERENCE_NODE);
    if (node != null) {
        debug = node.getBoolean(ITuleapConstants.TULEAP_PREFERENCE_DEBUG_MODE, false);
    }

    if (hostConfiguration == null) {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, null);
    }

    method.setRequestHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Accept-Charset", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$

    WebUtil.configureHttpClient(httpClient, getUserAgent());

    Header[] responseHeaders = null;
    String responseBody = null;
    ServerResponse serverResponse = null;
    try {
        int code = WebUtil.execute(httpClient, hostConfiguration, method, null);
        responseBody = method.getResponseBodyAsString();
        responseHeaders = method.getResponseHeaders();
        if (debug) {
            debugRestCall(method, responseBody);
        }
        Map<String, String> rHeaders = new LinkedHashMap<String, String>();
        for (Header h : responseHeaders) {
            rHeaders.put(h.getName(), h.getValue());
        }
        serverResponse = new ServerResponse(code, responseBody, rHeaders);
    } catch (IOException e) {
        logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages
                .getString(TuleapCoreKeys.ioError, method.getName() + ' ' + method.getPath(), e.getMessage())));
        serverResponse = new ServerResponse(IO_ERROR_STATUS_CODE, "", Collections //$NON-NLS-1$
                .<String, String>emptyMap());
    } finally {
        method.releaseConnection();
    }

    return serverResponse;
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * Logs a debug message of the REST request/response.
 *
 * @param method//ww w. java  2s  .  c  o m
 *            The method executed
 * @param bodyReceived
 *            The response body received
 */
private void debugRestCall(HttpMethod method, String bodyReceived) {
    int responseStatus = method.getStatusCode();
    StringBuilder b = new StringBuilder();
    b.append(method.getName());
    b.append(" ").append(method.getPath()); //$NON-NLS-1$
    String qs = method.getQueryString();
    if (qs != null && !qs.isEmpty()) {
        b.append('?').append(method.getQueryString());
    }
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity requestEntity = ((EntityEnclosingMethod) method).getRequestEntity();
        String body = ""; //$NON-NLS-1$
        if (requestEntity.isRepeatable()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                requestEntity.writeRequest(os);
                body = os.toString("UTF-8"); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
                // Nothing to do
            } catch (IOException e) {
                // Nothing to do
            }
        }
        b.append("\nbody:\n").append(body.replaceAll(//$NON-NLS-1$
                "\"password\" *: *\".*\"", "\"password\":\"(hidden in debug)\"")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    b.append("\n__________\nresponse:\n"); //$NON-NLS-1$
    b.append(method.getStatusLine()).append("\n"); //$NON-NLS-1$
    b.append("body:\n"); //$NON-NLS-1$
    b.append(bodyReceived);
    int status = IStatus.INFO;
    if (responseStatus != HttpURLConnection.HTTP_OK) {
        status = IStatus.ERROR;
    }
    this.logger.log(new Status(status, TuleapCoreActivator.PLUGIN_ID, b.toString()));
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.MockRestConnector.java

protected ServerRequest getServerRequest(HttpMethod method) {
    Map<String, String> header = new LinkedHashMap<String, String>();
    for (Header h : method.getRequestHeaders()) {
        header.put(h.getName(), h.getValue());
    }// w w  w.j av a 2  s . c o m
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity entity = ((EntityEnclosingMethod) method).getRequestEntity();
        if (entity instanceof StringRequestEntity) {
            return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString(),
                    ((StringRequestEntity) entity).getContent());
        }
    }
    return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString());
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.RestOperationsTest.java

@Test
public void testBasicBehavior() {
    RestOperation op = RestOperation.get("some/url", connector, gson, logger);
    HttpMethod m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("", m.getQueryString());

    op.withQueryParameter("key1", "value1");
    m = op.createMethod();/*from  www . j  a  v  a2 s  . c om*/
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1", m.getQueryString());

    op.withQueryParameter("key1", "value1b");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1b", m.getQueryString());

    op.withQueryParameter("key1", "value1", "value1b");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1&key1=value1b", m.getQueryString());

    op.withQueryParameter("key2", "value2");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1&key1=value1b&key2=value2", m.getQueryString());

    op.withoutQueryParameters("key1");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key2=value2", m.getQueryString());

    op.withoutQueryParameter();
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("", m.getQueryString());
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.RestResourceTest.java

/**
 * Test the pagination on GET with HEADER_X_PAGINATION_SIZE not set.
 * /*from   ww w .  j ava2 s .  co  m*/
 * @throws CoreException
 *             The exception to throw
 */
@Test
public void testGetPaginationSizeNotSet() throws CoreException {
    RestResource r = new RestResource("/server/api/v12.5/my/url", RestResource.GET, connector, gson,
            new TestLogger());
    Map<String, String> headers = Maps.newTreeMap();
    headers.put(RestResource.ALLOW, "OPTIONS,GET");
    headers.put(RestResource.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS,GET");
    connector.setResponse(new ServerResponse(ServerResponse.STATUS_OK, "", headers));
    RestOperation get = r.get();
    HttpMethod method = get.createMethod();
    assertEquals("GET", method.getName());
    assertEquals("/server/api/v12.5/my/url", method.getPath());
    assertEquals("", method.getQueryString());

    headers.put(RestResource.HEADER_X_PAGINATION_LIMIT_MAX, "10");
    connector.setResponse(new ServerResponse(ServerResponse.STATUS_OK, "", headers));
    get = r.get();
    method = get.createMethod();
    assertEquals("GET", method.getName());
    assertEquals("/server/api/v12.5/my/url", method.getPath());
    assertEquals("", method.getQueryString());
}

From source file:org.xwiki.test.rest.framework.AbstractHttpTest.java

protected String getHttpMethodInfo(HttpMethod method) throws Exception {
    return String.format("\nName: %s\nURI: %s\nStatus code: %d\nStatus text: %s", method.getName(),
            method.getURI(), method.getStatusCode(), method.getStatusText());
}