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

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

Introduction

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

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:org.dasein.cloud.azurepack.tests.compute.AzurePackVirtualMachineSupportTest.java

@Test
public void terminateShouldSendCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger deleteCount = new AtomicInteger(0);
    new GetOrListVirtualMachinesRequestExecutorMockUp() {
        @Mock//ww w .  ja  v  a 2 s .  c o m
        public void $init(CloudProvider provider, HttpClientBuilder clientBuilder, HttpUriRequest request,
                ResponseHandler handler) {
            String requestUri = request.getURI().toString();
            if (request.getMethod().equals("DELETE") && requestUri
                    .equals(String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) {
                requestResourceType = 11;
            } else {
                super.$init(provider, clientBuilder, request, handler);
            }
        }

        @Mock
        public Object execute() {
            if (requestResourceType == 11) {
                deleteCount.incrementAndGet();
                return "";
            } else {
                return super.execute();
            }
        }
    };
    azurePackVirtualMachineSupport.terminate(VM_1_ID, "no reason");
    assertEquals("terminate doesn't send DELETE request", 1, deleteCount.get());
}

From source file:org.fcrepo.apix.registry.impl.HttpRegistry.java

private CloseableHttpResponse execute(final HttpUriRequest request) {
    CloseableHttpResponse response = null;

    try {//from   w w w  . ja  v  a  2s.c  om
        response = client.execute(request);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final int code = response.getStatusLine().getStatusCode();
    if (code != SC_OK) {
        try {
            if (code == SC_NOT_FOUND || code == SC_GONE) {
                throw new ResourceNotFoundException("HTTP " + code + ": " + request.getURI());
            }

            try {
                LOG.warn(IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF_8")));
            } catch (final Exception e) {
                LOG.warn(Integer.toString(response.getStatusLine().getStatusCode()));
            }
            throw new RuntimeException(String.format("Error performing %s on %s: %s; %s", request.getMethod(),
                    request.getURI(), response.getStatusLine(), body(response)));

        } finally {
            try {
                response.close();
            } catch (final IOException e) {
                // nothing
            }
        }
    }

    return response;
}

From source file:org.opensaml.soap.client.http.AbstractPipelineHttpSOAPClient.java

/**
 * Check that trust engine evaluation of the server TLS credential was actually performed.
 * //from  w ww . j av a 2 s.c o  m
 * @param context the current HTTP context instance in use
 * @param request the HTTP URI request
 * @throws SSLPeerUnverifiedException thrown if the TLS credential was not actually evaluated by the trust engine
 */
protected void checkTLSCredentialTrusted(@Nonnull final HttpClientContext context,
        @Nonnull final HttpUriRequest request) throws SSLPeerUnverifiedException {
    if (context.getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_TRUST_ENGINE) != null
            && "https".equalsIgnoreCase(request.getURI().getScheme())) {
        if (context
                .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED) == null) {
            log.warn("Configured TLS trust engine was not used to verify server TLS credential, "
                    + "the appropriate socket factory was likely not configured");
            throw new SSLPeerUnverifiedException(
                    "Evaluation of server TLS credential with configured TrustEngine was not performed");
        }
    }
}

From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java

private <T> T extractContent(Class<T> type, HttpUriRequest request, HttpResponse response) throws IOException {
    assert request != null;
    assert response != null;
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new IOException(MessageFormat.format("Response message was invalid (empty): {0} ({1})",
                request.getURI(), response.getStatusLine()));
    }//from ww w  . j a v  a2 s .com

    try (Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING));) {
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(reader);
        if ((element instanceof JsonObject) == false) {
            throw new IOException(
                    MessageFormat.format("Response message was not a valid json object: {0} ({1})",
                            request.getURI(), response.getStatusLine()));
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("response: {}", new Object[] { element });
        }
        return GSON_BUILDER.create().fromJson(element, type);
    } catch (RuntimeException e) {
        throw new IOException(MessageFormat.format("Response message was invalid (not JSON): {0} ({1})",
                request.getURI(), response.getStatusLine()), e);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final String url) throws DSSException {

    final HttpClient client = getHttpClient(url);

    final String host = httpRequest.getURI().getHost();
    final int port = httpRequest.getURI().getPort();
    final String scheme = httpRequest.getURI().getScheme();
    final HttpHost targetHost = new HttpHost(host, port, scheme);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {//  www  .j a  va 2 s.  c  o m
        final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
        return response;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:org.springframework.cloud.netflix.ribbon.apache.RetryableRibbonLoadBalancingHttpClient.java

@Override
public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request,
        final IClientConfig configOverride) throws Exception {
    final RequestConfig.Builder builder = RequestConfig.custom();
    IClientConfig config = configOverride != null ? configOverride : this.config;
    builder.setConnectTimeout(config.get(CommonClientConfigKey.ConnectTimeout, this.connectTimeout));
    builder.setSocketTimeout(config.get(CommonClientConfigKey.ReadTimeout, this.readTimeout));
    builder.setRedirectsEnabled(config.get(CommonClientConfigKey.FollowRedirects, this.followRedirects));

    final RequestConfig requestConfig = builder.build();
    final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryPolicyFactory.create(this.getClientName(),
            this);
    RetryCallback retryCallback = new RetryCallback() {
        @Override/*from  w  w  w.  j  a v a 2s  .  co  m*/
        public RibbonApacheHttpResponse doWithRetry(RetryContext context) throws Exception {
            //on retries the policy will choose the server and set it in the context
            //extract the server and update the request being made
            RibbonApacheHttpRequest newRequest = request;
            if (context instanceof LoadBalancedRetryContext) {
                ServiceInstance service = ((LoadBalancedRetryContext) context).getServiceInstance();
                if (service != null) {
                    //Reconstruct the request URI using the host and port set in the retry context
                    newRequest = newRequest
                            .withNewUri(new URI(service.getUri().getScheme(), newRequest.getURI().getUserInfo(),
                                    service.getHost(), service.getPort(), newRequest.getURI().getPath(),
                                    newRequest.getURI().getQuery(), newRequest.getURI().getFragment()));
                }
            }
            if (isSecure(configOverride)) {
                final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri()).scheme("https").build()
                        .toUri();
                newRequest = newRequest.withNewUri(secureUri);
            }
            HttpUriRequest httpUriRequest = newRequest.toRequest(requestConfig);
            final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate
                    .execute(httpUriRequest);
            if (retryPolicy.retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) {
                throw new RetryableStatusCodeException(RetryableRibbonLoadBalancingHttpClient.this.clientName,
                        httpResponse.getStatusLine().getStatusCode());
            }
            return new RibbonApacheHttpResponse(httpResponse, httpUriRequest.getURI());
        }
    };
    return this.executeWithRetry(request, retryPolicy, retryCallback);
}

From source file:ch.entwine.weblounge.test.harness.content.ImagesTest.java

/**
 * Tests for the correctness of the English original image response.
 * //w ww  . jav  a2 s  .c  om
 * @param response
 *          the http response
 */
private void testEnglishOriginal(HttpUriRequest request) throws Exception {
    logger.info("Requesting original English image at {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    String eTagValue = null;
    Date modificationDate = null;

    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertTrue("No content received", response.getEntity().getContentLength() > 0);

        // Test general headers
        assertEquals(1, response.getHeaders("Content-Type").length);
        assertEquals(mimetypeEnglish, response.getHeaders("Content-Type")[0].getValue());
        assertEquals(sizeEnglish, response.getEntity().getContentLength());
        assertEquals(1, response.getHeaders("Content-Disposition").length);

        // Test filename
        assertEquals("inline; filename=" + filenameEnglish,
                response.getHeaders("Content-Disposition")[0].getValue());

        // Test ETag header
        Header eTagHeader = response.getFirstHeader("ETag");
        assertNotNull(eTagHeader);
        assertNotNull(eTagHeader.getValue());
        eTagValue = eTagHeader.getValue();

        // Test Last-Modified header
        Header modifiedHeader = response.getFirstHeader("Last-Modified");
        assertNotNull(modifiedHeader);
        modificationDate = lastModifiedDateFormat.parse(modifiedHeader.getValue());

        // Consume the content
        response.getEntity().consumeContent();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    TestSiteUtils.testETagHeader(request, eTagValue, logger, null);
    TestSiteUtils.testModifiedHeader(request, modificationDate, logger, null);
}

From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java

private IOException toException(HttpUriRequest request, HttpResponse response, JobStatus status,
        String message) {//from w w  w  .  ja va  2s  .  c om
    assert request != null;
    assert response != null;
    assert status != null;
    assert message != null;
    return new IOException(MessageFormat.format("{0} (uri={1}, status={2}, servercode={3}, servermessage={4})",
            message, request.getURI(), response.getStatusLine(), status.getErrorCode(),
            status.getErrorMessage()));
}

From source file:org.dasein.cloud.azurepack.tests.compute.AzurePackVirtualMachineSupportTest.java

@Test(expected = InternalException.class)
public void lauchShouldThrowExceptionIfLaunchFromVHDWithDefaultProduct()
        throws CloudException, InternalException {
    final AtomicInteger postCount = new AtomicInteger(0);
    new StartOrStopVirtualMachinesRequestExecutorMockUp("Start") {
        @Mock/*from w  w  w  .  j a  v  a2  s . co m*/
        public void $init(CloudProvider provider, HttpClientBuilder clientBuilder, HttpUriRequest request,
                ResponseHandler handler) {
            String requestUri = request.getURI().toString();
            if (request.getMethod().equals("POST")
                    && requestUri.equals(String.format(LIST_VM_RESOURCES, ENDPOINT, ACCOUNT_NO))) {
                requestResourceType = 21;
                WAPVirtualMachineModel wapVirtualMachineModel = new WAPVirtualMachineModel();
                wapVirtualMachineModel.setName(VM_1_NAME);
                wapVirtualMachineModel.setCloudId(REGION);
                wapVirtualMachineModel.setStampId(DATACENTER_ID);
                wapVirtualMachineModel.setVirtualHardDiskId(VHD_1_ID);
                wapVirtualMachineModel.setHardwareProfileId(HWP_1_ID);

                List<WAPNewAdapterModel> adapters = new ArrayList<>();
                WAPNewAdapterModel newAdapterModel = new WAPNewAdapterModel();
                newAdapterModel.setVmNetworkName(VM_1_NETWORK_NAME);
                adapters.add(newAdapterModel);
                wapVirtualMachineModel.setNewVirtualNetworkAdapterInput(adapters);
            } else {
                super.$init(provider, clientBuilder, request, handler);
            }
            responseHandler = handler;
        }

        @Mock
        public Object execute() {
            if (requestResourceType == 21) {
                postCount.incrementAndGet();
                return mapFromModel(this.responseHandler, createWAPVirtualMachineModel());
            } else {
                return super.execute();
            }
        }
    };

    VMLaunchOptions vmLaunchOptions = VMLaunchOptions.getInstance("default", VHD_1_ID, VM_1_NAME,
            VM_1_DESCRIPTION);
    vmLaunchOptions.inVlan(null, DATACENTER_ID, VM_1_NETWORK_ID);
    azurePackVirtualMachineSupport.launch(vmLaunchOptions);
}