congrats Icon
New! Announcing our next generation AI code completions
Read here
Tabnine Logo
MockHttpServletRequestBuilder.headers
Code IndexAdd Tabnine to your IDE (free)

How to use
headers
method
in
org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder

Best Java code snippets using org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.headers (Showing top 15 results out of 315)

origin: spring-projects/spring-framework

@Test
public void headers() {
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  httpHeaders.put("foo", Arrays.asList("bar", "baz"));
  this.builder.headers(httpHeaders);
  MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
  List<String> headers = Collections.list(request.getHeaders("foo"));
  assertEquals(2, headers.size());
  assertEquals("bar", headers.get(0));
  assertEquals("baz", headers.get(1));
  assertEquals(MediaType.APPLICATION_JSON.toString(), request.getHeader("Content-Type"));
}
origin: spring-projects/spring-framework

private ClientHttpResponse getClientHttpResponse(
    HttpMethod httpMethod, URI uri, HttpHeaders requestHeaders, byte[] requestBody) {
  try {
    MockHttpServletResponse servletResponse = this.mockMvc
        .perform(request(httpMethod, uri).content(requestBody).headers(requestHeaders))
        .andReturn()
        .getResponse();
    HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
    byte[] body = servletResponse.getContentAsByteArray();
    MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
    clientResponse.getHeaders().putAll(getResponseHeaders(servletResponse));
    return clientResponse;
  }
  catch (Exception ex) {
    byte[] body = ex.toString().getBytes(StandardCharsets.UTF_8);
    return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
origin: cloudfoundry/uaa

/**
 * The endpoint is not white-listed to allow CORS requests with the "X-Requested-With" header so the
 * CorsFilter returns a 403.
 *
 * @throws Exception on test failure
 */
@Test
void testLogOutCorsPreflightWithUnallowedEndpoint(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(singletonList("^localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout\\.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "X-Requested-With");
  httpHeaders.add("Access-Control-Request-Method", "GET");
  httpHeaders.add("Origin", "localhost");
  mockMvc.perform(options("/logout.dont").headers(httpHeaders)).andExpect(status().isForbidden());
}
origin: cloudfoundry/uaa

/**
 * This should avoid the logic for X-Requested-With header entirely.
 *
 * @throws Exception on test failure
 */
@Test
void testLogOutCorsPreflightWithStandardHeader(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(singletonList("^localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout\\.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "Accept");
  httpHeaders.add("Access-Control-Request-Method", "GET");
  httpHeaders.add("Origin", "localhost");
  mockMvc.perform(options("/logout.do").headers(httpHeaders)).andExpect(status().isOk());
}
origin: cloudfoundry/uaa

/**
 * Positive test case that exercises the CORS logic for dealing with the "X-Requested-With" header.
 *
 * @throws Exception
 */
@Test
void testLogOutCorsPreflightForIdentityZone(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(asList("^localhost$", "^*\\.localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "X-Requested-With");
  httpHeaders.add("Access-Control-Request-Method", "GET");
  httpHeaders.add("Origin", "testzone1.localhost");
  mockMvc.perform(options("/logout.do").headers(httpHeaders)).andExpect(status().isOk());
}
origin: cloudfoundry/uaa

/**
 * Positive test case that exercises the CORS logic for dealing with the "X-Requested-With" header.
 *
 * @throws Exception
 */
@Test
void testLogOutCorsPreflight(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(asList("^localhost$", "^*\\.localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout\\.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "X-Requested-With");
  httpHeaders.add("Access-Control-Request-Method", "GET");
  httpHeaders.add("Origin", "localhost");
  mockMvc.perform(options("/logout.do").headers(httpHeaders)).andExpect(status().isOk());
}
origin: cloudfoundry/uaa

/**
 * The request origin is not white-listed to allow CORS requests with the "X-Requested-With" header so the
 * CorsFilter returns a 403.
 *
 * @throws Exception on test failure
 */
@Test
void testLogOutCorsPreflightWithUnallowedOrigin(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(singletonList("^localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout\\.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "X-Requested-With");
  httpHeaders.add("Access-Control-Request-Method", "GET");
  httpHeaders.add("Origin", "fuzzybunnies.com");
  mockMvc.perform(options("/logout.do").headers(httpHeaders)).andExpect(status().isForbidden());
}
origin: cloudfoundry/uaa

/**
 * The access control request method is not a GET therefore CORS requests with the "X-Requested-With"
 * header are not allowed and the CorsFilter returns a 405.
 *
 * @throws Exception on test failure
 */
@Test
void testLogOutCorsPreflightWithUnallowedMethod(@Autowired CorsFilter corsFilter) throws Exception {
  corsFilter.setCorsXhrAllowedOrigins(singletonList("^localhost$"));
  corsFilter.setCorsXhrAllowedUris(singletonList("^/logout\\.do$"));
  corsFilter.initialize();
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.add("Access-Control-Request-Headers", "X-Requested-With");
  httpHeaders.add("Access-Control-Request-Method", "POST");
  httpHeaders.add("Origin", "localhost");
  mockMvc.perform(options("/logout.do").headers(httpHeaders)).andExpect(status().isMethodNotAllowed());
}
origin: cloudfoundry/uaa

@Test
void put_updateNothing_shouldFail() throws Exception {
  mockMvc.perform(put("/Users/" + seededUser.getId())
      .headers(zoneSeeder.getZoneIdRequestHeader())
      .header("Authorization", "Bearer " + uaaAdminToken)
      .header("If-Match", "\"" + seededUser.getVersion() + "\"")
      .accept(APPLICATION_JSON)
      .contentType(APPLICATION_JSON)
      .content(JsonUtils.writeValueAsBytes(seededUser)))
      .andDo(print())
      .andExpect(status().is(403))
      .andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(
          new JSONObject()
              .put("error_description", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("message", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("error", "internal_user_management_disabled"))));
}
origin: spring-io/initializr

    uri.toString());
requestBuilder.content(getBodyAsBytes());
requestBuilder.headers(getHeaders());
MockHttpServletResponse servletResponse = actions(requestBuilder)
    .andReturn().getResponse();
origin: cloudfoundry/uaa

@Test
void patch_updateUserEmail_WithAccessToken_ShouldFail() throws Exception {
  String accessToken = testClient.getUserOAuthAccessTokenForZone(
      zoneSeeder.getImplicitPasswordRefreshTokenClient().getClientId(),
      "",
      seededUser.getUserName(),
      zoneSeeder.getPlainTextPassword(seededUser),
      "openid",
      zoneSeeder.getIdentityZoneSubdomain());
  seededUser.addEmail("addAnotherNew@email.com");
  MockHttpServletRequestBuilder patch = patch("/Users/" + seededUser.getId())
      .headers(zoneSeeder.getZoneSubomainRequestHeader())
      .header("Authorization", "Bearer " + accessToken)
      .header("If-Match", "\"" + seededUser.getVersion() + "\"")
      .accept(APPLICATION_JSON)
      .contentType(APPLICATION_JSON)
      .content(JsonUtils.writeValueAsBytes(seededUser));
  mockMvc.perform(patch)
      .andExpect(status().is(403))
      .andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(
          new JSONObject()
              .put("error_description", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("message", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("error", "internal_user_management_disabled"))));
}
origin: cloudfoundry/uaa

@Test
void put_updateUserEmail_WithAccessToken_ShouldFail() throws Exception {
  String accessToken = testClient.getUserOAuthAccessTokenForZone(
      zoneSeeder.getImplicitPasswordRefreshTokenClient().getClientId(),
      "",
      seededUser.getUserName(),
      zoneSeeder.getPlainTextPassword(seededUser),
      "openid",
      zoneSeeder.getIdentityZoneSubdomain());
  seededUser.setEmails(null);
  seededUser.addEmail("resetEmail@mail.com");
  MockHttpServletRequestBuilder put = put("/Users/" + seededUser.getId())
      .headers(zoneSeeder.getZoneSubomainRequestHeader())
      .header("Authorization", "Bearer " + accessToken)
      .header("If-Match", "\"" + seededUser.getVersion() + "\"")
      .accept(APPLICATION_JSON)
      .contentType(APPLICATION_JSON)
      .content(JsonUtils.writeValueAsBytes(seededUser));
  mockMvc.perform(put).andDo(print())
      .andExpect(status().is(403))
      .andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(
          new JSONObject()
              .put("error_description", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("message", "Internal User Creation is currently disabled. External User Store is in use.")
              .put("error", "internal_user_management_disabled"))));
}
origin: org.apache.servicemix.bundles/org.apache.servicemix.bundles.spring-test

private ClientHttpResponse getClientHttpResponse(
    HttpMethod httpMethod, URI uri, HttpHeaders requestHeaders, byte[] requestBody) {
  try {
    MockHttpServletResponse servletResponse = this.mockMvc
        .perform(request(httpMethod, uri).content(requestBody).headers(requestHeaders))
        .andReturn()
        .getResponse();
    HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
    byte[] body = servletResponse.getContentAsByteArray();
    MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
    clientResponse.getHeaders().putAll(getResponseHeaders(servletResponse));
    return clientResponse;
  }
  catch (Exception ex) {
    byte[] body = ex.toString().getBytes(StandardCharsets.UTF_8);
    return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
origin: apache/servicemix-bundles

  @Override
  public ClientHttpResponse executeInternal() throws IOException {
    try {
      MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri);
      requestBuilder.content(getBodyAsBytes());
      requestBuilder.headers(getHeaders());
      MvcResult mvcResult = MockMvcClientHttpRequestFactory.this.mockMvc.perform(requestBuilder).andReturn();
      MockHttpServletResponse servletResponse = mvcResult.getResponse();
      HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
      byte[] body = servletResponse.getContentAsByteArray();
      HttpHeaders headers = getResponseHeaders(servletResponse);
      MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
      clientResponse.getHeaders().putAll(headers);
      return clientResponse;
    }
    catch (Exception ex) {
      byte[] body = ex.toString().getBytes(UTF8_CHARSET);
      return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
};
origin: org.activiti.cloud.common/activiti-cloud-services-test

/**
 * Perform GET [href] with an explicit Accept media type using MockMvc. Verify the requests succeeded and also came
 * back as the Accept type.
 *
 * @param href
 * @param contentType
 * @return a mocked servlet response with results from GET [href]
 * @throws Exception
 */
public MockHttpServletResponse request(String href, MediaType contentType, HttpHeaders httpHeaders)
                                                  throws Exception {
  return mvc.perform(get(href).accept(contentType).headers(httpHeaders)). //
       andExpect(status().isOk()). //
       andExpect(content().contentType(contentType)). //
       andReturn().getResponse();
}
org.springframework.test.web.servlet.requestMockHttpServletRequestBuilderheaders

Javadoc

Add all headers to the request. Values are always added.

Popular methods of MockHttpServletRequestBuilder

  • contentType
    Set the 'Content-Type' header of the request.
  • content
    Set the request body.
  • param
    Add a request parameter to the MockHttpServletRequest.If called more than once, new values get added
  • accept
    Set the 'Accept' header to the given media type(s).
  • header
    Add a header to the request. Values are always added.
  • with
    An extension point for further initialization of MockHttpServletRequestin ways not built directly in
  • requestAttr
    Set a request attribute.
  • buildRequest
    Build a MockHttpServletRequest.
  • contextPath
    Specify the portion of the requestURI that represents the context path. The context path, if specifi
  • principal
    Set the principal of the request.
  • flashAttr
    Set an "input" flash attribute.
  • session
    Set the HTTP session to use, possibly re-used across requests.Individual attributes provided via #se
  • flashAttr,
  • session,
  • sessionAttr,
  • cookie,
  • params,
  • servletPath,
  • <init>,
  • characterEncoding,
  • locale

Popular in Java

  • Making http post requests using okhttp
  • scheduleAtFixedRate (ScheduledExecutorService)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • getSystemService (Context)
  • GridBagLayout (java.awt)
    The GridBagLayout class is a flexible layout manager that aligns components vertically and horizonta
  • Permission (java.security)
    Legacy security code; do not use.
  • SQLException (java.sql)
    An exception that indicates a failed JDBC operation. It provides the following information about pro
  • Notification (javax.management)
  • Reference (javax.naming)
  • Join (org.hibernate.mapping)
  • 14 Best Plugins for Eclipse
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now