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.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void getLoadBalancerShouldReturnNullIfIsNotExist() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock//w  ww.j  a v  a 2  s  .c om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && PROFILE_URL.equals(request.getURI().toString())) {
                assertGet(request, PROFILE_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });

                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_NOT_FOUND), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    assertNull("", loadBalancerSupport.getLoadBalancer(LB_NAME));
}

From source file:com.seajas.search.contender.service.modifier.SourceElementModifierService.java

/**
 * Retrieve the result content for the given URI.
 *
 * @param encodingOverride// w w  w  .jav  a  2  s . c  om
 * @param resultHeaders
 * @param userAgent
 * @return Content
 */
public Content getContent(final URI resultUri, final String encodingOverride,
        final Map<String, String> resultHeaders, final String userAgent) {
    URI uriAfterRedirects = null;

    // Retrieve the content

    Header contentType = null;

    try {
        InputStream inputStream;

        // Local file streams can only be read if the parent scheme is also local

        if (!resultUri.getScheme().equalsIgnoreCase("file")) {
            HttpGet method = new HttpGet(resultUri);

            if (resultHeaders != null)
                for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                    method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
            if (userAgent != null)
                method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

            HttpContext context = new BasicHttpContext();

            SizeRestrictedHttpResponse response = httpClient.execute(method,
                    new SizeRestrictedResponseHandler(maximumContentLength, resultUri), context);

            if (response != null) {
                HttpUriRequest currentRequest = (HttpUriRequest) context
                        .getAttribute(ExecutionContext.HTTP_REQUEST);
                HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                try {
                    uriAfterRedirects = new URI(currentHost.toURI()).resolve(currentRequest.getURI());
                } catch (URISyntaxException e) {
                    logger.error(String.format("Final URI '%s' is mysteriously invalid", currentHost.toURI()),
                            e);
                }

                inputStream = new ByteArrayInputStream(response.getResponse());
                contentType = response.getContentType();
            } else
                return null;
        } else
            inputStream = new FileInputStream(resultUri.getPath());

        // Convert the stream to a reset-able one

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        IOUtils.copy(inputStream, outputStream);

        inputStream.close();
        inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        outputStream.close();

        // Now determine the content type and create a reader in case of structured content

        Metadata metadata = new Metadata();

        if (encodingOverride != null && contentType != null && StringUtils.hasText(contentType.getValue())) {
            MediaType type = MediaType.parse(contentType.getValue());

            metadata.add(HttpHeaders.CONTENT_TYPE,
                    type.getType() + "/" + type.getSubtype() + "; charset=" + encodingOverride);
        } else if (contentType != null && StringUtils.hasText(contentType.getValue()))
            metadata.add(HttpHeaders.CONTENT_TYPE, contentType.getValue());
        else if (encodingOverride != null)
            metadata.add(HttpHeaders.CONTENT_ENCODING, encodingOverride);

        MediaType mediaType = autoDetectParser.getDetector().detect(inputStream, metadata);

        return new Content(new ByteArrayInputStream(outputStream.toByteArray()),
                mediaType.getBaseType() + "/" + mediaType.getSubtype(),
                contentType != null ? contentType.getValue() : null,
                uriAfterRedirects != null ? uriAfterRedirects : resultUri);
    } catch (IOException e) {
        logger.error("Could not retrieve the given URL", e);

        return null;
    }
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void listLBHealthChecksShouldReturnEmptyIfProfilesIsNotFound() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock// w w w. j a v a2 s.  c om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && PROFILES_URL.equals(request.getURI().toString())) {
                assertGet(request, PROFILES_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });

                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_NOT_FOUND), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    List<LoadBalancerHealthCheck> loadBalancerHealthChecks = IteratorUtils
            .toList(loadBalancerSupport.listLBHealthChecks(HealthCheckFilterOptions.getInstance(true)
                    .matchingProtocol(LoadBalancerHealthCheck.HCProtocol.HTTP)).iterator());
    assertEquals("LoadBalancerSupport.listLBHealthChecks() return size doesn't match", 0,
            loadBalancerHealthChecks.size());
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void getLoadBalancerHealthCheckShouldReturnCorrectResult() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock/*from   ww  w .  ja v a 2s. co m*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && DEFINITION_URL.equals(request.getURI().toString())) {
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });

                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        createDefinitionModel("Failover", "Enabled", HC_PORT));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    assertLoadBalancerHealthCheck(loadBalancerSupport.getLoadBalancerHealthCheck(LB_NAME, LB_NAME), HC_PORT);
    assertLoadBalancerHealthCheck(loadBalancerSupport.getLoadBalancerHealthCheck(LB_NAME, null), HC_PORT);
}

From source file:org.jboss.arquillian.ce.httpclient.HttpClientImpl.java

public HttpResponse execute(HttpRequest request, HttpClientExecuteOptions options) throws IOException {
    IOException exception = null;
    HttpUriRequest r = HttpRequestImpl.class.cast(request).unwrap();
    CloseableHttpResponse rawResponse = null;
    HttpResponse response = null;/*from   w w w . j a v  a 2s .com*/

    for (int i = 0; i < options.getTries(); i++) {
        try {
            if (rawResponse != null) {
                EntityUtils.consume(rawResponse.getEntity());
            }
            rawResponse = client.execute(r);
            response = new HttpResponseImpl(rawResponse);
            if (options.getDesiredStatusCode() == -1
                    || response.getResponseCode() == options.getDesiredStatusCode()) {
                return response;
            }
            System.err.println(String.format("Response error [URL:%s]: Got code %d, expected %d.", r.getURI(),
                    response.getResponseCode(), options.getDesiredStatusCode()));
        } catch (IOException e) {
            exception = e;
            System.err.println(String.format("Execute error [URL:%s]: %s.", r.getURI(), e));
        }

        if (i + 1 < options.getTries()) {
            System.err.println(String.format("Trying again in %d seconds.", options.getDelay()));
            try {
                Thread.sleep(options.getDelay() * 1000);
            } catch (InterruptedException e) {
                exception = new IOException(e);
                break;
            }
        } else {
            System.err.println(
                    String.format("Giving up trying URL:%s after %d tries", r.getURI(), options.getTries()));
        }
    }

    if (exception != null) {
        throw exception;
    }

    return response;
}

From source file:org.dasein.cloud.azure.tests.network.AzureVlanSupportTest.java

@Test
public void removeVlanShouldPostCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock/*from www.ja va  2s. com*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")
                    && VIRTUAL_NETWORK_SITES_URL.equals(request.getURI().toString())) {
                DaseinObjectToXmlEntity<VirtualNetworkSitesModel> daseinEntity = new DaseinObjectToXmlEntity<VirtualNetworkSitesModel>(
                        createVirtualNetworkSitesModel(ID, NAME, REGION, CIDR, "Updating"));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("GET".equals(request.getMethod())
                    && NETWORK_CONFIG_URL.equals(request.getURI().toString())) {
                DaseinObjectToXmlEntity<NetworkConfigurationModel> daseinEntity = new DaseinObjectToXmlEntity<NetworkConfigurationModel>(
                        createNetworkConfigurationModel(NAME, REGION, CIDR));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("PUT".equals(request.getMethod())) {
                putCount.incrementAndGet();
                NetworkConfigurationModel networkConfigurationModel = createNetworkConfigurationModel(null,
                        null, null);
                assertPut(request, NETWORK_CONFIG_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        networkConfigurationModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }

        }
    };
    vlanSupport.removeVlan(ID);
    assertEquals("removeVlan PUT network config should perform only 1 times", 1, putCount.get());
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void getLoadBalancerShouldReturnCorrectResult() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock//from  w  ww.  ja  v a  2  s.c  om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && PROFILE_URL.equals(request.getURI().toString())) {
                assertGet(request, PROFILE_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DaseinObjectToXmlEntity<ProfileModel> daseinEntity = new DaseinObjectToXmlEntity<ProfileModel>(
                        createProfileModel());

                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("GET".equals(request.getMethod())
                    && DEFINITION_URL.equals(request.getURI().toString())) {
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        createDefinitionModel("Failover", "Enabled", HC_PORT));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    LoadBalancer loadBalancer = loadBalancerSupport.getLoadBalancer(LB_NAME);
    assertLoadBalancer(loadBalancer);
}

From source file:org.dasein.cloud.azure.tests.network.AzureVlanSupportTest.java

@Test
public void removeSubnetShouldPostCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock/*from www.j  a  va  2 s .  c  om*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")
                    && VIRTUAL_NETWORK_SITES_URL.equals(request.getURI().toString())) {
                DaseinObjectToXmlEntity<VirtualNetworkSitesModel> daseinEntity = new DaseinObjectToXmlEntity<VirtualNetworkSitesModel>(
                        createVirtualNetworkSitesModelWithSubnet(ID, NAME, REGION, CIDR, "Created", SUBNET_NAME,
                                SUBNET_CIDR));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("GET".equals(request.getMethod())
                    && NETWORK_CONFIG_URL.equals(request.getURI().toString())) {
                DaseinObjectToXmlEntity<NetworkConfigurationModel> daseinEntity = new DaseinObjectToXmlEntity<NetworkConfigurationModel>(
                        createNetworkConfigurationModelWithSubnet(NAME, REGION, CIDR, SUBNET_NAME,
                                SUBNET_CIDR));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("PUT".equals(request.getMethod())) {
                putCount.incrementAndGet();
                NetworkConfigurationModel networkConfigurationModel = createNetworkConfigurationModelWithSubnet(
                        NAME, REGION, CIDR, null, null);
                assertPut(request, NETWORK_CONFIG_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        networkConfigurationModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }

        }
    };
    vlanSupport.removeSubnet(SUBNET_ID);
    assertEquals("removeVlan PUT network config should perform only 1 times", 1, putCount.get());
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test(expected = AzureException.class)
public void createLoadBalancerShouldThrowExceptionIfNameIsExist() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock/* w ww .  j  a  v a  2  s. c o  m*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("POST".equals(request.getMethod()) && PROFILES_URL.equals(request.getURI().toString())) {
                assertPost(request, PROFILES_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }, createProfileModel());

                AzureOperationStatus.AzureOperationError error = new AzureOperationStatus.AzureOperationError();
                error.setCode("BadRequest");
                error.setMessage("A conflict occurred to prevent the operation from completing.");
                DaseinObjectToXmlEntity<AzureOperationStatus.AzureOperationError> daseinEntity = new DaseinObjectToXmlEntity<AzureOperationStatus.AzureOperationError>(
                        error);

                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_BAD_REQUEST), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }

        }
    };

    HealthCheckOptions healthCheckOptions = HealthCheckOptions.getInstance(LB_NAME, HC_DESCRIPTION, null, null,
            HC_PROTOCOL, HC_PORT, HC_PATH, 9, 9, 9, 9);
    LoadBalancerCreateOptions loadBalancerCreateOptions = LoadBalancerCreateOptions.getInstance(LB_NAME,
            LB_DESCRIPTION);
    loadBalancerCreateOptions.withHealthCheckOptions(healthCheckOptions);
    loadBalancerSupport.createLoadBalancer(loadBalancerCreateOptions);
}

From source file:org.dasein.cloud.azure.tests.network.AzureLoadBalancerSupportWithMockHttpClientTest.java

@Test
public void listLoadBalancersShouldReturnCorrectResult() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock//  w w w  .  j  a v a  2 s .c o m
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if ("GET".equals(request.getMethod()) && PROFILES_URL.equals(request.getURI().toString())) {
                assertGet(request, PROFILES_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DaseinObjectToXmlEntity<ProfilesModel> daseinEntity = new DaseinObjectToXmlEntity<ProfilesModel>(
                        createProfilesModel());

                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if ("GET".equals(request.getMethod())
                    && DEFINITION_URL.equals(request.getURI().toString())) {
                assertGet(request, DEFINITION_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                DaseinObjectToXmlEntity<DefinitionModel> daseinEntity = new DaseinObjectToXmlEntity<DefinitionModel>(
                        createDefinitionModel("Failover", "Enabled", HC_PORT));
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    List<LoadBalancer> loadBalancers = IteratorUtils.toList(loadBalancerSupport.listLoadBalancers().iterator());
    assertEquals("LoadBalancerSupport.listLoadBalancers() doesn't return correct result size", 1,
            loadBalancers.size());
    LoadBalancer loadBalancer = loadBalancers.get(0);
    assertLoadBalancer(loadBalancer);
}