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:ch.ralscha.extdirectspring.controller.RouterControllerOptionalTest.java

@Test
public void testStoreRead2() {

    HttpHeaders headers = new HttpHeaders();
    headers.add("requestHeader", "rValue");

    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("cookie", "cValue"));

    Map<String, Object> readRequest = new HashMap<String, Object>();
    readRequest.put("query", "name");

    ExtDirectStoreResult<Row> storeResponse = (ExtDirectStoreResult<Row>) ControllerUtil.sendAndReceive(mockMvc,
            headers, cookies, "remoteProviderOptional", "storeRead2",
            new TypeReference<ExtDirectStoreResult<Row>>() {
                // nothing here
            }, readRequest);//from   w ww .  j  av  a 2  s .  co m

    assertThat(storeResponse.getTotal()).isEqualTo(50L);
    assertThat(storeResponse.getRecords()).hasSize(50);
    int ix = 0;
    for (Row row : storeResponse.getRecords()) {
        assertThat(row.getName()).startsWith("name: " + ix + ":cValue:rValue");
        ix += 2;
    }

    readRequest = new HashMap<String, Object>();
    readRequest.put("query", "name");

    storeResponse = (ExtDirectStoreResult<Row>) ControllerUtil.sendAndReceive(mockMvc, "remoteProviderOptional",
            "storeRead2", new TypeReference<ExtDirectStoreResult<Row>>() {
                // nothing here
            }, readRequest);

    assertThat(storeResponse.getTotal()).isEqualTo(50L);
    assertThat(storeResponse.getRecords()).hasSize(50);
    ix = 0;
    for (Row row : storeResponse.getRecords()) {
        assertThat(row.getName()).startsWith("name: " + ix + ":defaultCookie:defaultHeader");
        ix += 2;
    }
}

From source file:cz.muni.fi.mushroomhunter.restclient.LocationCreateSwingWorker.java

@Override
protected Void doInBackground() throws Exception {
    LocationDto locationDto = new LocationDto();
    locationDto.setName(restClient.getTfLocationName().getText());
    locationDto.setDescription(restClient.getTfLocationDescription().getText());
    locationDto.setNearCity(restClient.getTfLocationNearCity().getText());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);// w w  w  .  j  ava  2  s.  c o m
    headers.setAccept(mediaTypeList);

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(locationDto);

    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    headers.add("Authorization", "Basic " + base64Creds);
    HttpEntity request = new HttpEntity(json, headers);

    Long[] result = restTemplate.postForObject(RestClient.SERVER_URL + "pa165/rest/location", request,
            Long[].class);

    RestClient.getLocationIDs().add(result[0]);
    return null;
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerSimpleNamedTest.java

@Test
public void testNonStrictMethod3() {
    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("aSimpleCookie", "cookie"));
    HttpHeaders headers = new HttpHeaders();
    headers.add("aSimpleHeader", "header");
    Map<String, Object> params = new LinkedHashMap<String, Object>();
    params.put("i", 17);
    ControllerUtil.sendAndReceiveNamed(mockMvc, headers, cookies, "remoteProviderSimpleNamed",
            "nonStrictMethod3", "nonStrictMethod3() called-17-cookie-header", params);
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerSseTest.java

@Test
public void sseRequiredHeaderWithValue() throws Exception {
    Map<String, String> params = new HashMap<String, String>();
    params.put("id", "1");

    HttpHeaders headers = new HttpHeaders();
    headers.add("header", "headerValue");
    headers.add("anotherName", "headerValue1");
    headers.add("anotherName", "headerValue2");

    List<SSEvent> events = ControllerUtil.performSseRequest(mockMvc, "sseProvider", "messageRequestHeader2",
            params, headers, null);/*w w  w. j  a  va2s . c o m*/
    assertThat(events).hasSize(1);
    SSEvent event = events.get(0);

    assertThat(event.getEvent()).isNull();
    assertThat(event.getComment()).isNull();
    assertThat(event.getData()).startsWith("1;headerValue1");
    assertThat(event.getId()).isNull();
    assertThat(event.getRetry()).isNull();

    params.clear();
    params.put("id", "2");

    events = ControllerUtil.performSseRequest(mockMvc, "sseProvider", "messageRequestHeader2", params, null,
            null, true);
    assertThat(events).hasSize(1);
    event = events.get(0);

    assertThat(event.getEvent()).isEqualTo("error");
    assertThat(event.getComment()).isNull();
    assertThat(event.getData()).startsWith("Server Error");
    assertThat(event.getId()).isNull();
    assertThat(event.getRetry()).isNull();
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerSimpleNamedTest.java

@Test
public void testRequestHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("aSimpleHeader", "theHeaderValue");

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("bd", new BigDecimal("1.1"));
    ControllerUtil.sendAndReceiveNamed(mockMvc, headers, null, "remoteProviderSimpleNamed", "withRequestHeader",
            "1.1:theHeaderValue", params);

    params = new HashMap<String, Object>();
    params.put("bd", new BigDecimal("1.2"));
    ControllerUtil.sendAndReceiveNamed(mockMvc, null, null, "remoteProviderSimpleNamed", "withRequestHeader",
            "1.2:defaultHeader", params);

    headers = new HttpHeaders();
    headers.add("aSimpleHeader", "theHeaderValue2");

    params = new HashMap<String, Object>();
    params.put("bd", new BigDecimal("1.2"));
    ControllerUtil.sendAndReceiveNamed(mockMvc, headers, null, "remoteProviderSimpleNamed",
            "withRequiredRequestHeader", "1.2:theHeaderValue2", params);

    params = new HashMap<String, Object>();
    params.put("bd", new BigDecimal("1.3"));
    ControllerUtil.sendAndReceiveNamed(mockMvc, null, null, "remoteProviderSimpleNamed",
            "withRequiredRequestHeader", null, params);
}

From source file:com.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Kuvasta tykkys//  w w  w.  j  a  va2 s  . c  o  m
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param redirect Uudelleenohjaus
 * @param req HTTP Request
 * @return Onnistuiko pyynt vai ei (sek sen tyyppi; unlike vai like).
 */
@RequestMapping(value = "/like", method = RequestMethod.POST)
public ResponseEntity<String> likeImage(Authentication a, @RequestParam String imageUuid,
        @RequestParam int redirect, HttpServletRequest req) {
    //Kyttjn autentikoiminen
    UserAccount u = userService.getUserByUsername(a.getName());
    final HttpHeaders h = new HttpHeaders();
    //Jos kyttjtili ei ole tyhj
    if (u != null) {
        //Haetaan kuva
        Image i = imageService.findOneImageByUuid(imageUuid);

        //Jos kuva ei ole tyhj
        if (i != null && i.isVisible()) {
            //Lis / poista tykkys tilanteen mukaan
            if (i.getLikedBy().contains(u)) {
                LOG.log(Level.INFO, "Kayttaja ''{0}'' poisti tykkayksen kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                i.removeLike(u);
                imageService.saveImage(i);
                h.add("LikeType", "unlike");
            } else {
                i.addLike(u);
                LOG.log(Level.INFO, "Kayttaja ''{0}'' tykkasi kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                imageService.saveImage(i);
                h.add("LikeType", "like");
            }
            //Uudelleenohjaus
            if (redirect == 1) {
                h.add("Location", req.getHeader("Referer"));
                return new ResponseEntity<>(h, HttpStatus.FOUND);
            }
            return new ResponseEntity<>(h, HttpStatus.OK);
        } else {
            //Jos kuvaa ei ole olemassa mutta yritetn silti tykt
            LOG.log(Level.WARNING, "Kayttaja ''{0}'' yritti tykata kuvaa, mita ei ole olemassa. ({1})",
                    new Object[] { a.getName(), imageUuid });
            return new ResponseEntity<>(h, HttpStatus.BAD_REQUEST);
        }
    }
    //Jos ei olla kirjauduttu sisn ja yritetn tykt kuvasta
    LOG.log(Level.WARNING, "Yritettiin tykata kuvaa kirjautumatta sisaan ({0})", a.getName());
    return new ResponseEntity<>(h, HttpStatus.UNAUTHORIZED);
}

From source file:com.aktios.appthree.server.service.OAuthAuthenticationService.java

public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) {
    RestOperations rest = new RestTemplate();

    HttpHeaders headersA = new HttpHeaders();
    headersA.set("Authorization", "Bearer " + accessTokenA);

    ResponseEntity<String> resAuth2 = rest.exchange(
            MessageFormat.format(
                    "{0}/oauth/authorize?"
                            + "client_id={1}&response_type=code&redirect_uri={2}&scope=read,write",
                    oauthServerBaseURL, appTokenClientTwo, redirectUri),
            HttpMethod.GET, new HttpEntity<String>(headersA), String.class);

    String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0);
    int p1 = sessionId.indexOf("=") + 1;
    int p2 = sessionId.indexOf(";");
    sessionId = sessionId.substring(p1, p2);
    headersA.add("Cookie", "JSESSIONID=" + sessionId);

    resAuth2 = rest.exchange(/*from   w  w  w.j a v  a  2 s  .  com*/
            MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize",
                    oauthServerBaseURL),
            HttpMethod.POST, new HttpEntity<String>(headersA), String.class);

    String code = resAuth2.getHeaders().get("location").get(0);
    p1 = code.lastIndexOf("=") + 1;
    code = code.substring(p1);

    return code;
}

From source file:ru.anr.base.facade.web.api.RestClient.java

/**
 * Applying for default headers/* w ww. jav  a2  s  .com*/
 * 
 * @return {@link HttpHeaders} object
 */
protected HttpHeaders applyHeaders() {

    HttpHeaders hh = new HttpHeaders();
    if (contentType != null) {
        hh.setContentType(contentType);
    }
    if (accept != null) {
        hh.setAccept(list(accept));
        hh.setAcceptCharset(list(Charset.forName("utf-8")));
    }

    if (basicCredentials != null) {
        hh.add("Authorization", basicCredentials);
    }

    return hh;
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetEntities_Paginated() throws Exception {

    HttpHeaders responseHeader = new HttpHeaders();
    responseHeader.add("X-Total-Count", "12");

    mockServer.expect(requestTo(baseURL + "/v2/entities?offset=2&limit=10&options=count"))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(
                    withSuccess(Utils.loadResource("json/getEntitiesResponse.json"), MediaType.APPLICATION_JSON)
                            .headers(responseHeader));

    Paginated<Entity> entities = ngsiClient.getEntities(null, null, null, null, 2, 10, true).get();
    assertEquals(2, entities.getOffset());
    assertEquals(10, entities.getLimit());
    assertEquals(12, entities.getTotal());
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetSubscriptions_Paginated() throws Exception {

    HttpHeaders responseHeader = new HttpHeaders();
    responseHeader.add("X-Total-Count", "1");

    mockServer.expect(requestTo(baseURL + "/v2/subscriptions?offset=2&limit=10&options=count"))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE))
            .andRespond(withSuccess(Utils.loadResource("json/getSubscriptionsResponse.json"),
                    MediaType.APPLICATION_JSON).headers(responseHeader));

    Paginated<Subscription> subscriptions = ngsiClient.getSubscriptions(2, 10, true).get();

    assertEquals(2, subscriptions.getOffset());
    assertEquals(10, subscriptions.getLimit());
    assertEquals(1, subscriptions.getTotal());
}