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.cloudfoundry.identity.uaa.integration.ScimUserEndpointsIntegrationTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from  ww  w . jav  a  2 s .co m
public void testJsonCaseInsensitivity() throws Exception {

    ResponseEntity<ScimUser> created = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = created.getBody();
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<String, Object>(
            mapper.readValue(mapper.writeValueAsString(joe), Map.class));
    map.put("username", JOE + "0");
    map.remove("userName");
    ResponseEntity<ScimUser> response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}",
            HttpMethod.PUT, new HttpEntity<Map>(map, headers), ScimUser.class, joe.getId());
    ScimUser joe1 = response.getBody();
    assertEquals(JOE + "0", joe1.getUserName());
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test/*  w w w. j a v  a2 s.c  o  m*/
public void updateUserWithBadAttributeFails() throws Exception {

    ResponseEntity<ScimUser> created = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = created.getBody();
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<String, Object>(
            mapper.readValue(mapper.writeValueAsString(joe), Map.class));
    map.put("nottheusername", JOE + "0");
    ResponseEntity<Map> response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}", HttpMethod.PUT,
            new HttpEntity<Map>(map, headers), Map.class, joe.getId());
    Map<String, Object> joe1 = response.getBody();
    assertTrue("Wrong message: " + joe1,
            ((String) joe1.get("message")).toLowerCase().contains("unrecognized field"));

}

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

@Test
public void updateUserWithNewAuthoritiesSucceeds() throws Exception {
    ResponseEntity<ScimUser> response = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = response.getBody();/*from  w w w.j  av  a 2s .  c o m*/
    assertEquals(JOE, joe.getUserName());

    joe.setUserType("admin");

    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}", HttpMethod.PUT,
            new HttpEntity<ScimUser>(joe, headers), ScimUser.class, joe.getId());
    ScimUser joe1 = response.getBody();
    assertEquals(JOE, joe1.getUserName());

    assertEquals(joe.getId(), joe1.getId());
    assertNull(joe1.getUserType()); // check that authorities was not updated

}

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

@Test
public void updateUserGroupsDoesNothing() {
    ResponseEntity<ScimUser> response = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = response.getBody();//from   ww  w.j  ava  2 s . c om
    assertEquals(JOE, joe.getUserName());
    assertEquals(NUM_DEFAULT_GROUPS_ON_STARTUP, joe.getGroups().size());

    joe.setGroups(Arrays.asList(new ScimUser.Group(UUID.randomUUID().toString(), "uaa.admin")));

    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}", HttpMethod.PUT,
            new HttpEntity<ScimUser>(joe, headers), ScimUser.class, joe.getId());
    ScimUser joe1 = response.getBody();
    assertEquals(JOE, joe1.getUserName());

    assertEquals(joe.getId(), joe1.getId());
    assertEquals(NUM_DEFAULT_GROUPS_ON_STARTUP, joe1.getGroups().size());
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(value = "/json/{name}.{ext}", method = RequestMethod.POST)
public HttpEntity<byte[]> exportFromJson(@PathVariable("name") String name,
        @PathVariable("ext") String extension, @RequestBody String requestBody)
        throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException {

    String randomFilename;//from   w w w  .  j a v a2s .  co m
    randomFilename = null;
    String json = requestBody;
    MimeType mime = getMime(extension);

    // add outfile parameter to the json with a simple string replace
    if (MimeType.PDF.equals(mime)) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
        int ind = json.lastIndexOf("}");
        json = new StringBuilder(json).replace(ind, ind + 1, ",\"outfile\":\"" + randomFilename).toString()
                + "\"}";
    }

    String result = converter.requestServer(json);
    ByteArrayOutputStream stream;
    if (randomFilename != null && randomFilename.equals(result)) {
        stream = writeFileToStream(randomFilename);
    } else {
        boolean base64 = !mime.getExtension().equals("svg");
        stream = outputToStream(result, base64);
    }

    HttpHeaders headers = new HttpHeaders();

    headers.add("Content-Type", mime.getType() + "; charset=utf-8");
    headers.add("Content-Disposition", "attachment; filename=" + name + "." + extension);
    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:eu.freme.common.rest.OwnedResourceManagingController.java

@RequestMapping(method = RequestMethod.GET)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> getAllEntities() {
    try {/*from   ww w  . jav a2s.c o m*/
        List<Entity> entities = entityDAO.findAllReadAccessible();
        String serialization = entities.stream().map(p -> {
            try {
                return p.toJson();
            } catch (JsonProcessingException e) {
                throw new FREMEHttpException("Could not serialize entity with identifier=\"" + p.getIdentifier()
                        + "\" to JSON. " + e.getMessage());
            }
        }).collect(Collectors.joining(",\n"));

        HttpHeaders responseHeaders = new HttpHeaders();
        //ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        //String serialization = ow.writeValueAsString(entities);
        responseHeaders.add("Content-Type", SerializationFormatMapper.JSON);
        return new ResponseEntity<>("[" + serialization + "]", responseHeaders, HttpStatus.OK);
    } catch (FREMEHttpException ex) {
        logger.error(ex.getMessage());
        throw ex;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new FREMEHttpException(ex.getMessage());
    }
}

From source file:org.cloudfoundry.identity.statsd.integration.UaaMetricsEmitterIT.java

@Test
public void testStatsDClientEmitsMetricsCollectedFromUAA() throws InterruptedException, IOException {
    RestTemplate template = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.set(headers.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> loginResponse = template.exchange(UAA_BASE_URL + "/login", HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);

    if (loginResponse.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : loginResponse.getHeaders().get("Set-Cookie")) {
            headers.add("Cookie", cookie);
        }//from   w  w w.  j av  a  2 s.c o m
    }
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());

    LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("username", TEST_USERNAME);
    body.add("password", TEST_PASSWORD);
    body.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);
    loginResponse = template.exchange(UAA_BASE_URL + "/login.do", HttpMethod.POST,
            new HttpEntity<>(body, headers), String.class);
    assertEquals(HttpStatus.FOUND, loginResponse.getStatusCode());
    assertNotNull(getMessage("uaa.audit_service.user_authentication_count:1", 5000));
}

From source file:ch.heigvd.gamification.api.BadgesEndpoint.java

@Override
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> badgesPost(
        @ApiParam(value = "Badge to add", required = true) @RequestBody BadgeDTO body,
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken) {
    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);

    if (apiKey == null) {
        return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }/*from  www.ja va2s. com*/

    Application app = apiKey.getApp();

    if (body != null && app != null) {

        if (badgeRepository.findByNameAndApp(body.getName(), app) != null) {
            return new ResponseEntity("name already use", HttpStatus.UNPROCESSABLE_ENTITY);
        }
        Badge badge = new Badge();
        badge.setDescription(body.getDescription());
        badge.setName(body.getName());
        badge.setImage(body.getImageURI());
        badge.setApp(app);
        badgeRepository.save(badge);

        HttpHeaders responseHeaders = new HttpHeaders();

        UriComponents uriComponents = MvcUriComponentsBuilder
                .fromMethodName(BadgesEndpoint.class, "badgesBadgeIdGet", 1, badge.getId()).build();

        URI locationUri = uriComponents.toUri();
        responseHeaders.add("Location", uriComponents.toString());
        return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED);

    } else {
        return new ResponseEntity("no content is available", HttpStatus.BAD_REQUEST);
    }
}

From source file:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param oldSharedResourceSet// w  ww. j  av  a  2  s.  co  m
 * @param accessTokenValue
 */
private void unregisterOldResourceSet(SharedResourceSet oldSharedResourceSet, String accessTokenValue,
        Principal p) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + accessTokenValue);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.exchange(oldSharedResourceSet.getLocation(), HttpMethod.DELETE, request, String.class);

    resourceService.unshareResourceSet(p);
}

From source file:com.sitewhere.rest.service.SiteWhereClient.java

/**
 * Send a REST request and handle the response.
 * /*from w  ww .ja  v  a 2 s . co  m*/
 * @param url
 * @param method
 * @param input
 * @param clazz
 * @param vars
 * @return
 * @throws SiteWhereSystemException
 */
protected <S, T> S sendRest(String url, HttpMethod method, T input, Class<S> clazz, Map<String, String> vars)
        throws SiteWhereSystemException {
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", getAuthHeader());
        HttpEntity<T> entity = new HttpEntity<T>(input, headers);
        ResponseEntity<S> response = getClient().exchange(url, method, entity, clazz, vars);
        return response.getBody();
    } catch (ResourceAccessException e) {
        if (e.getCause() instanceof SiteWhereSystemException) {
            throw (SiteWhereSystemException) e.getCause();
        }
        throw new RuntimeException(e);
    }
}