com.google.common.net.HttpHeaders Java Examples

The following examples show how to use com.google.common.net.HttpHeaders. 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: FileDownloadServletTest.java    From selenium-grid-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void getShouldReturnFileContentsWithNameInHeader() throws IOException {
    File fileToGet = File.createTempFile("test filename with spaces", ".txt");
    FileUtils.write(fileToGet, "expected_content", StandardCharsets.UTF_8);

    CloseableHttpClient httpClient = HttpClients.createDefault();

    String encode = Base64.getUrlEncoder().encodeToString(fileToGet.getAbsolutePath().getBytes(StandardCharsets.UTF_8));
    HttpGet httpGet = new HttpGet("/FileDownloadServlet/" + encode);

    CloseableHttpResponse execute = httpClient.execute(serverHost, httpGet);

    //check contents are properly sent
    try (
            InputStream content = execute.getEntity().getContent()) {
        String s = IOUtils.toString(content, StandardCharsets.UTF_8);
        assertThat(s, is("expected_content"));
    }

    //check file name is available from header
    Header contentDispositionHeader = execute.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION);
    assertThat(contentDispositionHeader.getValue(), containsString("filename=" + fileToGet.getName()));
    //check file is not locked by anything
    assertTrue(fileToGet.delete());
}
 
Example #2
Source File: AccessFilter.java    From seppb with MIT License 6 votes vote down vote up
private boolean loginValid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
	HttpSession session = httpServletRequest.getSession();
	String uid = httpServletRequest.getParameter(CommonParameter.USER_ID);
	String token = (String) session.getAttribute(uid);
	String url=httpServletRequest.getRequestURI();
	HashSet<String> canAccessUrls = Sets.newHashSet("/sepp/user/list_domain", "/", "/sepp/", "/sepp/user/list_domain",
			"/sepp/user/ldap_auth","/sepp/myHandler");
	if (canAccessUrls.contains(url) || url.contains("/user")) {
		return true;
	}
	if(StringUtils.isBlank(token))
	{
		httpServletResponse.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
		String errorMessage = LOGIN_VALID_ERROR_MESSAGE;
		httpServletResponse.getWriter().write(errorMessage);
		return false;
	}
	return true;
}
 
Example #3
Source File: ProxyFilterTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testProxyOnPerdu() throws Exception {
    ProxyFilter filter = new ProxyFilter() {

        @Override
        protected String getProxyTo() {
            return "http://perdu.com";
        }
    };

    Route route = mock(Route.class);
    RequestContext rc = mock(RequestContext.class);
    FakeContext context = new FakeContext();
    context.setPath("/").setHeader(HttpHeaders.CONNECTION, "keep-alive");

    FakeRequest request = new FakeRequest(context).method(HttpMethod.GET).uri("/");

    when(rc.context()).thenReturn(context);
    when(rc.request()).thenReturn(request);
    Result result = ((AsyncResult) filter.call(route, rc)).callable().call();
    assertThat(result).isNotNull();
    assertThat(result.getStatusCode()).isEqualTo(Status.OK);
    assertThat(streamToString(result)).contains("Pas de panique");
    assertThat(result.getHeaders().get(HeaderNames.CONTENT_TYPE)).isEqualTo(MimeTypes.HTML);
}
 
Example #4
Source File: RecordedHttpMessageBuilder.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Get content type from headers
 *
 * */
protected String getContentType() {
  // Content_Type cannot have multiple, commas-separated values, so this is safe.
  Iterator<String> header = _headers.get(HttpHeaders.CONTENT_TYPE).iterator();
  if (!header.hasNext()) {
    return DEFAULT_CONTENT_TYPE;
  } else {
    return MediaType.parse(header.next()).withoutParameters().toString();
  }
}
 
Example #5
Source File: RedirectFilterTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfiguration() throws Exception {
    Configuration configuration = mock(Configuration.class);
    when(configuration.get("prefix")).thenReturn("/redirected");
    when(configuration.get("redirectTo")).thenReturn("http://perdu.com");

    RedirectFilter filter = new RedirectFilter(configuration);

    Route route = mock(Route.class);
    RequestContext rc = mock(RequestContext.class);
    FakeContext context = new FakeContext();
    context.setPath("/redirected").setHeader(HttpHeaders.CONNECTION, "keep-alive");

    FakeRequest request = new FakeRequest(context).method(HttpMethod.GET).uri("/redirected");

    when(rc.context()).thenReturn(context);
    when(rc.request()).thenReturn(request);
    Result result = filter.call(route, rc);
    assertThat(result).isNotNull();
    assertThat(result.getStatusCode()).isEqualTo(Status.SEE_OTHER);
    assertThat(result.getHeaders().get(HeaderNames.LOCATION)).isEqualTo("http://perdu.com");
}
 
Example #6
Source File: BasicAuthFilter.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(HttpHeaders.AUTHORIZATION);

    if (header != null && header.startsWith("Basic ")) {
        String decoded = new String(BaseEncoding.base64().decode(header.substring(header.indexOf(" ") + 1)));

        if (decoded.contains(":")) {
            String username = decoded.substring(0, decoded.indexOf(":"));
            String password = decoded.substring(decoded.indexOf(":") + 1, decoded.length());

            if (username.equals(this.username) && password.equals(this.password)) {
                chain.doFilter(request, response);
                return;
            } else {
                log.info("Incorrect admin login with username '{}'.", username);
            }
        }
    }

    response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Administration\"");
    response.sendError(Response.SC_UNAUTHORIZED);
}
 
Example #7
Source File: FooControllerCustomEtagIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtagUsingCustomEtagEndpoint_thenResourceIsReturned() throws Exception {
 // Given
    String createdResourceUri = this.mvc.perform(post(FOOS_ENDPOINT).contentType(MediaType.APPLICATION_JSON)
        .content(createFooJson()))
        .andExpect(status().isCreated())
        .andReturn()
        .getResponse()
        .getHeader(HttpHeaders.LOCATION);
    ResultActions findOneResponse = this.mvc
        .perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON));
    String etag = findOneResponse.andReturn().getResponse().getHeader(HttpHeaders.ETAG);
    Foo createdFoo = deserializeFoo(findOneResponse.andReturn().getResponse().getContentAsString());
    createdFoo.setName("updated name");
    this.mvc
    .perform(put(createdResourceUri).contentType(MediaType.APPLICATION_JSON).content(serializeFoo(createdFoo)));

    // When
    ResultActions result = this.mvc
        .perform(get(createdResourceUri + CUSTOM_ETAG_ENDPOINT_SUFFIX).contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.IF_NONE_MATCH, etag));

    // Then
    result.andExpect(status().isOk())
    .andExpect(header().string(HttpHeaders.ETAG, "\"1\""));
}
 
Example #8
Source File: SecurityHeadersFilter.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Override public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
  if (response instanceof HttpServletResponse) {
    HttpServletResponse r = (HttpServletResponse) response;

    // Defense against XSS. We don't care about IE's Content-Security-Policy because it's useless
    r.addHeader("X-Content-Security-Policy", "default-src 'self'");
    r.addHeader(HttpHeaders.X_XSS_PROTECTION, "0"); // With CSP, we don't need crazy magic

    // Tell IE not to do silly things
    r.addHeader(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");

    // Protection against click jacking
    r.addHeader("Frame-Options", "DENY"); // Who uses this?
    r.addHeader(HttpHeaders.X_FRAME_OPTIONS, "DENY");

    // https-all-the-time
    r.addHeader(HttpHeaders.STRICT_TRANSPORT_SECURITY,
        format("max-age=%d; includeSubDomains", YEAR_OF_SECONDS));
  }
  chain.doFilter(request, response);
}
 
Example #9
Source File: UniversalReverseClickjackingJsonpEndpointTest.java    From firing-range with Apache License 2.0 6 votes vote down vote up
@Test
public void checksCallbackLength() throws IOException {
  String callback =
      Strings.repeat("a", UniversalReverseClickjackingJsonpEndpoint.MAX_CALLBACK_LENGTH);

  when(request.getParameter(UniversalReverseClickjackingJsonpEndpoint.ECHOED_PARAM))
      .thenReturn(callback);
  new UniversalReverseClickjackingJsonpEndpoint().doGet(request, response);
  verify(response).setStatus(200);
  verify(response).setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
  verify(writer).write("/**/" + callback + "({'foobar':'foo'});");

  when(request.getParameter(UniversalReverseClickjackingJsonpEndpoint.ECHOED_PARAM))
      .thenReturn(callback + "a");
  new UniversalReverseClickjackingJsonpEndpoint().doGet(request, response);
  verify(response).setStatus(400);
  // Verify that we also don't write overlong callbacks
  verify(writer, never()).write(contains("/**/" + callback + "a("));
}
 
Example #10
Source File: Servlets.java    From easyweb with Apache License 2.0 6 votes vote down vote up
/**
 * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
 * 
 * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
 * 
 * @param etag 内容的ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
	String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
	if (headerValue != null) {
		boolean conditionSatisfied = false;
		if (!"*".equals(headerValue)) {
			StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

			while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
				String currentToken = commaTokenizer.nextToken();
				if (currentToken.trim().equals(etag)) {
					conditionSatisfied = true;
				}
			}
		} else {
			conditionSatisfied = true;
		}

		if (conditionSatisfied) {
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			response.setHeader(HttpHeaders.ETAG, etag);
			return false;
		}
	}
	return true;
}
 
Example #11
Source File: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_EJBException() {
    Exception e = new EJBException(new WebApplicationException());
    StackTraceElement[] traceArr = new StackTraceElement[1];
    traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
    
    e.setStackTrace(traceArr);
    
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(500, response.getStatus());
    Assert.assertEquals(5, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example #12
Source File: HttpCommandEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testPayloadWithContentTypeHeaderYaml() throws InterruptedException {
   server.enqueue((jsonResponse("map-response.json")));

   httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
           .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
           .configure(HttpCommandEffector.EFFECTOR_URI, url("/post"))
           .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "POST")
           .configure(HttpCommandEffector.EFFECTOR_HTTP_PAYLOAD, "my yaml")
           .configure(HttpCommandEffector.EFFECTOR_HTTP_HEADERS, ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "application/yaml"))
           .configure(HttpCommandEffector.JSON_PATH, "$.data")
   );
   assertNotNull(httpCommandEffector);
   TestEntity testEntity = app.createAndManageChild(buildEntitySpec(httpCommandEffector));
   testEntity.invoke(EFFECTOR_HTTP_COMMAND, ImmutableMap.<String, Object>of()).getUnchecked(Duration.minutes(1));

   assertEquals(server.getRequestCount(), 1);
   assertEquals(new String(server.takeRequest().getBody()), "my yaml");
}
 
Example #13
Source File: RESTExceptionMapperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testToResponse_EJBException2() {
    Exception e = new EJBException(new QueryException());
    StackTraceElement[] traceArr = new StackTraceElement[1];
    traceArr[0] = new StackTraceElement("dummyClass", "dummyMethod", null, 0);
    
    e.setStackTrace(traceArr);
    
    Response response = rem.toResponse(e);
    MultivaluedMap<String,Object> responseMap = response.getHeaders();
    
    Assert.assertEquals(500, response.getStatus());
    Assert.assertEquals(6, responseMap.size());
    Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
    Assert.assertEquals(Lists.newArrayList("500-1"), responseMap.get(Constants.ERROR_CODE));
    Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
    Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
                    responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
 
Example #14
Source File: AbstractBasicLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() {
    // Given
    final String uriOfResource = createAsUri();
    final Response firstFindOneResponse = RestAssured.given()
        .header("Accept", "application/json")
        .get(uriOfResource);
    final String etagValue = firstFindOneResponse.getHeader(HttpHeaders.ETAG);
    final long createdId = firstFindOneResponse.jsonPath().getLong("id");

    Foo updatedFoo = new Foo("updated value");
    updatedFoo.setId(createdId);
    Response updatedResponse = RestAssured.given().contentType(ContentType.JSON).body(updatedFoo)
        .put(uriOfResource);
    assertThat(updatedResponse.getStatusCode() == 200);

    // When
    final Response secondFindOneResponse = RestAssured.given()
        .header("Accept", "application/json")
        .headers("If-None-Match", etagValue)
        .get(uriOfResource);

    // Then
    assertTrue(secondFindOneResponse.getStatusCode() == 200);
}
 
Example #15
Source File: HttpCommandEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testPayloadWithContentTypeHeaderXml() throws InterruptedException {
   server.enqueue(jsonResponse("int-response.json"));

   httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
           .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
           .configure(HttpCommandEffector.EFFECTOR_URI, url("/post"))
           .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "POST")
           .configure(HttpCommandEffector.EFFECTOR_HTTP_PAYLOAD, 1)
           .configure(HttpCommandEffector.EFFECTOR_HTTP_HEADERS, ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "application/xml"))
           .configure(HttpCommandEffector.JSON_PATH, "$.data")
   );
   assertNotNull(httpCommandEffector);
   TestEntity testEntity = app.createAndManageChild(buildEntitySpec(httpCommandEffector));
   Object output = testEntity.invoke(EFFECTOR_HTTP_COMMAND, ImmutableMap.<String, Object>of()).getUnchecked(Duration.seconds(1));
   assertEquals(output, "1");

   assertEquals(server.getRequestCount(), 1);
   assertSent(server, "POST", "/post");
}
 
Example #16
Source File: WebUtil.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
/**
 * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
 * <p>
 * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
 *
 * @param etag 内容的ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
    String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader(HttpHeaders.ETAG, etag);
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: RequestAuthenticatorTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationFailure() {
  when(authenticator.authenticate(any())).thenReturn(null);

  final Request request = Request.forUri("/", "PUT")
      .withHeader(HttpHeaders.AUTHORIZATION, "Bearer token")
      .withPayload(ByteString.encodeUtf8("hello"));

  try {
    sut.authenticate(request);
    fail();
  } catch (ResponseException e) {
    assertThat(e.getResponse().status(), is(
        Status.UNAUTHORIZED
            .withReasonPhrase("Authorization token is invalid")));
  }
}
 
Example #18
Source File: WebUtil.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
/**
 * 从request中获得参数,并返回可读的Map
 * application/x-www-form-urlencode
 * application/json
 * application/json;charset=UTF-8
 * multipart/form-data
 *
 * @param request
 * @return
 */
public static Map<String, String> getParameterMap(HttpServletRequest request) {
    String contentType = request.getHeader(org.springframework.http.HttpHeaders.CONTENT_TYPE);
    Map<String, String> returnMap = new HashMap();
    if (contentType != null && contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)) {
        // form-data表单
        MultipartResolver multipartResolver = SpringUtil.getBean(MultipartResolver.class);
        MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(request);
        returnMap = conventMap(multiReq.getParameterMap());
    } else if (MediaType.APPLICATION_JSON_VALUE.equals(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType)) {
        // json表单
        String body = getBodyString(request);
        if (StringUtils.isNoneBlank(body)) {
            try {
                returnMap = JSONObject.parseObject(body, Map.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        // 普通表单
        returnMap = conventMap(request.getParameterMap());
    }
    // 参数Map
    return returnMap;
}
 
Example #19
Source File: IlpOverHttpLink.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * Construct headers for an ILP-over-HTTP request.
 *
 * @return A newly constructed instance of {@link Headers}.
 */
private Headers constructHttpRequestHeaders() {
  final Headers.Builder headers = new Headers.Builder()
      // Defaults to ILP_OCTET_STREAM, but is replaced by whatever testConnection returns if it's a valid media-type.
      .add(HttpHeaders.ACCEPT, OCTET_STREAM.toString())
      .add(CONTENT_TYPE, OCTET_STREAM.toString())
      // Disable HTTP Caching of packets...
      .add(CACHE_CONTROL, "private, max-age=0, no-cache")
      .add(PRAGMA, "no-cache");

  // Set the Operator Address header, if present.
  headers.set(ILP_OPERATOR_ADDRESS_VALUE, getOperatorAddressSupplier().get().getValue());

  headers.add(HttpHeaders.AUTHORIZATION, BEARER_WITH_SPACE + this.authTokenSupplier.get());

  return headers.build();
}
 
Example #20
Source File: LeakedHttpOnlyCookieTest.java    From firing-range with Apache License 2.0 5 votes vote down vote up
@Test
public void doGet_leakedCookiePage_setsCookieAndReturnsItInResponse() throws Exception {
  ArgumentCaptor<String> setCookieHeader = ArgumentCaptor.forClass(String.class);
  doNothing()
      .when(response)
      .setHeader(Matchers.eq(HttpHeaders.SET_COOKIE), setCookieHeader.capture());
  when(request.getPathInfo()).thenReturn("/leakedcookie");

  new LeakedHttpOnlyCookie().doGet(request, response);

  String cookieValue = extractCookieValue(setCookieHeader.getValue());
  verify(response).setHeader(Matchers.eq(HttpHeaders.SET_COOKIE), contains("HttpOnly"));
  verify(writer).write(contains(cookieValue));
}
 
Example #21
Source File: WebUtil.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
 * <p>
 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
 *
 * @param lastModified 内容的最后修改时间.
 */
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
                                           long lastModified) {
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }
    return true;
}
 
Example #22
Source File: BalancerFilterTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testReverseRoutingHeaderModification() {
    Configuration configuration = mock(Configuration.class);
    when(configuration.get("prefix")).thenReturn("/app");
    when(configuration.getOrDie("name")).thenReturn("balancer");
    when(configuration.getBooleanWithDefault("stickySession", false))
            .thenReturn(true);
    when(configuration.getBooleanWithDefault("proxyPassReverse", false))
            .thenReturn(true);
    BalancerFilter balancer = new BalancerFilter(configuration);

    BalancerMember member1 = new DefaultBalancerMember("member-1", "http://foo.com",
            "balancer");

    balancer.addMember(member1);

    RequestContext rc = mock(RequestContext.class);
    FakeContext context = new FakeContext();
    context.setPath("/").setHeader(HttpHeaders.CONNECTION, "keep-alive");

    FakeRequest request = new FakeRequest(context)
            .method(HttpMethod.GET)
            .uri("http://localhost:9000/app/");

    when(rc.context()).thenReturn(context);
    when(rc.request()).thenReturn(request);

    Multimap<String, String> headers = ArrayListMultimap.create();
    headers.put(HeaderNames.LOCATION, "http://foo.com/my/path?q=v#test");
    headers.put(HeaderNames.CONTENT_LOCATION, "http://foo.com/my/path");
    balancer.updateHeaders(rc, headers);

    assertThat(headers.entries()).hasSize(2);
    assertThat(headers.containsEntry(HeaderNames.LOCATION,
            "http://localhost:9000/my/path?q=v#test")).isTrue();
    assertThat(headers.containsEntry(HeaderNames.CONTENT_LOCATION,
            "http://localhost:9000/my/path")).isTrue();

}
 
Example #23
Source File: AbstractRootNodeMessageConverterTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void writeInternalWithAttachmentGzip() throws IOException
{
    Mockito.doAnswer( invocation -> {
        ((OutputStream) invocation.getArgument( 2 )).write( rootNode.getName().getBytes( StandardCharsets.UTF_8 ) );
        return null;
    } ).when( nodeService ).serialize( Mockito.same( rootNode ), Mockito.eq( "other/xzx" ), Mockito.any( OutputStream.class ) );
    httpOutputMessage.getHeaders().set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=metadata" );
    converterGzip.writeInternal( rootNode, httpOutputMessage );
    Assert.assertNotNull( httpOutputMessage.getHeaders().get( HttpHeaders.CONTENT_DISPOSITION ) );
    Assert.assertEquals( 1, httpOutputMessage.getHeaders().get( HttpHeaders.CONTENT_DISPOSITION ).size() );
    Assert.assertEquals( "attachment; filename=metadata.xzx.gz", httpOutputMessage.getHeaders().get( HttpHeaders.CONTENT_DISPOSITION ).get( 0 ) );
    Assert.assertEquals( rootNode.getName(),
        IOUtils.toString( new GZIPInputStream( new ByteArrayInputStream( httpOutputMessage.getBodyAsBytes() ) ), StandardCharsets.UTF_8 ) );
}
 
Example #24
Source File: RecordedHttpMessageBuilder.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Get content encoding from headers
 *
 * */
protected String getContentEncoding() {
  // Content_Encoding cannot have multiple, commas-separated values, so this is safe.
  Iterator<String> header = _headers.get(HttpHeaders.CONTENT_ENCODING).iterator();
  if (!header.hasNext()) {
    return DEFAULT_CONTENT_ENCODING;
  } else {
    return header.next();
  }
}
 
Example #25
Source File: ScriptToResponse.java    From purplejs with Apache License 2.0 5 votes vote down vote up
private void setRedirect( final ResponseBuilder builder, final ScriptValue value )
{
    final String redirect = ( value != null ) ? value.getValue( String.class ) : null;
    if ( redirect == null )
    {
        return;
    }

    builder.status( Status.SEE_OTHER );
    builder.header( HttpHeaders.LOCATION, redirect );
}
 
Example #26
Source File: SingleResourceRetrievedDiscoverabilityListener.java    From tutorials with MIT License 5 votes vote down vote up
void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) {
    final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString();
    final int positionOfLastSlash = requestURL.lastIndexOf("/");
    final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash);

    final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection");
    response.addHeader(HttpHeaders.LINK, linkHeaderValue);
}
 
Example #27
Source File: CacheMediatorTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Test case for isValidCacheEntry() with no-store header.
 *
 * @throws AxisFault when exception happens on message context creation.
 */
public void testIsNoStore() throws AxisFault {
    MessageContext synCtx = createMessageContext();
    org.apache.axis2.context.MessageContext msgCtx =  ((Axis2MessageContext) synCtx).getAxis2MessageContext();

    Map<String, String> headers = new HashMap<>();
    headers.put(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_HEADER);
    if (msgCtx != null) {
        msgCtx.setProperty("TRANSPORT_HEADERS", headers);
        ((Axis2MessageContext) synCtx).setAxis2MessageContext(msgCtx);
    }
    assertEquals("no-store cache-control does not exist.", HttpCachingFilter.isNoStore(msgCtx), true);
}
 
Example #28
Source File: TestHttpRequest.java    From quarantyne with Apache License 2.0 5 votes vote down vote up
private static CaseInsensitiveStringKV defaultHeaders() {
  Map<String, String> h = Maps.newHashMap();
  h.put(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  h.put(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
  h.put(HttpHeaders.CONNECTION, "Close");
  h.put(HttpHeaders.COOKIE, "theme=light; sessionToken=abc123");
  h.put(HttpHeaders.DNT, "1");
  h.put(HttpHeaders.HOST, "www.example.org");
  h.put(HttpHeaders.USER_AGENT, DEFAULT_USER_AGENT);
  return new CaseInsensitiveStringKV(h);
}
 
Example #29
Source File: ReplicationClientFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHealthy(ServiceEndPoint endPoint) {
    URI adminUrl = Payload.valueOf(endPoint.getPayload()).getAdminUrl();
    return _jerseyClient.resource(adminUrl).path("/healthcheck")
            .header(HttpHeaders.CONNECTION, "close")
            .head().getStatus() == 200;
}
 
Example #30
Source File: AttachmentController.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
    * 下载文件
    *
    * @param id id
    * @author tangyi
    * @date 2018/10/30 22:26
    */
   @GetMapping("download")
   @ApiOperation(value = "下载附件", notes = "根据ID下载附件")
   @ApiImplicitParam(name = "id", value = "附件ID", required = true, dataType = "Long")
   public void download(HttpServletRequest request, HttpServletResponse response, @NotBlank Long id) {
       try {
		Attachment attachment = new Attachment();
		attachment.setId(id);
		attachment = attachmentService.get(attachment);
		if (attachment == null)
			throw new CommonException("Attachment does not exist");
		InputStream inputStream = UploadInvoker.getInstance().download(attachment);
		if (inputStream == null) {
		    log.info("attachment is not exists");
		    return;
           }
           OutputStream outputStream = response.getOutputStream();
           response.setContentType("application/zip");
           response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=10");
           // IE之外的浏览器使用编码输出名称
           String contentDisposition = "";
           String httpUserAgent = request.getHeader("User-Agent");
           if (StringUtils.isNotEmpty(httpUserAgent)) {
               httpUserAgent = httpUserAgent.toLowerCase();
               String fileName = attachment.getAttachName();
               contentDisposition = httpUserAgent.contains("wps") ? "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") : Servlets.getDownName(request, fileName);
           }
           response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
           response.setContentLength(inputStream.available());
           FileCopyUtils.copy(inputStream, outputStream);
           log.info("download {} success", attachment.getAttachName());
	} catch (Exception e) {
       	log.error("Download attachment failed: {}", e.getMessage(), e);
	}
}