Example usage for org.apache.http.client.methods HttpUriRequest getMethod

List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getMethod.

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithoutResponseHandler(HttpUriRequest request, boolean fault, boolean respexpected)
        throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*www .j  a va 2  s  .  co  m*/
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }
        if (!respexpected) {
            request.addHeader("test-no-data", "true");
        }

        HttpResponse response = httpclient.execute(request);

        int status = response.getStatusLine().getStatusCode();

        if (!fault) {
            assertEquals("Unexpected response code", 200, status);

            if (respexpected) {
                HttpEntity entity = response.getEntity();

                assertNotNull(entity);

                assertEquals(HELLO_WORLD, EntityUtils.toString(entity));
            }
        } else {
            assertEquals("Unexpected fault response code", 401, status);
        }

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithResponseHandler(HttpUriRequest request, boolean fault) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  ww w  .j  av  a 2s.  c om*/
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();

                assertEquals("Unexpected response code", 200, status);

                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }

        };

        String responseBody = httpclient.execute(request, responseHandler);

        assertEquals(HELLO_WORLD, responseBody);

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}

From source file:org.rundeck.api.ApiCall.java

/**
 * Execute an HTTP request to the Rundeck instance. We will login first, and then execute the API call.
 *
 * @param request to execute. see {@link HttpGet}, {@link HttpDelete}, and so on...
 * @return a new {@link InputStream} instance, not linked with network resources
 * @throws RundeckApiException in case of error when calling the API
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 *//*  w ww . ja  va 2s  . c om*/
private <T> T execute(HttpUriRequest request, Handler<HttpResponse, T> handler)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException {
    try (CloseableHttpClient httpClient = instantiateHttpClient()) {
        // we only need to manually login in case of login-based authentication
        // note that in case of token-based auth, the auth (via an HTTP header) is managed by an interceptor.
        if (client.getToken() == null && client.getSessionID() == null) {
            login(httpClient);
        }

        // execute the HTTP request
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (IOException e) {
            throw new RundeckApiException(
                    "Failed to execute an HTTP " + request.getMethod() + " on url : " + request.getURI(), e);
        }

        // in case of error, we get a redirect to /api/error
        // that we need to follow manually for POST and DELETE requests (as GET)
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode / 100 == 3) {
            String newLocation = response.getFirstHeader("Location").getValue();
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                throw new RundeckApiException("Failed to consume entity (release connection)", e);
            }
            request = new HttpGet(newLocation);
            try {
                response = httpClient.execute(request);
                statusCode = response.getStatusLine().getStatusCode();
            } catch (IOException e) {
                throw new RundeckApiException("Failed to execute an HTTP GET on url : " + request.getURI(), e);
            }
        }

        // check the response code (should be 2xx, even in case of error : error message is in the XML result)
        if (statusCode / 100 != 2) {
            if (statusCode == 403 && (client.getToken() != null || client.getSessionID() != null)) {
                throw new RundeckApiTokenException("Invalid Token or sessionID ! Got HTTP response '"
                        + response.getStatusLine() + "' for " + request.getURI());
            } else {
                throw new RundeckApiException.RundeckApiHttpStatusException(
                        "Invalid HTTP response '" + response.getStatusLine() + "' for " + request.getURI(),
                        statusCode);
            }
        }
        if (statusCode == 204) {
            return null;
        }
        if (response.getEntity() == null) {
            throw new RundeckApiException(
                    "Empty Rundeck response ! HTTP status line is : " + response.getStatusLine());
        }
        return handler.handle(response);
    } catch (IOException e) {
        throw new RundeckApiException("failed closing http client", e);
    }
}

From source file:illab.nabal.proxy.AbstractContext.java

/**
 * Get base string for HMAC-SHA1 encoding.
 * /*from   w  w w  . j a  v  a  2 s  .co  m*/
 * @deprecated
 * @param request
 * @return  signatureBaseString
 * @throws Exception
 */
protected String getSignatureBaseString(HttpUriRequest request) throws Exception {

    String signatureBaseString = "";

    URI uri = request.getURI();

    StringHelper strings = new StringHelper();
    strings.appendAllAtOnce(request.getMethod(), AMPERSEND, URLEncoder.encode(uri.getPath(), UTF_8), AMPERSEND);

    List<NameValuePair> oauthParams = new ArrayList<NameValuePair>();
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entry = ((HttpEntityEnclosingRequest) request).getEntity();
        if (entry instanceof UrlEncodedFormEntity) {
            List<NameValuePair> params = URLEncodedUtils.parse(entry);
            if (params != null) {
                oauthParams.addAll(params);
            }
        }
    }

    List<NameValuePair> params = URLEncodedUtils.parse(uri, UTF_8);
    if (params != null) {
        oauthParams.addAll(params);
        if (oauthParams.size() > 0) {
            StringHelper paramStrings = new StringHelper();
            NameValuePair[] sortedParams = oauthParams.toArray(new NameValuePair[params.size()]);
            Arrays.sort(sortedParams, ParameterHelper.paramComparator);
            int paramCnt = 0;
            for (NameValuePair param : sortedParams) {
                if (paramCnt > 0) {
                    paramStrings.append(AMPERSEND);
                }
                paramStrings.append(param.getName());
                paramStrings.append(EQUAL_MARK);
                if (StringHelper.isEmpty(param.getName()) == false && OAUTH_CALLBACK.equals(param.getName())) {
                    paramStrings.append(URLEncoder.encode(param.getValue(), UTF_8));
                } else {
                    paramStrings.append(StringHelper.nvl(param.getValue()));
                }
                paramCnt++;
            }
            strings.append(URLEncoder.encode(paramStrings.toString(), UTF_8));

            paramStrings = null;
            sortedParams = null;
            params = null;
            oauthParams = null;
        }
    }

    signatureBaseString = strings.toString();

    strings = null;

    return signatureBaseString;
}

From source file:com.twitter.hbc.httpclient.auth.OAuth1.java

@Override
public void signRequest(HttpUriRequest request, String postParams) {
    // TODO: this is a little odd: we already encoded the values earlier, but using URLEncodedUtils.parse will decode the values,
    // which we will encode again.
    List<NameValuePair> httpGetParams = URLEncodedUtils.parse(request.getURI().getRawQuery(), Charsets.UTF_8);
    List<Pair> javaParams = new ArrayList<Pair>(httpGetParams.size());
    for (NameValuePair params : httpGetParams) {
        Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
        javaParams.add(tuple);/*from w ww . java 2  s. c  o m*/
    }

    if (postParams != null) {
        List<NameValuePair> httpPostParams = URLEncodedUtils.parse(postParams, Charsets.UTF_8);

        for (NameValuePair params : httpPostParams) {
            Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
            javaParams.add(tuple);
        }
    }

    long timestampSecs = generateTimestamp();
    String nonce = generateNonce();

    OAuthParams.OAuth1Params oAuth1Params = new OAuthParams.OAuth1Params(token, consumerKey, nonce,
            timestampSecs, Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1, OAuthParams.ONE_DOT_OH);

    int port = request.getURI().getPort();
    if (port <= 0) {
        // getURI can return a -1 for a port
        if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTP_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTP_PORT;
        } else if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTPS_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTPS_PORT;
        } else {
            throw new IllegalStateException("Bad URI scheme: " + request.getURI().getScheme());
        }
    }

    String normalized = normalizer.normalize(request.getURI().getScheme(), request.getURI().getHost(), port,
            request.getMethod().toUpperCase(), request.getURI().getPath(), javaParams, oAuth1Params);

    String signature;
    try {
        signature = signer.getString(normalized, tokenSecret, consumerSecret);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> oauthHeaders = new HashMap<String, String>();
    oauthHeaders.put(OAuthParams.OAUTH_CONSUMER_KEY, quoted(consumerKey));
    oauthHeaders.put(OAuthParams.OAUTH_TOKEN, quoted(token));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE, quoted(signature));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE_METHOD, quoted(OAuthParams.HMAC_SHA1));
    oauthHeaders.put(OAuthParams.OAUTH_TIMESTAMP, quoted(Long.toString(timestampSecs)));
    oauthHeaders.put(OAuthParams.OAUTH_NONCE, quoted(nonce));
    oauthHeaders.put(OAuthParams.OAUTH_VERSION, quoted(OAuthParams.ONE_DOT_OH));
    String header = Joiner.on(", ").withKeyValueSeparator("=").join(oauthHeaders);

    request.setHeader(HttpHeaders.AUTHORIZATION, "OAuth " + header);

}

From source file:io.gs2.AbstractGs2Client.java

/**
 * ?/*from w w  w .  j  ava  2  s  . c o m*/
 * 
 * @param <U> ??
 * @param request 
 * @param clazz ??
 * @return ?
 * @throws BadRequestException ????????
 * @throws UnauthorizedException ?????????
 * @throws NotFoundException ?????????
 * @throws InternalServerErrorException ??????????
 */
protected <U> U doRequest(HttpUriRequest request, Class<U> clazz)
        throws BadRequestException, UnauthorizedException, NotFoundException, InternalServerErrorException {
    try {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000 * 30)
                .setConnectTimeout(1000 * 30).setSocketTimeout(1000 * 30).build();
        HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        ObjectMapper mapper = new ObjectMapper();

        int statusCode = 200;
        String message = null;
        int retryCount = 0;
        for (; retryCount < Gs2Constant.RETRY_NUM; retryCount++) {

            boolean timeout = false;
            try {
                HttpResponse response = client.execute(request);

                statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    if (clazz == null)
                        return null;
                    try (InputStream in = response.getEntity().getContent()) {
                        return mapper.readValue(in, clazz);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                try {
                    JsonNode json = mapper.readTree(response.getEntity().getContent());
                    message = ((TextNode) json.get("message")).asText();
                } catch (Exception e) {
                }

                if (statusCode == 504) {
                    timeout = true;
                }
            } catch (SocketTimeoutException e) {
                timeout = true;
            }
            if (timeout) {
                try {
                    Thread.sleep(Gs2Constant.RETRY_WAIT);
                } catch (InterruptedException e) {
                }
                continue;
            }
            break;
        }

        if (retryCount > 0 && request.getMethod().equals("DELETE") && statusCode == 404) {
            return null;
        }

        switch (statusCode) {
        case 400:
            throw new BadRequestException(message);
        case 401:
            throw new UnauthorizedException(message);
        case 402:
            throw new QuotaExceedException(message);
        case 404:
            throw new NotFoundException(message);
        case 409:
            throw new ConflictException(message);
        case 500:
            throw new InternalServerErrorException(message);
        case 502:
            throw new BadGatewayException(message);
        case 503:
            throw new ServiceUnavailableException(new ArrayList<>());
        case 504:
            throw new RequestTimeoutException(message);
        }
        throw new RuntimeException("[" + statusCode + "] " + (message == null ? "unknown" : message));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.personium.core.rs.box.PersoniumEngineSvcCollectionResource.java

/**
 * relay??./*from w  ww.ja va 2  s  .  c om*/
 * @param method 
 * @param uriInfo URI
 * @param path ??
 * @param headers 
 * @param is 
 * @return JAX-RS Response
 */
public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) {

    String cellName = this.davRsCmp.getCell().getName();
    String boxName = this.davRsCmp.getBox().getName();
    String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", PersoniumUnitConfig.getEngineHost(),
            PersoniumUnitConfig.getEnginePort(), PersoniumUnitConfig.getEnginePath(), cellName, boxName, path);

    // baseUrl?
    String baseUrl = uriInfo.getBaseUri().toString();

    // ???
    HttpClient client = new DefaultHttpClient();
    HttpUriRequest req = null;
    if (method.equals(HttpMethod.POST)) {
        HttpPost post = new HttpPost(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        post.setEntity(ise);
        req = post;
    } else if (method.equals(HttpMethod.PUT)) {
        HttpPut put = new HttpPut(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        put.setEntity(ise);
        req = put;
    } else if (method.equals(HttpMethod.DELETE)) {
        HttpDelete delete = new HttpDelete(requestUrl);
        req = delete;
    } else {
        HttpGet get = new HttpGet(requestUrl);
        req = get;
    }

    req.addHeader("X-Baseurl", baseUrl);
    req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString());
    if (davCmp instanceof DavCmpFsImpl) {
        DavCmpFsImpl dcmp = (DavCmpFsImpl) davCmp;
        req.addHeader("X-Personium-Fs-Path", dcmp.getFsPath());
        req.addHeader("X-Personium-Fs-Routing-Id", dcmp.getCellId());
    }
    req.addHeader("X-Personium-Box-Schema", this.davRsCmp.getBox().getSchema());

    // ???
    MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders();
    for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String key = (String) entry.getKey();
        if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        }
        List<String> valueList = (List<String>) entry.getValue();
        for (Iterator<String> i = valueList.iterator(); i.hasNext();) {
            String value = (String) i.next();
            req.setHeader(key, value);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("?EngineRelay " + req.getMethod() + "  " + req.getURI());
        Header[] reqHeaders = req.getAllHeaders();
        for (int i = 0; i < reqHeaders.length; i++) {
            log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue());
        }
    }

    // Engine??
    HttpResponse objResponse = null;
    try {
        objResponse = client.execute(req);
    } catch (ClientProtocolException e) {
        throw PersoniumCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR;
    } catch (Exception ioe) {
        throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe);
    }

    // 
    ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode());
    Header[] headersResEngine = objResponse.getAllHeaders();
    // ?
    for (int i = 0; i < headersResEngine.length; i++) {
        // Engine????Transfer-Encoding????
        // ?MW????????Content-Length???Transfer-Encoding????
        // 2??????????????????????
        if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        // Engine????Date????
        // Web??MW?Jetty???2?????????
        if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        res.header(headersResEngine[i].getName(), headersResEngine[i].getValue());
    }

    InputStream isResBody = null;

    // ?
    HttpEntity entity = objResponse.getEntity();
    if (entity != null) {
        try {
            isResBody = entity.getContent();
        } catch (IllegalStateException e) {
            throw PersoniumCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e);
        } catch (IOException e) {
            throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e);
        }
        final InputStream isInvariable = isResBody;
        // ??
        StreamingOutput strOutput = new StreamingOutput() {
            @Override
            public void write(final OutputStream os) throws IOException {
                int chr;
                try {
                    while ((chr = isInvariable.read()) != -1) {
                        os.write(chr);
                    }
                } finally {
                    isInvariable.close();
                }
            }
        };
        res.entity(strOutput);
    }

    // ??
    return res.build();
}

From source file:org.deviceconnect.android.profile.restful.test.RESTfulDConnectTestCase.java

/**
 * HTTP??./*w  w w  .j a  v a 2s. c o m*/
 * @param request HTTP
 * @param requiredAuth ????????????
 * @param count ?
 * @return ?
 */
protected final JSONObject sendRequest(final HttpUriRequest request, final boolean requiredAuth,
        final int count) {
    try {
        JSONObject response = sendRequestInternal(request, requiredAuth);
        int result = response.getInt(DConnectMessage.EXTRA_RESULT);
        if (result == DConnectMessage.RESULT_ERROR && count <= RETRY_COUNT) {
            if (!response.has(DConnectMessage.EXTRA_ERROR_CODE)) {
                return response;
            }
            int errorCode = response.getInt(DConnectMessage.EXTRA_ERROR_CODE);
            if (errorCode == DConnectMessage.ErrorCode.EXPIRED_ACCESS_TOKEN.getCode()) {
                mAccessToken = requestAccessToken(mClientId, mClientSecret, PROFILES);
                assertNotNull(mAccessToken);
                storeOAuthInfo(mClientId, mClientSecret, mAccessToken);

                URI uri = request.getURI();
                URIBuilder builder = new URIBuilder(uri);
                builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());

                final HttpUriRequest newRequest;
                if (request instanceof HttpGet) {
                    newRequest = new HttpGet(builder.toString());
                } else if (request instanceof HttpPost) {
                    HttpPost newPostRequest = new HttpPost(builder.toString());
                    newPostRequest.setEntity(((HttpPost) request).getEntity());
                    newRequest = newPostRequest;
                } else if (request instanceof HttpPut) {
                    HttpPut newPostRequest = new HttpPut(builder.toString());
                    newPostRequest.setEntity(((HttpPost) request).getEntity());
                    newRequest = newPostRequest;
                } else if (request instanceof HttpDelete) {
                    newRequest = new HttpDelete(builder.toString());
                } else {
                    fail("Invalid method is specified: " + request.getMethod());
                    return null;
                }
                return sendRequest(newRequest, requiredAuth, count + 1);
            }
        }
        return response;
    } catch (JSONException e) {
        Assert.fail("IOException: " + e.getMessage());
    }
    return null;
}

From source file:com.fujitsu.dc.core.rs.box.DcEngineSvcCollectionResource.java

/**
 * relay??./*from   ww  w . j a v a 2 s  .  co m*/
 * @param method 
 * @param uriInfo URI
 * @param path ??
 * @param headers 
 * @param is 
 * @return JAX-RS Response
 */
public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) {

    String cellName = this.davRsCmp.getCell().getName();
    String boxName = this.davRsCmp.getBox().getName();
    String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", DcCoreConfig.getEngineHost(),
            DcCoreConfig.getEnginePort(), DcCoreConfig.getEnginePath(), cellName, boxName, path);

    // baseUrl?
    String baseUrl = uriInfo.getBaseUri().toString();

    // ???
    HttpClient client = new DefaultHttpClient();
    HttpUriRequest req = null;
    if (method.equals(HttpMethod.POST)) {
        HttpPost post = new HttpPost(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        post.setEntity(ise);
        req = post;
    } else if (method.equals(HttpMethod.PUT)) {
        HttpPut put = new HttpPut(requestUrl);
        InputStreamEntity ise = new InputStreamEntity(is, -1);
        ise.setChunked(true);
        put.setEntity(ise);
        req = put;
    } else if (method.equals(HttpMethod.DELETE)) {
        HttpDelete delete = new HttpDelete(requestUrl);
        req = delete;
    } else {
        HttpGet get = new HttpGet(requestUrl);
        req = get;
    }

    req.addHeader("X-Baseurl", baseUrl);
    req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString());
    // ?INDEXIDTYPE?
    if (davCmp instanceof DavCmpEsImpl) {
        DavCmpEsImpl test = (DavCmpEsImpl) davCmp;
        req.addHeader("X-Dc-Es-Index", test.getEsColType().getIndex().getName());
        req.addHeader("X-Dc-Es-Id", test.getNodeId());
        req.addHeader("X-Dc-Es-Type", test.getEsColType().getType());
        req.addHeader("X-Dc-Es-Routing-Id", this.davRsCmp.getCell().getId());
        req.addHeader("X-Dc-Box-Schema", this.davRsCmp.getBox().getSchema());
    }

    // ???
    MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders();
    for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String key = (String) entry.getKey();
        if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        }
        List<String> valueList = (List<String>) entry.getValue();
        for (Iterator<String> i = valueList.iterator(); i.hasNext();) {
            String value = (String) i.next();
            req.setHeader(key, value);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("?EngineRelay " + req.getMethod() + "  " + req.getURI());
        Header[] reqHeaders = req.getAllHeaders();
        for (int i = 0; i < reqHeaders.length; i++) {
            log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue());
        }
    }

    // Engine??
    HttpResponse objResponse = null;
    try {
        objResponse = client.execute(req);
    } catch (ClientProtocolException e) {
        throw DcCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR;
    } catch (Exception ioe) {
        throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe);
    }

    // 
    ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode());
    Header[] headersResEngine = objResponse.getAllHeaders();
    // ?
    for (int i = 0; i < headersResEngine.length; i++) {
        // Engine????Transfer-Encoding????
        // ?MW????????Content-Length???Transfer-Encoding????
        // 2??????????????????????
        if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        // Engine????Date????
        // Web??MW?Jetty???2?????????
        if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) {
            continue;
        }
        res.header(headersResEngine[i].getName(), headersResEngine[i].getValue());
    }

    InputStream isResBody = null;

    // ?
    HttpEntity entity = objResponse.getEntity();
    if (entity != null) {
        try {
            isResBody = entity.getContent();
        } catch (IllegalStateException e) {
            throw DcCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e);
        } catch (IOException e) {
            throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e);
        }
        final InputStream isInvariable = isResBody;
        // ??
        StreamingOutput strOutput = new StreamingOutput() {
            @Override
            public void write(final OutputStream os) throws IOException {
                int chr;
                try {
                    while ((chr = isInvariable.read()) != -1) {
                        os.write(chr);
                    }
                } finally {
                    isInvariable.close();
                }
            }
        };
        res.entity(strOutput);
    }

    // ??
    return res.build();
}

From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java

private void signRequest(HttpUriRequest request, String postParams, String token, String tokenSecret,
        String consumerKey, String consumerSecret) {
    // TODO: this is a little odd: we already encoded the values earlier, but using URLEncodedUtils.parse will decode the values,
    // which we will encode again.
    List<NameValuePair> httpGetParams = null;

    if (request.getURI().getRawQuery() == null) {
        httpGetParams = new ArrayList<NameValuePair>();
    } else {//from w ww.j a v  a2  s.  co m
        httpGetParams = URLEncodedUtils.parse(request.getURI().getRawQuery(), Charsets.UTF_8);
    }

    List<Pair> javaParams = new ArrayList<Pair>(httpGetParams.size());
    for (NameValuePair params : httpGetParams) {
        Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
        javaParams.add(tuple);
    }

    if (postParams != null) {
        List<NameValuePair> httpPostParams = URLEncodedUtils.parse(postParams, Charsets.UTF_8);

        for (NameValuePair params : httpPostParams) {
            Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
            javaParams.add(tuple);
        }
    }

    long timestampSecs = generateTimestamp();
    String nonce = generateNonce();

    OAuthParams.OAuth1Params oAuth1Params = new OAuthParams.OAuth1Params(token, consumerKey, nonce,
            timestampSecs, Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1, OAuthParams.ONE_DOT_OH);

    int port = request.getURI().getPort();
    if (port <= 0) {
        // getURI can return a -1 for a port
        if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTP_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTP_PORT;
        } else if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTPS_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTPS_PORT;
        } else {
            throw new IllegalStateException("Bad URI scheme: " + request.getURI().getScheme());
        }
    }

    String normalized = Normalizer.getStandardNormalizer().normalize(request.getURI().getScheme(),
            request.getURI().getHost(), port, request.getMethod().toUpperCase(), request.getURI().getPath(),
            javaParams, oAuth1Params);

    String signature;
    try {
        signature = Signer.getStandardSigner().getString(normalized, tokenSecret, consumerSecret);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> oauthHeaders = new HashMap<String, String>();
    oauthHeaders.put(OAuthParams.OAUTH_CONSUMER_KEY, quoted(consumerKey));
    oauthHeaders.put(OAuthParams.OAUTH_TOKEN, quoted(token));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE, quoted(signature));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE_METHOD, quoted(OAuthParams.HMAC_SHA1));
    oauthHeaders.put(OAuthParams.OAUTH_TIMESTAMP, quoted(Long.toString(timestampSecs)));
    oauthHeaders.put(OAuthParams.OAUTH_NONCE, quoted(nonce));
    oauthHeaders.put(OAuthParams.OAUTH_VERSION, quoted(OAuthParams.ONE_DOT_OH));
    String header = Joiner.on(", ").withKeyValueSeparator("=").join(oauthHeaders);

    request.setHeader(HttpHeaders.AUTHORIZATION, "OAuth " + header);

}