org.eclipse.jetty.http.HttpFields Java Examples

The following examples show how to use org.eclipse.jetty.http.HttpFields. 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: JettyReactiveHttpClient.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
protected void setUpHeaders(ReactiveHttpRequest request, HttpFields httpHeaders) {
	request.headers().forEach(httpHeaders::put);

	String acceptHeader;
	if(CharSequence.class.isAssignableFrom(returnActualClass) && returnPublisherClass == Mono.class){
		acceptHeader = TEXT;
	}
	else if(returnActualClass == ByteBuffer.class || returnActualClass == byte[].class){
		acceptHeader = APPLICATION_OCTET_STREAM;
	}
	else if(returnPublisherClass == Mono.class){
		acceptHeader = APPLICATION_JSON;
	}
	else {
		acceptHeader = APPLICATION_STREAM_JSON;
	}
	httpHeaders.put(ACCEPT.asString(), singletonList(acceptHeader));
}
 
Example #2
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
private String runRequest2(String path, Request request, Response response)
     throws IOException, ServletException {
   //request.setMethod(/*HttpMethod.GET,*/ "GET");
   HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
   HttpFields httpf = new HttpFields();
   MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
//   request.setMetaData(metadata);

   // request.setServerName(SERVER_NAME);
  // request.setAuthority(SERVER_NAME,9999);
  //// request.setPathInfo(path);
  //// request.setURIPathQuery(path);
   request.setDispatcherType(DispatcherType.REQUEST);
   doReturn(response).when(request).getResponse();

   ByteArrayOutputStream output = new ByteArrayOutputStream();
   try (PrintWriter writer = new PrintWriter(output)) {
     when(response.getWriter()).thenReturn(writer);
     securityHandler.handle(path, request, request, response);
   }
   return new String(output.toByteArray());
 }
 
Example #3
Source File: RegistrationMonitorWorkerIntegrationTest.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    HttpClient httpClient = mock(HttpClient.class);
    response = mock(ContentResponse.class);
    when(response.getStatus()).thenReturn(200);
    when(response.getContentAsString()).thenReturn(healthInfo);
    HttpFields headers = new HttpFields();
    headers.add(CONSUL_INDEX, "42");
    when(response.getHeaders()).thenReturn(headers);
    Request request = mock(Request.class);
    when(httpClient.newRequest(anyString())).thenReturn(request);
    when(request.send()).thenReturn(response);
    props = new ServiceProperties();
    props.addProperty(ServiceProperties.REGISTRY_SERVER_KEY, "localhost:1234");
    worker = new RegistrationMonitorWorker(httpClient, props, mock(ServiceDependencyHealthCheck.class));
    worker.setServiceName("foobar");
}
 
Example #4
Source File: RpcClientIntegrationTest.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
private void initialize() {
    httpResponse = mock(ContentResponse.class);
    when(httpResponse.getHeaders()).thenReturn(new HttpFields());
    when(httpResponse.getStatus()).thenReturn(200);
    try {
        RpcEnvelope.Response.Builder responseBuilder = RpcEnvelope.Response.newBuilder();
        responseBuilder.setServiceMethod("Test.test");
        if (requestsFail) {
            RpcCallException callException = new RpcCallException(
                    RpcCallException.Category.InternalServerError, "requests fail!");
            responseBuilder.setError(callException.toJson().toString());
        }
        RpcEnvelope.Response rpcResponse = responseBuilder.build();
        byte[] responseHeader = rpcResponse.toByteArray();
        byte[] payload = FrameworkTest.Foobar.newBuilder().build().toByteArray();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(Ints.toByteArray(responseHeader.length));
        out.write(responseHeader);
        out.write(Ints.toByteArray(payload.length));
        out.write(payload);
        out.flush();
        when(httpResponse.getContent()).thenReturn(out.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #5
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testUserRequired_NoUser() throws Exception {
  String path = "/user/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
 // request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #6
Source File: OcJettyHttpClientExtractorTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtraction() {
  HttpFields fields = new HttpFields();
  fields.add(new HttpField("User-Agent", "Test 1.0"));

  Request request = mock(Request.class);
  Response response = mock(Response.class);
  OcJettyHttpClientExtractor extractor = new OcJettyHttpClientExtractor();
  when(request.getHost()).thenReturn("localhost");
  when(request.getMethod()).thenReturn("GET");
  when(request.getHeaders()).thenReturn(fields);
  when(request.getPath()).thenReturn("/test");
  when(request.getURI()).thenReturn(uri);
  when(response.getStatus()).thenReturn(0);

  assertThat(extractor.getHost(request)).contains("localhost");
  assertThat(extractor.getMethod(request)).contains("GET");
  assertThat(extractor.getPath(request)).contains("/test");
  assertThat(extractor.getUrl(request)).contains(URI_STR);
  assertThat(extractor.getRoute(request)).contains("");
  assertThat(extractor.getUserAgent(request)).contains("Test 1.0");
  assertThat(extractor.getStatusCode(response)).isEqualTo(0);
}
 
Example #7
Source File: SystemInfoServiceClient.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public SystemInfo getSystemInfo() {
    try {
        Session session = createSession();
        HttpFields requestFields = new HttpFields();
        requestFields.put(USER_AGENT, USER_AGENT_VERSION);
        MetaData.Request request = new MetaData.Request("GET", getSystemInfoURI, HttpVersion.HTTP_2, requestFields);
        HeadersFrame headersFrame = new HeadersFrame(request, null, true);
        GetListener getListener = new GetListener();
        session.newStream(headersFrame, new FuturePromise<>(), getListener);
        SystemInfo response = getListener.get(SystemInfo.class);
        session.close(0, null, new Callback() {});
        return response;
    } catch (Exception e) {
        throw new HttpAccessException(e);
    }
}
 
Example #8
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testUserRequired_PreserveQueryParams() throws Exception {
  String path = "/user/blah";
  
  Request request = new Request(null, null);
  // request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path,"foo=baqr","foo=bar","foo=barff");
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
  MultiMap<String> queryParameters = new MultiMap<> ();
  queryParameters.add("ffo", "bar");
  request.setQueryParameters(queryParameters);
      request = spy(request);

 /// request.setAuthority(SERVER_NAME,9999);
  request.setQueryString("foo=bar");
  Response response = mock(Response.class);
  String output = runRequest2(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s?foo=bar", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #9
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAdminRequired_NoUser() throws Exception {
  String path = "/admin/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
//  request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #10
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Fire one request at the security handler (and by extension to the AuthServlet behind it).
 *
 * @param path The path to hit.
 * @param request The request object to use.
 * @param response The response object to use. Must be created by Mockito.mock()
 * @return Any data written to response.getWriter()
 * @throws IOException
 * @throws ServletException
 */
private String runRequest(String path, Request request, Response response)
    throws IOException, ServletException {
  //request.setMethod(/*HttpMethod.GET,*/ "GET");
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);

  // request.setServerName(SERVER_NAME);
 // request.setAuthority(SERVER_NAME,9999);
 //// request.setPathInfo(path);
 //// request.setURIPathQuery(path);
  request.setDispatcherType(DispatcherType.REQUEST);
  doReturn(response).when(request).getResponse();

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (PrintWriter writer = new PrintWriter(output)) {
    when(response.getWriter()).thenReturn(writer);
    securityHandler.handle(path, request, request, response);
  }
  return new String(output.toByteArray());
}
 
Example #11
Source File: GoServerLoadingIndicationHandlerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
private MockResponse request(String target, String acceptHeaderValue) throws Exception {
    Request baseRequest = mock(Request.class);
    HttpFields httpFields = new HttpFields();
    if (acceptHeaderValue != null) {
        httpFields.add("Accept", acceptHeaderValue);
    }
    when(baseRequest.getHttpFields()).thenReturn(httpFields);

    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    PrintWriter printWriter = mock(PrintWriter.class);
    when(servletResponse.getWriter()).thenReturn(printWriter);

    handler.getHandler().handle(target, baseRequest, servletRequest, servletResponse);

    return new MockResponse(servletResponse, printWriter);
}
 
Example #12
Source File: Jetty9ServerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddDefaultHeadersForRootContext() throws Exception {
    jetty9Server.configure();
    jetty9Server.startHandlers();

    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(mock(PrintWriter.class));

    HttpServletRequest request = mock(HttpServletRequest.class);

    Request baseRequest = mock(Request.class);
    when(baseRequest.getDispatcherType()).thenReturn(DispatcherType.REQUEST);
    when(baseRequest.getHttpFields()).thenReturn(mock(HttpFields.class));

    ContextHandler rootPathHandler = getLoadedHandlers().get(GoServerLoadingIndicationHandler.class);
    rootPathHandler.setServer(server);
    rootPathHandler.start();
    rootPathHandler.handle("/something", baseRequest, request, response);

    verify(response).setHeader("X-XSS-Protection", "1; mode=block");
    verify(response).setHeader("X-Content-Type-Options", "nosniff");
    verify(response).setHeader("X-Frame-Options", "SAMEORIGIN");
    verify(response).setHeader("X-UA-Compatible", "chrome=1");
}
 
Example #13
Source File: SyncHttpRequestSendInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    HttpRequest request = (HttpRequest) objInst;
    ContextCarrier contextCarrier = new ContextCarrier();
    AbstractSpan span = ContextManager.createExitSpan(request.getURI()
                                                             .getPath(), contextCarrier, request.getHost() + ":" + request
        .getPort());
    span.setComponent(ComponentsDefine.JETTY_CLIENT);

    Tags.HTTP.METHOD.set(span, getHttpMethod(request));
    Tags.URL.set(span, request.getURI().toString());
    SpanLayer.asHttp(span);

    CarrierItem next = contextCarrier.items();
    HttpFields field = request.getHeaders();
    while (next.hasNext()) {
        next = next.next();
        field.add(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example #14
Source File: SyncHttpRequestSendInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    HttpRequest request = (HttpRequest) objInst;
    ContextCarrier contextCarrier = new ContextCarrier();
    AbstractSpan span = ContextManager.createExitSpan(request.getURI()
                                                             .getPath(), contextCarrier, request.getHost() + ":" + request
        .getPort());
    span.setComponent(ComponentsDefine.JETTY_CLIENT);

    Tags.HTTP.METHOD.set(span, getHttpMethod(request));
    Tags.URL.set(span, request.getURI().toString());
    SpanLayer.asHttp(span);

    CarrierItem next = contextCarrier.items();
    HttpFields field = request.getHeaders();
    while (next.hasNext()) {
        next = next.next();
        field.add(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example #15
Source File: AsyncHttpExecutableTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
private void fireResponse(CapturingRequest request, int errorCode, String responseText, int resultSize, ObservableObserver observer, boolean successfulResponse) throws InterruptedException {
    Response.CompleteListener listener = request.awaitSend(1000, TimeUnit.MILLISECONDS);
    assertNotNull(listener);
    InputStreamResponseListener responseListener = (InputStreamResponseListener) listener;

    Result result = mock(Result.class);
    Response response = mock(Response.class);
    when(result.getResponse()).thenReturn(response);
    when(result.isSucceeded()).thenReturn(successfulResponse);
    when(result.isFailed()).thenReturn(!successfulResponse);
    HttpFields headers = mock(HttpFields.class);
    when(response.getHeaders()).thenReturn(headers);
    when(headers.get(HttpHeader.CONTENT_LENGTH)).thenReturn(String.valueOf(resultSize));
    when(response.getStatus()).thenReturn(errorCode);
    when(response.getVersion()).thenReturn(HttpVersion.HTTP_1_1);

    // fire that event
    responseListener.onHeaders(response);
    responseListener.onContent(response, ByteBuffer.allocate(0));
    responseListener.onComplete(result);

    assertTrue(observer.getLatch().await(1000, TimeUnit.MILLISECONDS));
}
 
Example #16
Source File: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static MetaData.Request toRequestMetadata(ServiceRequestContext ctx, AggregatedHttpRequest aReq) {
    // Construct the HttpURI
    final StringBuilder uriBuf = new StringBuilder();
    final RequestHeaders aHeaders = aReq.headers();

    uriBuf.append(ctx.sessionProtocol().isTls() ? "https" : "http");
    uriBuf.append("://");
    uriBuf.append(aHeaders.authority());
    uriBuf.append(aHeaders.path());

    final HttpURI uri = new HttpURI(uriBuf.toString());
    uri.setPath(ctx.mappedPath());

    // Convert HttpHeaders to HttpFields
    final HttpFields jHeaders = new HttpFields(aHeaders.size());
    aHeaders.forEach(e -> {
        final AsciiString key = e.getKey();
        if (!key.isEmpty() && key.byteAt(0) != ':') {
            jHeaders.add(key.toString(), e.getValue());
        }
    });

    return new MetaData.Request(aHeaders.get(HttpHeaderNames.METHOD), uri,
                                HttpVersion.HTTP_1_1, jHeaders, aReq.content().length());
}
 
Example #17
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Request testRequest(String scheme, int responseCode, String httpMethod, String path) throws Exception {
    HttpChannel channel = new HttpChannel(connector, new HttpConfiguration(), null, new DummyTransport());
    MetaData.Request metaData = new MetaData.Request(httpMethod, new HttpURI(scheme + "://" + path), HttpVersion.HTTP_1_1, new HttpFields());
    Request req = channel.getRequest();
    req.setMetaData(metaData);

    this.httpResponseCode = responseCode;
    channel.handle();
    return req;
}
 
Example #18
Source File: RequestLogEnhancer.java    From tutorials with MIT License 5 votes vote down vote up
private static Charset getCharset(HttpFields headers) {
    String contentType = headers.get(HttpHeader.CONTENT_TYPE);
    if (contentType != null) {
        String[] tokens = contentType
          .toLowerCase(Locale.US)
          .split("charset=");
        if (tokens.length == 2) {
            String encoding = tokens[1].replaceAll("[;\"]", "");
            return Charset.forName(encoding);
        }
    }
    return StandardCharsets.UTF_8;
}
 
Example #19
Source File: HttpClientWrapper.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> convertHeaderToMap(HttpFields headers) {
    Map<String, String> httpHeader = new HashMap<>();
    for (HttpField header : headers) {
        httpHeader.put(header.getName(), header.getValue());
    }
    return httpHeader;
}
 
Example #20
Source File: ProxyServiceImpl.java    From moon-api-gateway with MIT License 5 votes vote down vote up
private boolean checkContentType(HttpFields responseHeaders) {
    if (responseHeaders.contains(HttpHeader.CONTENT_TYPE)) {
        String contentTypeValue = responseHeaders.get(HttpHeader.CONTENT_TYPE);
        return contentTypeValue.split(Constant.CONTENT_TYPE_EXTRACT_DELIMITER)[0]
                .equals(responseInfo.getRequestAccept().split(Constant.CONTENT_TYPE_EXTRACT_DELIMITER)[0]);
    }

    return false;
}
 
Example #21
Source File: JettyXhrTransport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static HttpHeaders toHttpHeaders(HttpFields httpFields) {
	HttpHeaders responseHeaders = new HttpHeaders();
	Enumeration<String> names = httpFields.getFieldNames();
	while (names.hasMoreElements()) {
		String name = names.nextElement();
		Enumeration<String> values = httpFields.getValues(name);
		while (values.hasMoreElements()) {
			String value = values.nextElement();
			responseHeaders.add(name, value);
		}
	}
	return responseHeaders;
}
 
Example #22
Source File: SystemTest.java    From app-runner with MIT License 5 votes vote down vote up
@Test
public void theReverseProxyBehavesItself() throws Exception {
    ContentResponse resp = restClient.homepage(mavenApp.name);
    assertThat(resp, is(equalTo(200, containsString("My Maven App"))));
    HttpFields headers = resp.getHeaders();
    assertThat(headers.getValuesList("Date"), hasSize(1));
    assertThat(headers.getValuesList("Via"), Matchers.equalTo(singletonList("HTTP/1.1 apprunner")));
    assertThat(restClient.deleteApp(mavenApp.name), equalTo(200, containsString("{")));
}
 
Example #23
Source File: JettyResponseListener.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the value of the <code>Content-Type</code> header.
 * @return
 * @throws IOException
 */
public String getContentType() throws IOException {
	ensureResponse();
	
	final HttpFields headers = m_response.getHeaders();
	
	return headers.get(HttpHeader.CONTENT_TYPE);
}
 
Example #24
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static HttpHeaders toHttpHeaders(HttpFields httpFields) {
	HttpHeaders responseHeaders = new HttpHeaders();
	Enumeration<String> names = httpFields.getFieldNames();
	while (names.hasMoreElements()) {
		String name = names.nextElement();
		Enumeration<String> values = httpFields.getValues(name);
		while (values.hasMoreElements()) {
			String value = values.nextElement();
			responseHeaders.add(name, value);
		}
	}
	return responseHeaders;
}
 
Example #25
Source File: FileHandler.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void setCaching(final HttpServletResponse response, final int expiresSeconds) {
    if (response instanceof org.eclipse.jetty.server.Response) {
        org.eclipse.jetty.server.Response r = (org.eclipse.jetty.server.Response) response;
        HttpFields fields = r.getHttpFields();
        
        // remove the last-modified field since caching otherwise does not work
        /*
           https://www.ietf.org/rfc/rfc2616.txt
           "if the response does have a Last-Modified time, the heuristic
           expiration value SHOULD be no more than some fraction of the interval
           since that time. A typical setting of this fraction might be 10%."
        */
        fields.remove(HttpHeader.LAST_MODIFIED); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work

        // cache-control: allow shared caching (i.e. proxies) and set expires age for cache
        if(expiresSeconds == 0){
            fields.put(HttpHeader.CACHE_CONTROL, "public, no-store, max-age=" + Integer.toString(expiresSeconds)); // seconds
        }
        else {
            fields.put(HttpHeader.CACHE_CONTROL, "public, max-age=" + Integer.toString(expiresSeconds)); // seconds
        }
    } else {
        response.setHeader(HttpHeader.LAST_MODIFIED.asString(), ""); // not really the best wqy to remove this header but there is no other option
        if(expiresSeconds == 0){
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, no-store, max-age=" + Integer.toString(expiresSeconds));
        }
        else{
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, max-age=" + Integer.toString(expiresSeconds));
        }

    }

    // expires: define how long the file shall stay in a cache if cache-control is not used for this information
    response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + expiresSeconds * 1000);
}
 
Example #26
Source File: RestClient20.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public Stream createStream(Session session, HttpURI uri, Stream.Listener listener) throws Exception {
    HttpFields requestFields = new HttpFields();
    requestFields.put(USER_AGENT, USER_AGENT_VERSION);
    MetaData.Request request = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, requestFields);
    HeadersFrame headersFrame = new HeadersFrame(request, null, false);
    FuturePromise<Stream> streamPromise = new FuturePromise<>();
    session.newStream(headersFrame, streamPromise, listener);
    return streamPromise.get();
}
 
Example #27
Source File: AssetServlet.java    From onedev with MIT License 5 votes vote down vote up
public AssetServlet() {
	super(new ResourceService() {
		
		@Override
		protected void putHeaders(HttpServletResponse response, HttpContent content, long contentLength) {
			super.putHeaders(response, content, contentLength);
			
			HttpFields fields;
			if (response instanceof Response)
				fields = ((Response) response).getHttpFields();
			else
				fields = ((Response)((HttpServletResponseWrapper) response).getResponse()).getHttpFields();
			
			if (requestHolder.get().getDispatcherType() == DispatcherType.ERROR) {
				/*
				 * Do not cache error page and also makes sure that error page is not eligible for 
				 * modification check. That is, error page will be always retrieved.
				 */
	            fields.put(HttpHeader.CACHE_CONTROL, "must-revalidate,no-cache,no-store");
			} else if (requestHolder.get().getRequestURI().equals("/favicon.ico")) {
				/*
				 * Make sure favicon request is cached. Otherwise, it will be requested for every 
				 * page request.
				 */
				fields.put(HttpHeader.CACHE_CONTROL, "max-age=86400,public");
			}
		}
		
	});
}
 
Example #28
Source File: HttpRequestParamsReader.java    From tika-server with Apache License 2.0 5 votes vote down vote up
public void initialize(InputStream stream) {
    if (initialized)
        return;
    initialized = true;
    MetaData metaDict = getMetaDataField(stream);
    if (metaDict == null)
        return;

    HttpFields fields = metaDict.getFields();
    for (HttpField field : fields)
        rawParams.put(field.getName(), field.getValue());
    GetCommonFlags();
}
 
Example #29
Source File: HeadersAdaptersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Parameterized.Parameters(name = "headers [{0}]")
public static Object[][] arguments() {
	return new Object[][] {
			{CollectionUtils.toMultiValueMap(
					new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH))},
			{new NettyHeadersAdapter(new DefaultHttpHeaders())},
			{new TomcatHeadersAdapter(new MimeHeaders())},
			{new UndertowHeadersAdapter(new HeaderMap())},
			{new JettyHeadersAdapter(new HttpFields())}
	};
}
 
Example #30
Source File: JettyXhrTransport.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static HttpHeaders toHttpHeaders(HttpFields httpFields) {
	HttpHeaders responseHeaders = new HttpHeaders();
	Enumeration<String> names = httpFields.getFieldNames();
	while (names.hasMoreElements()) {
		String name = names.nextElement();
		Enumeration<String> values = httpFields.getValues(name);
		while (values.hasMoreElements()) {
			String value = values.nextElement();
			responseHeaders.add(name, value);
		}
	}
	return responseHeaders;
}