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:fi.helsinki.opintoni.service.usefullink.UsefulLinkService.java

public SearchPageTitleDto searchPageTitle(SearchPageTitleDto searchPageTitleDto) throws NotFoundException {
    try {//  ww  w .  j  a  va  2  s  .co  m
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Lists.newArrayList(MediaType.TEXT_HTML));
        headers.add("User-Agent", "Mozilla");
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

        ResponseEntity<String> responseEntity = linkUrlLoaderRestTemplate.exchange(searchPageTitleDto.searchUrl,
                HttpMethod.GET, entity, String.class);
        if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            Document document = Jsoup.parse(responseEntity.getBody());
            searchPageTitleDto.searchResult = document.title();
        }
    } catch (Exception e) {
    }
    return searchPageTitleDto;
}

From source file:de.fhg.fokus.nubomedia.paas.VNFRServiceImpl.java

/**
 * Registers a new App to the VNFR with a specific VNFR ID
 *    /*from   w  w  w.j  a v a  2 s. c o m*/
 * @param externalAppId - application identifier
 * @param points - capacity
 */
public ApplicationRecord registerApplication(String externalAppId, int points)
        throws NotEnoughResourcesException {
    try {
        if (serviceProfile == null) {
            logger.info("Service Profile not set. make sure the VNFR_ID, VNFM_IP and VNFM_PORT are available ");
            return null;
        }
        String URL = serviceProfile.getServiceApiUrl();
        ApplicationRecordBody bodyObj = new ApplicationRecordBody(externalAppId, points);
        Gson mapper = new GsonBuilder().create();
        String body = mapper.toJson(bodyObj, ApplicationRecordBody.class);

        logger.info("registering new application: \nURL: " + URL + "\n + " + body);
        HttpHeaders creationHeader = new HttpHeaders();
        creationHeader.add("Accept", "application/json");
        creationHeader.add("Content-type", "application/json");

        HttpEntity<String> registerEntity = new HttpEntity<String>(body, creationHeader);
        ResponseEntity response = restTemplate.exchange(URL, HttpMethod.POST, registerEntity, String.class);

        logger.info("response from VNFM " + response);
        HttpStatus status = response.getStatusCode();
        if (status.equals(HttpStatus.CREATED) || status.equals(HttpStatus.OK)) {
            logger.info("Deployment status: " + status + " response: " + response);
            ApplicationRecord responseBody = mapper.fromJson((String) response.getBody(),
                    ApplicationRecord.class);

            logger.info("returned object " + responseBody.toString());
            return responseBody;
        } else if (status.equals(HttpStatus.UNPROCESSABLE_ENTITY)) {

            throw new NotEnoughResourcesException("Not enough resource " + response.getBody());
        }
    } catch (NotEnoughResourcesException e) {
        logger.error(e.getMessage());
    } catch (RestClientException e) {
        logger.error("Error registering application to VNFR - " + e.getMessage());
    }
    return null;
}

From source file:eu.freme.broker.eservices.BaseRestController.java

/**
 * Create a ResponseEntity for a REST API method. It accepts a Jena Model
 * and an RDFSerialization format. It converts the model to a string in the
 * desired serialization format and sets the right Content-Type header.
 * /*from   w  w  w.  ja  va 2s  .co  m*/
 * @param rdf
 * @param rdfFormat
 * @return
 */
public ResponseEntity<String> createSuccessResponse(Model rdf, RDFConstants.RDFSerialization rdfFormat) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", rdfFormat.contentType());
    String rdfString;
    try {
        rdfString = serializeNif(rdf, rdfFormat);
    } catch (Exception e) {
        throw new InternalServerErrorException();
    }
    return new ResponseEntity<>(rdfString, responseHeaders, HttpStatus.OK);
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

private static void loginAndSaveJsessionIdCookie(final String user, final String password,
        final HttpHeaders headersToUpdate) {

    String url = "http://localhost:" + port + "/";

    new RestTemplate().execute(url, HttpMethod.POST,

            new RequestCallback() {
                @Override//w ww . j av a  2 s  . co  m
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
                    map.add("username", user);
                    map.add("password", password);
                    new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
                }
            },

            new ResponseExtractor<Object>() {
                @Override
                public Object extractData(ClientHttpResponse response) throws IOException {
                    headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
                    return null;
                }
            });
}

From source file:uk.ac.ebi.emma.controller.AlleleManagementListController.java

/**
 * Deletes the allele identified by <b>id</b>. This method is configured as
 * a GET because it is intended to be called as an ajax call. Using GET
 * avoids re-posting problems with the back button. NOTE: It is the caller's
 * responsibility to insure there are no foreign key constraints.
 * //from  w ww  .  j  a  va 2 s.com
 * @param allele_key primary key of the allele to be deleted
 * @return a JSON string containing 'status' [ok or fail], and a message [
 * empty string if status is ok; error message otherwise]
 */
@RequestMapping(value = "/deleteAllele", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> deleteAllele(
        @RequestParam(value = "allele_key", required = true) int allele_key) {
    String status, message;

    try {
        allelesManager.delete(allele_key);
        status = "ok";
        message = "";
    } catch (Exception e) {
        status = "fail";
        message = e.getLocalizedMessage();
    }

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

    return new ResponseEntity(returnStatus.toJSONString(), headers, HttpStatus.OK);
}

From source file:org.cloudfoundry.identity.uaa.login.feature.InvitationsIT.java

private String generateCode() {
    String token = testClient.getOAuthAccessToken("login", "loginsecret", "client_credentials",
            "password.write,scim.write");
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + token);
    RestTemplate uaaTemplate = new RestTemplate();

    String userEmail = "user" + new SecureRandom().nextInt() + "@example.com";
    ScimUser scimUser = new ScimUser();
    scimUser.setUserName(userEmail);//from   w ww .  j  a  va2  s  .c  o  m
    ScimUser.Email email = new ScimUser.Email();
    email.setPrimary(true);
    email.setValue(userEmail);
    scimUser.setEmails(Arrays.asList(email));
    scimUser.setOrigin(Origin.UAA);

    HttpEntity<ScimUser> request = new HttpEntity<>(scimUser, headers);
    ResponseEntity<ScimUser> response = uaaTemplate.exchange(uaaUrl + "/Users", HttpMethod.POST, request,
            ScimUser.class);

    Timestamp expiry = new Timestamp(System.currentTimeMillis()
            + TimeUnit.MILLISECONDS.convert(System.currentTimeMillis() + 24 * 3600, TimeUnit.MILLISECONDS));
    ExpiringCode expiringCode = new ExpiringCode(null, expiry, "{\"client_id\":\"app\", \"user_id\":\""
            + response.getBody().getId() + "\", \"email\":\"user@example.com\"}");
    HttpEntity<ExpiringCode> expiringCodeRequest = new HttpEntity<>(expiringCode, headers);
    ResponseEntity<ExpiringCode> expiringCodeResponse = uaaTemplate.exchange(uaaUrl + "/Codes", HttpMethod.POST,
            expiringCodeRequest, ExpiringCode.class);
    expiringCode = expiringCodeResponse.getBody();
    return expiringCode.getCode();
}

From source file:uk.ac.ebi.emma.controller.MutationManagementListController.java

/**
 * Deletes the mutations identified by <b>id</b>. This method is configured as
 * a GET because it is intended to be called as an ajax call. Using GET
 * avoids re-posting problems with the back button. NOTE: It is the caller's
 * responsibility to insure there are no foreign key constraints.
 * //from w ww  .  j  a  va2  s.  com
 * @param mutation_key primary key of the mutation to be deleted
 * @return a JSON string containing 'status' [ok or fail], and a message [
 * empty string if status is ok; error message otherwise]
 */
@RequestMapping(value = "/deleteMutation", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> deleteMutation(@RequestParam int mutation_key) {
    String status, message;

    try {
        mutationsManager.delete(mutation_key);
        status = "ok";
        message = "";
    } catch (Exception e) {
        status = "fail";
        message = e.getLocalizedMessage();
    }

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

    return new ResponseEntity(returnStatus.toJSONString(), headers, HttpStatus.OK);
}

From source file:uk.ac.ebi.emma.controller.GeneManagementListController.java

/**
 * Deletes the gene identified by <b>id</b>. This method is configured as
 * a GET because it is intended to be called as an ajax call. Using GET
 * avoids re-posting problems with the back button. NOTE: It is the caller's
 * responsibility to insure there are no foreign key constraints.
 * /*from ww w .  j  a va  2 s. com*/
 * @param gene_key primary key of the gene to be deleted
 * @return a JSON string containing 'status' [ok or fail], and a message [
 * empty string if status is ok; error message otherwise]
 */
@RequestMapping(value = "/deleteGene", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> deleteGene(@RequestParam int gene_key) {
    String status, message;

    try {
        genesManager.delete(gene_key);
        status = "ok";
        message = "";
    } catch (Exception e) {
        status = "fail";
        message = e.getLocalizedMessage();
    }

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

    return new ResponseEntity(returnStatus.toJSONString(), headers, HttpStatus.OK);
}

From source file:com.basicservice.controller.UserController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> login(HttpServletRequest request,
        @RequestParam(value = "email") EmailValidatedString email,
        @RequestParam(value = "password") String password) {
    if (email == null || email.getValue() == null || password == null) {
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    }/*w  w w . ja  v  a 2  s.  com*/
    User user = userService.login(email.getValue(), password);
    LOG.debug("Got login request: email:" + email.getValue() + ", pass:" + password);

    if (user == null) {
        try {
            new AppSensorException("AF1", "Authentication Failure", "Authentication Failure detected");
        } catch (Exception e) {
            // AppSensor might throw an exception, but we want to catch it here and stop propagation
        }
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    } else if (!user.isEmailConfirmed()) {
        // let the user know that she can't login until she confirms the email
        return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
    }

    user.setLastLogin(new Date());

    LOG.debug("Preparing to save user to db");
    userService.save(user);
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Set-Cookie", Constants.AUTHENTICATED_USER_ID_COOKIE + "=" + user.getSessionId() + "; Path=/");
    return new ResponseEntity<String>(headers, HttpStatus.OK);
}