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:org.cloudfoundry.identity.uaa.login.feature.SamlLoginIT.java

@Test
public void testContentTypes() throws Exception {
    String loginUrl = baseUrl + "/login";

    HttpHeaders jsonHeaders = new HttpHeaders();
    jsonHeaders.add("Accept", "application/json");
    ResponseEntity<Map> jsonResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(jsonHeaders), Map.class);
    assertThat(jsonResponseEntity.getHeaders().get("Content-Type").get(0),
            containsString(APPLICATION_JSON_VALUE));

    HttpHeaders htmlHeaders = new HttpHeaders();
    htmlHeaders.add("Accept", "text/html");
    ResponseEntity<Void> htmlResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(htmlHeaders), Void.class);
    assertThat(htmlResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE));

    HttpHeaders defaultHeaders = new HttpHeaders();
    defaultHeaders.add("Accept", "*/*");
    ResponseEntity<Void> defaultResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET,
            new HttpEntity<>(defaultHeaders), Void.class);
    assertThat(defaultResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE));
}

From source file:org.jnrain.mobile.network.NewPostRequest.java

@Override
public SimpleReturnCode loadDataFromNetwork() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("Content", _content);
    params.set("board", _brd);
    params.set("signature", Integer.toString(_signid));
    params.set("subject", _title);

    if (_is_new_thread) {
        params.set("ID", "");
        params.set("groupID", "");
        params.set("reID", "0");
    } else {//w  ww  . j a  v  a2s.co m
        params.set("ID", Long.toString(_tid));
        params.set("groupID", Long.toString(_tid));
        params.set("reID", Long.toString(_reid));
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);

    return getRestTemplate().postForObject(
            /* "http://rhymin.jnrain.com/api/post/new/", */
            "http://bbs.jnrain.com/rainstyle/apipost.php", req, SimpleReturnCode.class);
}

From source file:org.energyos.espi.thirdparty.web.custodian.AdministratorController.java

@RequestMapping(value = Routes.ROOT_SERVICE_STATUS, method = RequestMethod.GET)
public String showServiceStatus(ModelMap model) {

    ApplicationInformation applicationInformation = resourceService.findById(1L, ApplicationInformation.class);
    String statusUri = applicationInformation.getAuthorizationServerAuthorizationEndpoint()
            + "/ReadServiceStatus";
    // not sure this will work w/o the right seed information
    ////from w ww . j av  a2 s. co  m
    Authorization authorization = resourceService.findByResourceUri(statusUri, Authorization.class);
    RetailCustomer retailCustomer = authorization.getRetailCustomer();

    String accessToken = authorization.getAccessToken();
    String serviceStatus = "OK";

    try {

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Authorization", "Bearer " + accessToken);
        @SuppressWarnings({ "unchecked", "rawtypes" })
        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

        // get the subscription
        HttpEntity<String> httpResult = restTemplate.exchange(statusUri, HttpMethod.GET, requestEntity,
                String.class);

        // import it into the repository
        ByteArrayInputStream bs = new ByteArrayInputStream(httpResult.getBody().toString().getBytes());

        importService.importData(bs, retailCustomer.getId());

        List<EntryType> entries = importService.getEntries();

        // TODO: Use-Case 1 registration - service status

    } catch (Exception e) {
        // nothing there, so log the fact and move on. It will
        // get imported later.
        e.printStackTrace();
    }
    model.put("serviceStatus", serviceStatus);

    return "/custodian/datacustodian/showservicestatus";
}

From source file:eu.supersede.dm.rest.CriteriaRest.java

/**
 * Create a new criterion./*from  w  w  w  . j  a  v  a2 s. c  om*/
 * @param vc
 */
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createCriteria(@RequestBody ValutationCriteria vc) {
    vc.setCriteriaId(null);
    DMGame.get().getJpa().criteria.save(vc);
    //        valutationCriterias.save(vc);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(vc.getCriteriaId()).toUri());
    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}

From source file:com.boyuanitsm.fort.web.rest.AccountResource.java

/**
 * POST  /register : register the user.//from ww w. j a  v  a2  s. c  om
 *
 * @param managedUserDTO the managed user DTO
 * @param request the HTTP request
 * @return the ResponseEntity with status 201 (Created) if the user is registred or 400 (Bad Request) if the login or e-mail is already in use
 */
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.TEXT_PLAIN_VALUE })
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO,
        HttpServletRequest request) {

    HttpHeaders textPlainHeaders = new HttpHeaders();
    textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);

    return userRepository.findOneByLogin(managedUserDTO.getLogin().toLowerCase())
            .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findOneByEmail(managedUserDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders,
                            HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(managedUserDTO.getLogin(),
                                managedUserDTO.getPassword(), managedUserDTO.getFirstName(),
                                managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(),
                                managedUserDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort() + // "80"
                        request.getContextPath(); // "/myContextPath" or "" if deployed in root context

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;/*w  ww  . j a v  a2  s.  com*/

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

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

@Test
public void testUnauthenticated() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    ResourceOwnerPasswordResourceDetails app = testAccounts.getDefaultResourceOwnerPasswordResource();
    headers.set("Authorization", testAccounts.getAuthorizationHeader(app.getClientId(), "bogus"));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.getForObject("/clientinfo", Map.class, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    assertEquals("unauthorized", response.getBody().get("error"));

}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.ClientController.java

@RequiresPermissions("clients:create")
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<ClientResource> create(HttpEntity<Client> entity, HttpServletRequest request)
        throws URISyntaxException {
    Client Client = entity.getBody();/*from   w w  w  .java  2s. c  om*/
    clientService.save(Client);
    HttpHeaders headers = new HttpHeaders();
    ClientResource ClientResource = new ClientResourceAssembler().toResource(Client);
    headers.setLocation(entityLinks.linkForSingleResource(Client.class, Client.getId()).toUri());
    ResponseEntity<ClientResource> responseEntity = new ResponseEntity<ClientResource>(ClientResource, headers,
            HttpStatus.CREATED);
    return responseEntity;
}

From source file:$.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);

        // ?//from ww w.j ava2  s.  c o  m
        taskService.saveTask(task);

        // Restful?url, ?id.
        Long 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);
    }