Example usage for org.springframework.http HttpHeaders HttpHeaders

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

Introduction

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

Prototype

public HttpHeaders() 

Source Link

Document

Construct a new, empty instance of the HttpHeaders object.

Usage

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

@RequestMapping(value = { "/{eventKey}/usercalendar" }, method = RequestMethod.GET)
@ResponseBody// w  ww .  java 2  s .c  o m
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:com.orange.cepheus.cep.EventSinkListenerTest.java

/**
 * Check that an updateContext is fired when a new event bean arrives
 *///from w  w w.j  ava2s .c o m
@Test
public void postMessageOnEventUpdate() {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    when(statement.getText()).thenReturn("statement");
    when(ngsiClient.getRequestHeaders(any())).thenReturn(httpHeaders);

    // Trigger event update
    List<ContextAttribute> attributes = new LinkedList<>();
    attributes.add(new ContextAttribute("id", "string", "OUT1234"));
    attributes.add(new ContextAttribute("avgTemp", "double", 10.25));
    attributes.add(new ContextAttribute("avgTemp_unit", "string", "celcius"));
    EventBean[] beans = { buildEventBean("TempSensorAvg", attributes) };
    eventSinkListener.update(beans, null, statement, provider);

    // Capture updateContext when postUpdateContextRequest is called on updateContextRequest,
    ArgumentCaptor<UpdateContext> updateContextArg = ArgumentCaptor.forClass(UpdateContext.class);
    ArgumentCaptor<HttpHeaders> headersArg = ArgumentCaptor.forClass(HttpHeaders.class);

    verify(ngsiClient).updateContext(eq(broker.getUrl()), headersArg.capture(), updateContextArg.capture());

    // Check updateContext is valid
    UpdateContext updateContext = updateContextArg.getValue();
    assertEquals(UpdateAction.APPEND, updateContext.getUpdateAction());
    assertEquals(1, updateContext.getContextElements().size());

    // Check headers are valid
    HttpHeaders headers = headersArg.getValue();
    assertEquals(MediaType.APPLICATION_JSON, headers.getContentType());
    assertTrue(headers.getAccept().contains(MediaType.APPLICATION_JSON));
    assertEquals("SN", headers.getFirst("Fiware-Service"));
    assertEquals("SP", headers.getFirst("Fiware-ServicePath"));
    assertEquals("AUTH_TOKEN", headers.getFirst("X-Auth-Token"));

    ContextElement contextElement = updateContext.getContextElements().get(0);
    assertEquals("OUT1234", contextElement.getEntityId().getId());
    assertEquals("TempSensorAvg", contextElement.getEntityId().getType());
    assertFalse(contextElement.getEntityId().getIsPattern());
    assertEquals(1, contextElement.getContextAttributeList().size());

    ContextAttribute attr = contextElement.getContextAttributeList().get(0);
    assertEquals("avgTemp", attr.getName());
    assertEquals("double", attr.getType());
    assertEquals(10.25, attr.getValue());
    assertEquals(1, attr.getMetadata().size());
    assertEquals("unit", attr.getMetadata().get(0).getName());
    assertEquals("string", attr.getMetadata().get(0).getType());
    assertEquals("celcius", attr.getMetadata().get(0).getValue());
}

From source file:com.springsource.html5expense.security.EndpointTokenServices.java

public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    // TODO: Probably should catch REST client exceptions and rethrow as AuthenticationException
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
    ResponseEntity<OAuth2Authentication> response = restTemplate.exchange(oauthAuthenticationUrl,
            HttpMethod.GET, requestEntity, OAuth2Authentication.class);

    OAuth2Authentication oauth2Authentication = response.getBody();
    return oauth2Authentication;
}

From source file:edu.wisc.cypress.dao.taxstmt.RestTaxStatementDao.java

@Override
public void getTaxStatement(String emplid, String docId, ProxyResponse proxyResponse) {
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("HRID", emplid);
    this.restOperations.proxyRequest(proxyResponse, this.statementUrl, HttpMethod.GET, httpHeaders, docId);
}

From source file:org.trustedanalytics.routermetrics.gathering.GatheringConfig.java

private HttpEntity<byte[]> getGorouterHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(
                    encodeBase64((gorouterProperties.getUsername() + ":" + gorouterProperties.getPassword())
                            .getBytes(Charset.forName("US-ASCII")))));
    return new HttpEntity<>(headers);
}

From source file:com.bailen.radioOnline.recursos.REJA.java

public Cancion[] random(String apiKey) throws IOException {
    HttpHeaders header = new HttpHeaders();
    header.set("Authorization", apiKey);
    HttpEntity entity = new HttpEntity(header);
    String lista = new String();
    HttpEntity<String> response;
    response = new RestTemplate().exchange("http://ceatic.ujaen.es:8075/radioapi/v2/random", HttpMethod.GET,
            entity, String.class, lista);

    String canc = response.getBody();
    StringTokenizer st = new StringTokenizer(canc, "[", true);
    st.nextToken();/*from  ww w  . jav  a2 s  . c  om*/
    st.nextToken();
    canc = "[" + st.nextToken();

    try {

        ObjectMapper a = new ObjectMapper();
        Item[] listilla = a.readValue(canc, Item[].class);
        Vector<Integer> ids = new Vector<>();
        for (int i = 0; i < listilla.length; ++i) {
            ids.add(listilla[i].getId());
        }
        return jamendo.canciones(ids);

    } catch (Exception e) {
        //return null;
        throw new IOException("no se han recibido canciones");
    }

}

From source file:cn.dsgrp.field.stock.rest.TaskRestController.java

@RequestMapping(method = RequestMethod.POST, consumes = MediaTypes.JSON)
public ResponseEntity<?> create(@RequestBody Task task, UriComponentsBuilder uriBuilder) {
    // JSR303 Bean Validator, RestExceptionHandler?.
    BeanValidators.validateWithException(validator, task);

    // ?/* w ww. j av  a  2s . c o m*/
    taskService.saveTask(task);

    // Restful?url, ?id.
    BigInteger id = task.getId();
    URI uri = uriBuilder.path("/api/v1/task/" + id).build().toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);

    return new ResponseEntity(headers, HttpStatus.CREATED);
}

From source file:khs.trouble.service.impl.TroubleService.java

public String kill(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }//w  w w.jav  a 2 s. co m

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "trouble/kill", ssl);

    // invoke kill api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        // int instanceCount = registry.instanceCount(serviceName);
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            eventService.killed(serviceName, url);
            // monitorServiceRecovery(serviceName, instanceCount);
        }
    } catch (Exception e) {
        eventService.attempted("Attempted to Kill service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:com.nebhale.buildmonitor.web.ProjectController.java

@Transactional
@RequestMapping(method = RequestMethod.POST, value = "", produces = MEDIA_TYPE)
ResponseEntity<?> create(@RequestBody Project project) {
    if (this.repository.exists(project.getKey())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }//www. ja va  2s .c  om

    this.repository.saveAndFlush(project);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(linkTo(ProjectController.class).slash(project.getKey()).toUri());

    this.projectsChangedNotifier.projectsChanged();
    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}