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:com.vmware.photon.controller.api.client.resource.ApiTestBase.java

@SuppressWarnings("unchecked")
public final void setupMocksForPagination(String serializedResponse, String serializedResponseForNextPage,
        String nextPageLink, int responseCode) throws IOException {
    this.asyncHttpClient = mock(CloseableHttpAsyncClient.class);
    this.httpClient = mock(HttpClient.class);

    doAnswer(new Answer<Object>() {
        @Override/*  ww  w  . ja  va2 s  .c o  m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(this.asyncHttpClient).close();

    this.restClient = new RestClient("http://1.1.1.1", this.asyncHttpClient, this.httpClient);

    final HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(responseCode);
    when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, ContentType.APPLICATION_JSON));

    final HttpResponse httpResponseForNextPage = mock(HttpResponse.class);
    StatusLine statusLineForNextPage = mock(StatusLine.class);
    when(httpResponseForNextPage.getStatusLine()).thenReturn(statusLineForNextPage);
    when(statusLineForNextPage.getStatusCode()).thenReturn(responseCode);
    when(httpResponseForNextPage.getEntity())
            .thenReturn(new StringEntity(serializedResponseForNextPage, ContentType.APPLICATION_JSON));

    final Future<HttpResponse> httpResponseFuture = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponse;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponse;
        }
    };

    final Future<HttpResponse> httpResponseFutureForNextPage = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponseForNextPage;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponseForNextPage;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenAnswer(new Answer<HttpResponse>() {
        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
            if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                return httpResponseForNextPage;
            }
            return httpResponse;
        }
    });

    when(this.asyncHttpClient.execute(any(HttpUriRequest.class), any(BasicHttpContext.class),
            any(FutureCallback.class))).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
                    if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                        if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                            ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                    .completed(httpResponseForNextPage);
                        }
                        return httpResponseFutureForNextPage;
                    }

                    if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}

From source file:com.vmware.photon.controller.client.RestClientTest.java

@Test
public void testPerformPost() {
    String payload = "{name: DUMMY}";
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.POST,
            new StringEntity(payload, ContentType.APPLICATION_JSON));

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);/*from w  ww  .  j a  v a  2  s  .c o  m*/
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.POST.toString()));
    assertEquals(request.getURI().toString(), uri);

    HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    String actualPayload = null;
    try {
        actualPayload = IOUtils.toString(httpEntityEnclosingRequest.getEntity().getContent());
    } catch (IOException e) {
        fail(e.getMessage());
    }

    assertEquals(actualPayload, payload);
}

From source file:com.comcast.cim.rest.client.xhtml.TestRequestBuilder.java

@Test
public void testBuildsRequestWithAbsoluteURLInFormAction() throws Exception {
    Element form = new Element("form", XhtmlParser.XHTML_NS_URI);
    form.setAttribute("method", "GET");
    String absoluteUri = "http://foo.example.com/";
    form.setAttribute("action", absoluteUri);
    buildDocument(form);//from   w  w  w. j  av  a 2 s .co m
    URL context = new URL("http://www.example.com");

    HttpUriRequest result = impl.submitForm(form, context, args);
    Assert.assertEquals(absoluteUri, result.getURI().toString());
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaBaseDispatcher.java

private void retryRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.retryingRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(RETRY_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }//  ww w . ja v a 2s. c  o  m
    inboundRequest.setAttribute(RETRY_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxRetryAttempts) {
        if (retrySleep > 0) {
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.retrySleepFailed(this.resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxRetryAttemptsReached(maxRetryAttempts, this.resourceRole, outboundRequest.getURI().toString());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailure() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//from   w w  w . ja va  2  s  .  c o m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

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);/*w  w  w  .j  a va  2 s. co 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:org.apache.hadoop.gateway.rm.dispatch.RMHaBaseDispatcher.java

private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.failingOverRequest(outboundRequest.getURI().toString());
    URI uri;//from  ww w  . j av  a2 s.co m
    String outboundURIs;
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }
    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
    outboundURIs = outboundRequest.getURI().toString();

    if (counter.incrementAndGet() <= maxFailoverAttempts) {
        //null out target url so that rewriters run again
        inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);

        uri = getUriFromInbound(inboundRequest, inboundResponse, outboundURIs);
        ((HttpRequestBase) outboundRequest).setURI(uri);
        if (failoverSleep > 0) {
            try {
                Thread.sleep(failoverSleep);
            } catch (InterruptedException e) {
                LOG.failoverSleepFailed(this.resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxFailoverAttemptsReached(maxFailoverAttempts, this.resourceRole);
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:br.ufsc.das.gtscted.shibbauth.Connection.java

public String[] httpGetWithEndpoint(String url) throws IOException {
    HttpGet httpget = new HttpGet(url);
    HttpContext context = new BasicHttpContext();
    HttpResponse response = httpClient.execute(httpget, context);
    String responseAsStr = readResponse(response.getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(response.getStatusLine().toString());
    }//from   w  w w .j  ava  2 s .  c  om
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String currentUrl = currentHost.toURI() + currentReq.getURI();

    URL endpointUrl = new URL(currentUrl);
    String endpointDomain = "https://" + endpointUrl.getHost();

    String[] returnArray = { endpointDomain, responseAsStr };
    return returnArray;
}

From source file:com.comcast.cim.rest.client.xhtml.TestRequestBuilder.java

@Test
public void testBuildsRequestWithRelativeURLInFormAction() throws Exception {
    Element form = new Element("form", XhtmlParser.XHTML_NS_URI);
    form.setAttribute("method", "POST");
    form.setAttribute("action", "./baz");
    buildDocument(form);//w  w  w .  j  a v  a  2  s  . co  m
    URL context = new URL("http://www.example.com/foo/bar");

    HttpUriRequest result = impl.submitForm(form, context, args);
    Assert.assertEquals("http://www.example.com/foo/baz", result.getURI().toString());
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/*from  w w  w . j a  v  a2s  .co m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host");
    URI uri2 = new URI("http://other-host");
    URI uri3 = new URI("http://active-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString()))
            .anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest,
            outboundResponse);

    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(),
            dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}