Java Code Examples for org.apache.http.HttpResponse#addHeader()

The following examples show how to use org.apache.http.HttpResponse#addHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testSpecialCharacterInErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    HttpEntity httpEntity = new StringEntity("é", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("é", HttpResponseUtils.toString(driverResponse));
}
 
Example 2
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testHeadersPreservedWhenError500() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Dummy", "dummy");
    HttpEntity httpEntity = new StringEntity("Error", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    int statusCode = driverResponse.getStatusLine().getStatusCode();
    assertEquals("Status code", HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
    assertTrue("Header 'Dummy'", driverResponse.containsHeader("Dummy"));
}
 
Example 3
Source File: HttpClientRequestExecutorTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Test with a cookie sent in the response that contains spaces in the value.
 * 
 * @throws Exception
 */
public void testCookieWithSpaces() throws Exception {
    properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") //
            .set(Parameters.USE_CACHE, false) // Default value
            .build();

    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request =
            httpClientRequestExecutor.createOutgoingRequest(originalRequest, "http://localhost:8080", false);
    HttpResponse response = createMockResponse("");
    response.addHeader("Set-Cookie", "test=\"a b\"; Version=1");
    mockConnectionManager.setResponse(response);
    httpClientRequestExecutor.execute(request);
    assertEquals(1, originalRequest.getOriginalRequest().getNewCookies().length);
    assertEquals("a b", originalRequest.getOriginalRequest().getNewCookies()[0].getValue());
}
 
Example 4
Source File: ApacheHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
Example 5
Source File: HttpClientRequestExecutorTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * 
 * @throws Exception
 */
public void testForcedTtlWith302ResponseCode() throws Exception {
    properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") //
            .set(Parameters.TTL, 1000) //
            .build();

    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request =
            httpClientRequestExecutor.createOutgoingRequest(originalRequest, "http://localhost:8080", true);
    HttpResponse response =
            new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
                    HttpStatus.SC_MOVED_TEMPORARILY, "Moved temporarily"));
    response.addHeader("Location", "http://www.foo.com");
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}
 
Example 6
Source File: RequestHeaderAuthenticationStrategy.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Map<String, Header> getChallenges(
    final HttpHost authhost, final HttpResponse response, final HttpContext context)
    throws MalformedChallengeException
{
  HttpRequest request = (HttpRequest) context.getAttribute(REQUEST_ATTRIBUTE);
  if (request != null) {
    Optional<Header> bearerTokenRequestOpt = getBearerHeader(request, HttpHeaders.AUTHORIZATION);
    Optional<Header> bearerTokenResponseOpt = getBearerHeader(response, HttpHeaders.WWW_AUTHENTICATE);

    /*
      Add necessary bearer token from request to response if it's absent, it's required for avoid infinite loop in docker
      (see NEXUS-23360)
     */
    if (bearerTokenRequestOpt.isPresent() && !bearerTokenResponseOpt.isPresent()) {
      response.addHeader(HttpHeaders.WWW_AUTHENTICATE, bearerTokenRequestOpt.get().getValue());
    }
  }
  return super.getChallenges(authhost, response, context);
}
 
Example 7
Source File: HttpServerUtilities.java    From Repeat with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an HTTP redirect response. Note that this uses code 302, not 301.
 *
 * @param dest path to the destination. This is absolute path not including the domain.
 */
public static Void redirect(HttpAsyncExchange exchange, String dest, Map<String, String> params) throws IOException {
	String location = "";
	try {
		URIBuilder builder = new URIBuilder(exchange.getRequest().getRequestLine().getUri());
		builder.clearParameters();
		for (Entry<String, String> entry : params.entrySet()) {
			builder.setParameter(entry.getKey(), entry.getValue());
		}
		location = builder.setPath(dest).build().toString();
	} catch (URISyntaxException e) {
		LOGGER.log(Level.WARNING, "Unable to parse request URI.", e);
		return prepareTextResponse(exchange, 500, "Unable to parse request URI.");
	}

	HttpResponse response = exchange.getResponse();
	response.setStatusCode(302);
	response.addHeader("Location", location);
	exchange.submitResponse(new BasicAsyncResponseProducer(response));
	return null;
}
 
Example 8
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * 0000174: Redirect location with default port specified are incorrectly rewritten when preserveHost=true
 * <p>
 * http://www.esigate.org/mantisbt/view.php?id=174
 * 
 * <p>
 * Issue with default ports, which results in invalid url creation.
 * 
 * @throws Exception
 */
public void testRewriteRedirectResponseWithDefaultPortSpecifiedInLocation() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://www.foo.com:8080") //
            .set(Parameters.PRESERVE_HOST, true) //
            .build();

    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_MOVED_TEMPORARILY, "Found");
    // The backend server sets the port even if default (OK it should not
    // but some servers do it)
    response.addHeader("Location", "http://www.foo.com:80/foo/bar");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    request = TestUtils.createIncomingRequest("http://www.foo.com:80/foo");
    // HttpClientHelper will use the Host
    // header to rewrite the request sent to the backend
    // http://www.foo.com/foo
    CloseableHttpResponse driverResponse = driver.proxy("/foo", request.build());
    // The test initially failed with an invalid Location:
    // http://www.foo.com:80:80/foo/bar
    assertEquals("http://www.foo.com:80/foo/bar", driverResponse.getFirstHeader("Location").getValue());
}
 
Example 9
Source File: PassThroughNHttpGetProcessor.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the services list.
 *
 * @param response    HttpResponse
 * @param conn        NHttpServerConnection
 * @param os          OutputStream
 * @param servicePath service path of the service
 */
protected void generateServicesList(HttpResponse response,
                                    NHttpServerConnection conn,
                                    OutputStream os, String servicePath) {
    try {
        byte[] bytes = getServicesHTML(
                servicePath.endsWith("/") ? "" : servicePath + "/").getBytes();
        response.addHeader(CONTENT_TYPE, TEXT_HTML);
        SourceContext.updateState(conn, ProtocolState.WSDL_RESPONSE_DONE);
        sourceHandler.commitResponseHideExceptions(conn, response);
        os.write(bytes);

    } catch (IOException e) {
        handleBrowserException(response, conn, os,
                "Error generating services list", e);
    }
}
 
Example 10
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
HttpResponse callBackend(HttpHost target, HttpRequest request,
		HttpContext context) throws IOException {

	Date requestDate = getCurrentDate();

	log.debug("Calling the backend");
	HttpResponse backendResponse = backend
			.execute(target, request, context);
	backendResponse.addHeader("Via", generateViaHeader(backendResponse));
	return handleBackendResponse(target, request, requestDate,
			getCurrentDate(), backendResponse);

}
 
Example 11
Source File: DriverTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Test bug Bug 142 (1st case).
 * <p>
 * 0000142: Error with 304 backend responses
 * <p>
 * NPE in Apache HTTP CLient cache
 * <p>
 * See :http://www.esigate.org/mantisbt/view.php?id=142
 * 
 * @throws Exception
 */
public void testBug142() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://www.foo.com/");
    properties.put(Parameters.TTL.getName(), "43200");
    properties.put(Parameters.PRESERVE_HOST.getName(), "true");
    properties.put(Parameters.USE_CACHE.getName(), true);

    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_NOT_MODIFIED, "Not Modified");
    response.addHeader("Etag", "b5e3f57c0e84fc7a197b849fdfd3d407");
    response.addHeader("Date", "Thu, 13 Dec 2012 07:28:01 GMT");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);

    // First request
    request = TestUtils.createIncomingRequest("http://www.bar.com/foo/");
    request.addHeader("If-None-Match", "b5e3f57c0e84fc7a197b849fdfd3d407");
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml");
    request.addHeader("If-Modified-Since", "Fri, 15 Jun 2012 21:06:25 GMT");
    request.addHeader("Cache-Control", "max-age=0");
    CloseableHttpResponse driverResponse = driver.proxy("/foo/", request.build());
    assertEquals(HttpStatus.SC_NOT_MODIFIED, driverResponse.getStatusLine().getStatusCode());

    // Second request
    request = TestUtils.createIncomingRequest("http://www.bar.com/foo/");
    request.addHeader("If-None-Match", "b5e3f57c0e84fc7a197b849fdfd3d407");
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml");
    request.addHeader("If-Modified-Since", "Fri, 15 Jun 2012 21:06:25 GMT");
    request.addHeader("Cache-Control", "max-age=0");

    driverResponse = driver.proxy("/foo/", request.build());
    assertEquals(HttpStatus.SC_NOT_MODIFIED, driverResponse.getStatusLine().getStatusCode());
}
 
Example 12
Source File: MockServer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage));
    setEntity(response, content);
    response.addHeader("Content-Length", String.valueOf(content.getBytes().length));
    response.addHeader("Connection", "close");
    return new DummyResponseServerBehavior(response);
}
 
Example 13
Source File: AsyncRequestWrapperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private AsyncRequestWrapperImpl createAsyncRequestWrapperImplWithRetryAfter(int retryAfter)
    throws IOException, URISyntaxException {

  HttpClient httpClient = mock(HttpClient.class);
  ODataClient oDataClient = mock(ODataClient.class);
  Configuration configuration = mock(Configuration.class);
  HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
  HttpUriRequestFactory httpUriRequestFactory = mock(HttpUriRequestFactory.class);
  HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);

  when(oDataClient.getConfiguration()).thenReturn(configuration);
  when(configuration.getHttpClientFactory()).thenReturn(httpClientFactory);
  when(configuration.getHttpUriRequestFactory()).thenReturn(httpUriRequestFactory);
  when(httpClientFactory.create(any(), any())).thenReturn(httpClient);
  when(httpUriRequestFactory.create(any(), any())).thenReturn(httpUriRequest);

  HttpResponseFactory factory = new DefaultHttpResponseFactory();
  HttpResponse firstResponse = factory.newHttpResponse(
      new BasicStatusLine(HttpVersion.HTTP_1_1, 202, null), null);
  firstResponse.addHeader(HttpHeader.LOCATION, "http://localhost/monitor");
  firstResponse.addHeader(HttpHeader.RETRY_AFTER, String.valueOf(retryAfter));
  when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(firstResponse);

  AbstractODataRequest oDataRequest = mock(AbstractODataRequest.class);
  ODataResponse oDataResponse = mock(ODataResponse.class);
  when(oDataRequest.getResponseTemplate()).thenReturn(oDataResponse);
  when(oDataRequest.getURI()).thenReturn(new URI("http://localhost/path"));
  when(oDataResponse.initFromHttpResponse(any(HttpResponse.class))).thenReturn(null);

  return new AsyncRequestWrapperImpl(oDataClient, oDataRequest);
}
 
Example 14
Source File: ResponseProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(
		HttpRequest request, HttpResponse response) {
	if (!request.getRequestLine().getMethod()
			.equalsIgnoreCase(HeaderConstants.OPTIONS_METHOD)) {
		return;
	}

	if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
		return;
	}

	if (response.getFirstHeader(HTTP.CONTENT_LEN) == null) {
		response.addHeader(HTTP.CONTENT_LEN, "0");
	}
}
 
Example 15
Source File: DriverTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testGzipErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Content-encoding", "gzip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = "é".getBytes("UTF-8");
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("Text/html;Charset=UTF-8");
    httpEntity.setContentEncoding("gzip");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("é", HttpResponseUtils.toString(driverResponse));
}
 
Example 16
Source File: MoveResponseHeader.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * This method can be used directly to move an header.
 * 
 * @param response
 *            HTTP response
 * @param srcName
 *            source header name
 * @param targetName
 *            target header name
 */
public static void moveHeader(HttpResponse response, String srcName, String targetName) {
    if (response.containsHeader(srcName)) {
        LOG.info("Moving header {} to {}", srcName, targetName);

        Header[] headers = response.getHeaders(srcName);
        response.removeHeaders(targetName);
        for (Header h : headers) {
            response.addHeader(targetName, h.getValue());
        }
        response.removeHeaders(srcName);
    }
}
 
Example 17
Source File: PassThroughNHttpGetProcessor.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
private void processWithGetProcessor(HttpRequest request,
                                      HttpResponse response,
                                      String requestUri,
                                      String requestUrl,
                                      String queryString,
                                      String item,
                                      OutputStream outputStream,
                                      NHttpServerConnection conn) throws Exception {
     OverflowBlob temporaryData = new OverflowBlob(256, 4048, "_nhttp", ".dat");
     try {
         CarbonHttpRequest carbonHttpRequest = new CarbonHttpRequest(
                 "GET", requestUri, requestUrl);

         String uri = request.getRequestLine().getUri();
         // setting the parameters for nhttp transport
         int pos = uri.indexOf("?");
         if (pos != -1) {
             StringTokenizer st = new StringTokenizer(uri.substring(pos + 1), "&");
             while (st.hasMoreTokens()) {
                 String param = st.nextToken();
                 pos = param.indexOf("=");
                 if (pos != -1) {
                     carbonHttpRequest.setParameter(
                             param.substring(0, pos), param.substring(pos + 1));
                 } else {
                     carbonHttpRequest.setParameter(param, null);
                 }
             }
         }

         carbonHttpRequest.setContextPath(cfgCtx.getServiceContextPath());
         carbonHttpRequest.setQueryString(queryString);

         CarbonHttpResponse carbonHttpResponse = new CarbonHttpResponse(
                 temporaryData.getOutputStream());

         (getRequestProcessors.get(item)).process(carbonHttpRequest, carbonHttpResponse, cfgCtx);
         
          // adding headers
         Map<String, String> responseHeaderMap = carbonHttpResponse.getHeaders();
         for (Object key : responseHeaderMap.keySet()) {
             Object value = responseHeaderMap.get(key);
             response.addHeader(key.toString(), value.toString());
         }

         // setting status code
         response.setStatusCode(carbonHttpResponse.getStatusCode());

         // setting error codes
         if (carbonHttpResponse.isError()) {
             if (carbonHttpResponse.getStatusMessage() != null) {
                 response.setStatusLine(response.getProtocolVersion(),
                         carbonHttpResponse.getStatusCode(),
                         carbonHttpResponse.getStatusMessage());
             } else {
                 response.setStatusLine(response.getProtocolVersion(),
                         carbonHttpResponse.getStatusCode());
             }
         }

         if (carbonHttpResponse.isRedirect()) {
             response.addHeader("Location", carbonHttpResponse.getRedirect());
             response.setStatusLine(response.getProtocolVersion(), 302);
         }

         SourceContext.updateState(conn, ProtocolState.WSDL_RESPONSE_DONE);
        
         
         try{
         temporaryData.writeTo(outputStream);
         }catch (Exception e) {
	e.printStackTrace();
}

         try {
             outputStream.flush();
             outputStream.close();
         } catch (Exception ignored) {}
     } finally {
         temporaryData.release();
         sourceHandler.commitResponseHideExceptions(conn, response);
         
     }
 }
 
Example 18
Source File: MixerHttpClientTest.java    From beam-client-java with MIT License 4 votes vote down vote up
@Test
public void itHandlesJWT() {
    mixerAPI = new MixerAPI("clientId");
    defaultHttpClient = mock(HttpClient.class);

    final String jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjU3NDk5NSwiYnR5cCI6ImdyYW50IiwiZ3JvdXBzIjpbeyJpZCI6MSwibmFtZSI6IlVzZXIiLCJVc2VyR3JvdXAiOnsiZ3JvdXBJZCI6MSwidXNlcklkIjo1NzQ5OTV9fV0sImlhdCI6MTQ4MTE0NDQ0NywiZXhwIjoxNTEyNjgwNDQ3LCJpc3MiOiJCZWFtIiwianRpIjoiVGhpcyBpc24ndCBhIHJlYWwgc2Vzc2lvbi4ifQ==.HkL5xq-eivwCk5OgczgIu5s_NFFxdQAKH9Jfb906aT4";

    final JSONWebToken.Group jwtGroup = new JSONWebToken.Group();
    jwtGroup.id = 1L;
    jwtGroup.name = "User";

    final JSONWebToken jwt = new JSONWebToken();
    jwt.exp = 1512680447L;
    jwt.iat = 1481144447L;
    jwt.iss = "Mixer";
    jwt.jti = "This isn't a real session.";
    jwt.sub = 574995L;
    jwt.btyp = "grant";
    jwt.groups = new JSONWebToken.Group[]{jwtGroup};

    // This is done because Mockito is not able to mock methods that are called within the class'
    // Constructor.
    class MockableMixerHttpClient extends MixerHttpClient {
        private MockableMixerHttpClient(MixerAPI mixer) {
            super(mixer, "clientId");
        }

        @Override
        protected HttpClient buildHttpClient() {
            return defaultHttpClient;
        }
    }

    mixerHttpClient = new MockableMixerHttpClient(mixerAPI);

    HttpResponse okResponse = prepareResponse(200, "{\"id\":314,\"userId\":344,\"token\":\"Mixer\",\"online\":false,\"featured\":false,\"partnered\":false,\"transcodingProfileId\":1,\"suspended\":false,\"name\":\"Weekly Updates and more!\"}");
    okResponse.addHeader(new BasicHeader(X_JWT_HEADER, jwtString));

    try {
        doReturn(okResponse).when(defaultHttpClient).execute(any(HttpUriRequest.class), isNull(HttpContext.class));
    } catch (IOException e) {
        Assert.fail();
    }

    Futures.addCallback(mixerHttpClient.get("/channels/314", MixerUser.class, null), new FutureCallback<MixerUser>() {
        @Override
        public void onSuccess(MixerUser mixerUser) {
            Assert.assertEquals(mixerHttpClient.getJWTString(), jwtString);
            Assert.assertEquals(mixerHttpClient.getJwt(), jwt);
        }

        @Override
        public void onFailure(Throwable throwable) {
            Assert.fail();
        }
    });
}
 
Example 19
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
HttpResponse revalidateCacheEntry(HttpHost target, HttpRequest request,
		HttpContext context, HttpCacheEntry cacheEntry) throws IOException,
		ProtocolException {
	HttpRequest conditionalRequest = conditionalRequestBuilder
			.buildConditionalRequest(request, cacheEntry);

	Date requestDate = getCurrentDate();
	HttpResponse backendResponse = backend.execute(target,
			conditionalRequest, context);
	Date responseDate = getCurrentDate();

	final Header entryDateHeader = cacheEntry.getFirstHeader("Date");
	final Header responseDateHeader = backendResponse
			.getFirstHeader("Date");
	if (entryDateHeader != null && responseDateHeader != null) {
		try {
			Date entryDate = DateUtils
					.parseDate(entryDateHeader.getValue());
			Date respDate = DateUtils.parseDate(responseDateHeader
					.getValue());
			if (respDate.before(entryDate)) {
				HttpRequest unconditional = conditionalRequestBuilder
						.buildUnconditionalRequest(request, cacheEntry);
				requestDate = getCurrentDate();
				backendResponse = backend.execute(target, unconditional,
						context);
				responseDate = getCurrentDate();
			}
		} catch (DateParseException e) {
			// either backend response or cached entry did not have a valid
			// Date header, so we can't tell if they are out of order
			// according to the origin clock; thus we can skip the
			// unconditional retry recommended in 13.2.6 of RFC 2616.
		}
	}

	backendResponse.addHeader("Via", generateViaHeader(backendResponse));

	int statusCode = backendResponse.getStatusLine().getStatusCode();
	if (statusCode == HttpStatus.SC_NOT_MODIFIED
			|| statusCode == HttpStatus.SC_OK) {
		cacheUpdates.getAndIncrement();
		setResponseStatus(context, CacheResponseStatus.VALIDATED);
	}

	if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
		HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(
				target, request, cacheEntry, backendResponse, requestDate,
				responseDate);
		if (suitabilityChecker.isConditional(request)
				&& suitabilityChecker.allConditionalsMatch(request,
						updatedEntry, new Date())) {
			return responseGenerator
					.generateNotModifiedResponse(updatedEntry);
		}
		return responseGenerator.generateResponse(updatedEntry);
	}

	return handleBackendResponse(target, conditionalRequest, requestDate,
			responseDate, backendResponse);
}
 
Example 20
Source File: DapTestCommon.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpResponse execute(HttpRequestBase rq) throws IOException {
  URI uri = rq.getURI();
  DapController controller = getController(uri);
  StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller);
  mvcbuilder.setValidator(new TestServlet.NullValidator());
  MockMvc mockMvc = mvcbuilder.build();
  MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri);
  // We need to use only the path part
  mockrb.servletPath(uri.getPath());
  // Move any headers from rq to mockrb
  Header[] headers = rq.getAllHeaders();
  for (int i = 0; i < headers.length; i++) {
    Header h = headers[i];
    mockrb.header(h.getName(), h.getValue());
  }
  // Since the url has the query parameters,
  // they will automatically be parsed and added
  // to the rb parameters.

  // Finally set the resource dir
  mockrb.requestAttr("RESOURCEDIR", this.resourcepath);

  // Now invoke the servlet
  MvcResult result;
  try {
    result = mockMvc.perform(mockrb).andReturn();
  } catch (Exception e) {
    throw new IOException(e);
  }

  // Collect the output
  MockHttpServletResponse res = result.getResponse();
  byte[] byteresult = res.getContentAsByteArray();

  // Convert to HttpResponse
  HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), "");
  if (response == null)
    throw new IOException("HTTPMethod.executeMock: Response was null");
  Collection<String> keys = res.getHeaderNames();
  // Move headers to the response
  for (String key : keys) {
    List<String> values = res.getHeaders(key);
    for (String v : values) {
      response.addHeader(key, v);
    }
  }
  ByteArrayEntity entity = new ByteArrayEntity(byteresult);
  String sct = res.getContentType();
  entity.setContentType(sct);
  response.setEntity(entity);
  return response;
}