Example usage for org.springframework.http HttpHeaders add

List of usage examples for org.springframework.http HttpHeaders add

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders add.

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

From source file:org.echocat.marquardt.example.ServiceLoginIntegrationTest.java

private void whenAccessingProtectedResourceWithSelfSignedCertificate(final byte[] attackersCertificate) {
    final RestTemplate restTemplate = new RestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    headers.add(X_CERTIFICATE.getHeaderName(), new String(attackersCertificate));
    final HttpEntity<Object> requestEntity = new HttpEntity<>(headers);

    restTemplate.exchange(baseUriOfApp() + "/exampleservice/someProtectedResource", HttpMethod.POST,
            requestEntity, Void.class);
}

From source file:com.blogspot.sgdev.blog.GrantByAuthorizationCodeProviderTest.java

@Test
public void getJwtTokenByAuthorizationCode()
        throws JsonParseException, JsonMappingException, IOException, URISyntaxException {
    String redirectUrl = "http://localhost:" + port + "/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user", "password").postForEntity(
            "http://localhost:" + port
                    + "/oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}",
            null, String.class, redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user", "password").postForEntity("http://localhost:" + port
            + "oauth/authorize?response_type=code&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<Void>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());//from   w  w  w . ja  va 2  s  .  co  m
    String location = response.getHeaders().get("Location").get(0);
    URI locationURI = new URI(location);
    String query = locationURI.getQuery();

    location = "http://localhost:" + port + "/oauth/token?" + query
            + "&grant_type=authorization_code&client_id=normal-app&redirect_uri={redirectUrl}";

    response = new TestRestTemplate("normal-app", "").postForEntity(location,
            new HttpEntity<Void>(new HttpHeaders()), String.class, redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    HashMap jwtMap = new ObjectMapper().readValue(response.getBody(), HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/client", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal",
            HttpMethod.GET, new HttpEntity<String>(null, headers), String.class);
    assertEquals("user", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET,
            new HttpEntity<String>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody());
}

From source file:org.eclipse.virgo.samples.rest.RestController.java

public ResponseEntity<String> createResponseEntity(String json, HttpStatus status) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");
    return new ResponseEntity<String>(json + "\n", headers, status);
}

From source file:example.company.UrlLevelSecurityTests.java

@Test
public void allowsGetRequestsButRejectsPostForUser() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.ACCEPT, MediaTypes.HAL_JSON.toString());
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encode(("greg:turnquist").getBytes())));

    mvc.perform(get("/employees").//
            headers(headers)).//
            andExpect(content().contentType(MediaTypes.HAL_JSON)).//
            andExpect(status().isOk()).//
            andDo(print());//from   w  w  w. j  ava 2 s.c  o m

    mvc.perform(post("/employees").//
            headers(headers)).//
            andExpect(status().isForbidden()).//
            andDo(print());
}

From source file:io.syndesis.runtime.action.DynamicActionSqlStoredITCase.java

@Test
public void shouldOfferDynamicActionPropertySuggestions() {

    final HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    final ResponseEntity<ActionDefinition> firstResponse = http(HttpMethod.POST,
            "/api/v1/connections/" + connectionId + "/actions/io.syndesis:sql-stored-connector:latest", null,
            ActionDefinition.class, tokenRule.validToken(), headers, HttpStatus.OK);

    ConfigurationProperty procedureNames = firstResponse.getBody().getPropertyDefinitionSteps().iterator()
            .next().getProperties().get("procedureName");
    assertThat(procedureNames.getEnum().size() == 2);
    assertThat(procedureNames.getEnum().iterator().next().getLabel().startsWith("DEMO_ADD"));

    final ResponseEntity<ActionDefinition> secondResponse = http(HttpMethod.POST,
            "/api/v1/connections/" + connectionId + "/actions/io.syndesis:sql-stored-connector:latest",
            Collections.singletonMap("procedureName", "DEMO_ADD"), ActionDefinition.class,
            tokenRule.validToken(), headers, HttpStatus.OK);

    final Map<String, ConfigurationProperty> secondRequestProperties = secondResponse.getBody()
            .getPropertyDefinitionSteps().get(0).getProperties();
    assertThat(secondRequestProperties.get("template").getDefaultValue())
            .isEqualTo("DEMO_ADD(INTEGER ${body[A]}, INTEGER ${body[B]}, INTEGER ${body[C]})");
}

From source file:com.devnexus.ting.web.controller.CalendarController.java

@RequestMapping(value = { "/{eventKey}/usercalendar" }, method = RequestMethod.GET)
@ResponseBody/*from  w w w .j  a  v a  2 s . com*/
public ResponseEntity<List<UserCalendar>> calendar(@PathVariable("eventKey") String eventKey)
        throws JsonProcessingException {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");

    if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) {

        headers.add("WWW-Authenticate", "Google realm=\"http://www.devnexus.org\"");

        return new ResponseEntity<List<UserCalendar>>(new ArrayList<UserCalendar>(), headers,
                HttpStatus.UNAUTHORIZED);
    }

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<UserCalendar> calendar = calendarService.getUserCalendar(user, eventKey);
    return new ResponseEntity<>(calendar, headers, HttpStatus.OK);
}

From source file:org.cloudfoundry.identity.uaa.integration.VmcScimUserEndpointIntegrationTests.java

@SuppressWarnings("rawtypes")
private ResponseEntity<Map> deleteUser(RestOperations client, String id, int version) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + version + "\"");
    return client.exchange(serverRunning.getUrl(usersEndpoint + "/{id}"), HttpMethod.DELETE,
            new HttpEntity<Void>(headers), Map.class, id);
}

From source file:sp.CASController.java

/**
 * Produce a page displaying a link to the CAS validation endpoint.
 * //from w  ww.j  a  va 2s  . c om
 * @param servletRequest
 * @param servletResponse
 * @return HTML displaying a link to the CAS validation endpoint
 * @throws Exception
 */
@RequestMapping(value = "/Service", method = RequestMethod.GET)
public ResponseEntity<String> handleCASResponse(HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws Exception {

    final String baseUrl = getBaseUrl(servletRequest);

    final String endpointURL = baseUrl + idpCASEndpointPath + "/serviceValidate";

    final URLBuilder urlBuilder = new URLBuilder(endpointURL);

    final String ticket = servletRequest.getParameter(ProtocolParam.Ticket.id());

    final List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
    queryParams.add(new Pair<String, String>(ProtocolParam.Service.id(), baseUrl + casSPServicePath));
    queryParams.add(new Pair<String, String>(ProtocolParam.Ticket.id(), ticket));

    final String redirectURL = urlBuilder.buildURL();

    final String html = "<html><body><a id=cas-service-validate href=\"" + redirectURL
            + "\">CAS Service Validate</a></body></html>";
    log.trace("Returning html '{}'", html);

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/html");

    return new ResponseEntity<>(html, headers, HttpStatus.OK);
}

From source file:com.gopivotal.cla.github.GitHubConditionalTest.java

@Test
public void noNextLink() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Link", "<" + URL + ">; rel=\"first\"");
    ResponseEntity<Set> response = new ResponseEntity<Set>(Sets.asSet(), headers, HttpStatus.OK);
    when(this.restOperations.exchange(URL, HttpMethod.GET, REQUEST_ENTITY, Set.class)).thenReturn(response);

    this.gitHubType.getTrigger();

    assertTrue(this.gitHubType.initializedCalled);
}

From source file:com.consol.citrus.samples.flightbooking.header.HttpHeaderMapper.java

@Override
public void fromHeaders(MessageHeaders headers, HttpHeaders target) {
    super.fromHeaders(headers, target);

    //Fix issue with default header mapper not mapping non-string header values
    target.add("X-sequenceNumber", getSequenceNumber(headers).toString());
    target.add("X-sequenceSize", getSequenceSize(headers).toString());
}