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.opentestsystem.authoring.testauth.rest.PublishingRecordController.java

private HttpHeaders buildResponseHeaders(final int contentLength, final String filename) {
    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.clear();//  w w  w.  j  av a2s  .com
    responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
    responseHeaders.setPragma("public");
    responseHeaders.setCacheControl("no-store, must-revalidate");
    responseHeaders.setExpires(Long.valueOf("-1"));
    responseHeaders.setContentDispositionFormData("inline", filename);
    responseHeaders.setContentLength(contentLength);
    responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes");
    return responseHeaders;
}

From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java

private HttpHeaders buildResponseHeaders(final int contentLength, final String filename) {
    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.clear();//from w w  w. j  a  v a2  s .  com
    responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE,
            com.google.common.net.MediaType.CSV_UTF_8.toString());
    responseHeaders.setPragma("public");
    responseHeaders.setCacheControl("no-store, must-revalidate");
    responseHeaders.setExpires(Long.valueOf("-1"));
    responseHeaders.setContentDispositionFormData("inline", filename);
    responseHeaders.setContentLength(contentLength);
    responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes");
    return responseHeaders;
}

From source file:org.opentestsystem.authoring.testspecbank.rest.TestSpecificationController.java

private static HttpHeaders buildResponseHeaders(final int contentLength, final String filename) {
    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.clear();//w  ww  .  j  av a 2  s .  c o m
    responseHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
    responseHeaders.setPragma("public");
    responseHeaders.setCacheControl("no-store, must-revalidate");
    responseHeaders.setExpires(Long.valueOf("-1"));
    responseHeaders.setContentDispositionFormData("inline", filename);
    responseHeaders.setContentLength(contentLength);
    responseHeaders.add(org.apache.http.HttpHeaders.ACCEPT_RANGES, "bytes");
    return responseHeaders;
}

From source file:org.project.openbaton.nubomedia.paas.core.openshift.AuthenticationManager.java

public String authenticate(String baseURL, String username, String password) throws UnauthorizedException {

    String res = "";

    String authBase = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBase64String(authBase.getBytes());
    logger.debug("Auth header " + authHeader);

    String url = baseURL + suffix;

    HttpHeaders authHeaders = new HttpHeaders();
    authHeaders.add("Authorization", authHeader);
    authHeaders.add("X-CSRF-Token", "1");

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("client_id", "openshift-challenging-client").queryParam("response_type", "token");

    HttpEntity<String> authEntity = new HttpEntity<>(authHeaders);
    ResponseEntity<String> response = null;
    try {//from   w w w.  jav a2s.com
        response = template.exchange(builder.build().encode().toUriString(), HttpMethod.GET, authEntity,
                String.class);
    } catch (ResourceAccessException e) {
        return "PaaS Missing";
    } catch (HttpClientErrorException e) {
        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    logger.debug("Response " + response.toString());

    if (response.getStatusCode().equals(HttpStatus.FOUND)) {

        URI location = response.getHeaders().getLocation();
        logger.debug("Location " + location);
        res = this.getToken(location.toString());

    } else if (response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {

        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    return res;
}

From source file:org.rippleosi.common.service.proxies.C4HReportingRequestProxy.java

private HttpEntity<String> buildRequest(String body) {
    String credentials = openEhrUsername + ":" + openEhrPassword;
    byte[] base64 = Base64.encodeBase64(credentials.getBytes());
    String encoded = new String(base64);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
    headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    return new HttpEntity<>(body, headers);
}

From source file:org.rippleosi.common.service.proxies.DefaultRequestProxy.java

private HttpEntity<String> buildRequestWithoutSession(String body) {

    String credentials = openEhrUsername + ":" + openEhrPassword;
    byte[] base64 = Base64.encodeBase64(credentials.getBytes());
    String encoded = new String(base64);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
    headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    return new HttpEntity<>(body, headers);
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

public void saveRubricEvaluation(String toolId, String associatedItemId, String evaluatedItemId,
        String evaluatedItemOwnerId, String evaluatorId, HashMap<String, String> params) {

    String evaluationUri = null;/*from   www .  j a  v  a  2s . c  o  m*/
    String created = "";
    String owner = "";

    try {

        // Check for an existing evaluation
        Evaluation existingEvaluation = null;
        String rubricEvaluationId = null;

        try {

            TypeReferences.ResourcesType<Resource<Evaluation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Evaluation>>() {
            };

            URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
            Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

            Traverson.TraversalBuilder builder = traverson.follow("evaluations", "search",
                    "by-tool-item-and-associated-item-and-evaluated-item-ids");

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId)));
            builder.withHeaders(headers);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("toolId", toolId);
            parameters.put("itemId", associatedItemId);
            parameters.put("evaluatedItemId", evaluatedItemId);
            parameters.put("evaluatorId", evaluatorId);

            Resources<Resource<Evaluation>> evaluationResources = builder.withTemplateParameters(parameters)
                    .toObject(resourceParameterizedTypeReference);

            // Should only be one matching this search criterion
            if (evaluationResources.getContent().size() > 1) {
                throw new IllegalStateException(
                        String.format("Number of evaluation resources greater than one for request: %s",
                                evaluationResources.getLink(Link.REL_SELF).toString()));
            }
            for (Resource<Evaluation> evaluationResource : evaluationResources) {
                existingEvaluation = evaluationResource.getContent();
                evaluationUri = evaluationResource.getLink(Link.REL_SELF).getHref();
            }

        } catch (Exception ex) {
            log.info(ex.getMessage());
            //no previous evaluation
        }

        // Get the actual association (necessary to get the rubrics association resource for persisting
        // the evaluation)
        Resource<ToolItemRubricAssociation> rubricToolItemAssociationResource = getRubricAssociationResource(
                toolId, associatedItemId).get();

        String criterionJsonData = createCriterionJsonPayload(params, rubricToolItemAssociationResource);

        if (existingEvaluation == null) { // Create a new one

            String input = String.format("{ \"evaluatorId\" : \"%s\",\"evaluatedItemId\" : \"%s\", "
                    + "\"evaluatedItemOwnerId\" : \"%s\"," + "\"overallComment\" : \"%s\", "
                    + "\"toolItemRubricAssociation\" : \"%s\", " + "\"criterionOutcomes\" : [ %s ] " + "}",
                    evaluatorId, evaluatedItemId, evaluatedItemOwnerId, "",
                    rubricToolItemAssociationResource.getLink(Link.REL_SELF).getHref(), criterionJsonData);

            String requestUri = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                    + "evaluations/";
            String resultPost = postRubricResource(requestUri, input, toolId);
            log.debug("resultPost: " + resultPost);

        } else { // Update existing evaluation

            // Resource IDs return as null when using Spring HATEOAS due to https://github.com/spring-projects/spring-hateoas/issues/67
            // so ID is not added and the resource URI is where it is derived from.

            String input = String.format("{ \"evaluatorId\" : \"%s\",\"evaluatedItemId\" : \"%s\", "
                    + "\"evaluatedItemOwnerId\" : \"%s\", \"overallComment\" : \"%s\", \"toolItemRubricAssociation\" : \"%s\", "
                    + "\"criterionOutcomes\" : [ %s ] }", evaluatorId, evaluatedItemId, evaluatedItemOwnerId,
                    "", rubricToolItemAssociationResource.getLink(Link.REL_SELF).getHref(), criterionJsonData);

            String resultPut = putRubricResource(evaluationUri, input, toolId);
            //lets update the actual one.
            log.debug("resultPUT: " + resultPut);
        }

    } catch (Exception e) {
        //TODO If we have an error here, maybe we should return say something to the user
        log.error("Error in SaveRubricEvaluation" + e.getMessage());
    }

}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

private String createCriterionJsonPayload(HashMap<String, String> formPostParameters,
        Resource<ToolItemRubricAssociation> association) throws Exception {

    Map<String, Map<String, String>> criterionDataMap = extractCriterionDataFromParams(formPostParameters);

    String criterionJsonData = "";
    int index = 0;
    boolean pointsAdjusted = false;
    String points = null;/*from ww  w  .  j  av a 2 s .  c o m*/
    String selectedRatingId = null;

    String inlineRubricUri = String.format("%s?%s", association.getLink("rubric").getHref(),
            "projection=inlineRubric");

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization",
            String.format("Bearer %s", generateJsonWebToken(association.getContent().getToolId())));
    HttpEntity<?> requestEntity = new HttpEntity<>(headers);
    ResponseEntity<Rubric> rubricEntity = restTemplate.exchange(inlineRubricUri, HttpMethod.GET, requestEntity,
            Rubric.class);

    Map<String, Criterion> criterions = new HashMap<>();
    for (Criterion criterion : rubricEntity.getBody().getCriterions()) {
        criterions.put(String.valueOf(criterion.getId()), criterion);
    }

    for (Map.Entry<String, Map<String, String>> criterionData : criterionDataMap.entrySet()) {
        if (index > 0) {
            criterionJsonData += ", ";
        }
        index++;

        final String selectedRatingPoints = criterionData.getValue().get("rbcs-criterion");

        if (StringUtils.isNotBlank(criterionData.getValue().get("rbcs-criterion-override"))) {
            pointsAdjusted = true;
            points = criterionData.getValue().get("rbcs-criterion-override");
        } else {
            pointsAdjusted = false;
            points = selectedRatingPoints;
        }

        Criterion criterion = criterions.get(criterionData.getKey());
        Optional<Rating> rating = criterion.getRatings().stream()
                .filter(c -> String.valueOf(c.getPoints()).equals(selectedRatingPoints)).findFirst();

        if (rating.isPresent()) {
            selectedRatingId = String.valueOf(rating.get().getId());
        }

        if (StringUtils.isEmpty(points)) {
            points = "0";
        }

        criterionJsonData += String.format(
                "{ \"criterionId\" : \"%s\", \"points\" : \"%s\", "
                        + "\"comments\" : \"%s\", \"pointsAdjusted\" : %b, \"selectedRatingId\" : \"%s\"  }",
                criterionData.getKey(), points,
                StringEscapeUtils.escapeJson(criterionData.getValue().get("rbcs-criterion-comment")),
                pointsAdjusted, selectedRatingId);
    }

    return criterionJsonData;
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

/**
 * Returns the ToolItemRubricAssociation resource for the given tool and associated item ID, wrapped as an Optional.
 * @param toolId the tool id, something like "sakai.assignment"
 * @param associatedToolItemId the id of the associated element within the tool
 * @return/*w w  w .j a  va  2 s.  co  m*/
 */
protected Optional<Resource<ToolItemRubricAssociation>> getRubricAssociationResource(String toolId,
        String associatedToolItemId) throws Exception {

    TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {
    };

    URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
    Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

    Traverson.TraversalBuilder builder = traverson.follow("rubric-associations", "search", "by-tool-item-ids");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId)));
    builder.withHeaders(headers);

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("toolId", toolId);
    parameters.put("itemId", associatedToolItemId);

    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder
            .withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);

    // Should only be one matching this search criterion
    if (associationResources.getContent().size() > 1) {
        throw new IllegalStateException(
                String.format("Number of rubric association resources greater than one for request: %s",
                        associationResources.getLink(Link.REL_SELF).toString()));
    }

    Optional<Resource<ToolItemRubricAssociation>> associationResource = associationResources.getContent()
            .stream().findFirst();

    return associationResource;
}

From source file:org.sakaiproject.rubrics.logic.RubricsServiceImpl.java

public void saveRubricEvaluation(String toolId, String associatedItemId, String evaluatedItemId,
        String evaluatedItemOwnerId, String evaluatorId, Map<String, String> params) {

    String evaluationUri = null;//w  ww. j  a  v a 2  s.co m
    String created = "";
    String owner = "";

    try {
        // Check for an existing evaluation
        Evaluation existingEvaluation = null;
        String rubricEvaluationId = null;

        try {
            TypeReferences.ResourcesType<Resource<Evaluation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Evaluation>>() {
            };

            URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
            Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);

            Traverson.TraversalBuilder builder = traverson.follow("evaluations", "search",
                    "by-tool-item-and-associated-item-and-evaluated-item-ids");

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId)));
            builder.withHeaders(headers);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("toolId", toolId);
            parameters.put("itemId", associatedItemId);
            parameters.put("evaluatedItemId", evaluatedItemId);
            parameters.put("evaluatorId", evaluatorId);

            Resources<Resource<Evaluation>> evaluationResources = builder.withTemplateParameters(parameters)
                    .toObject(resourceParameterizedTypeReference);

            // Should only be one matching this search criterion
            if (evaluationResources.getContent().size() > 1) {
                throw new IllegalStateException(
                        String.format("Number of evaluation resources greater than one for request: %s",
                                evaluationResources.getLink(Link.REL_SELF).toString()));
            }

            for (Resource<Evaluation> evaluationResource : evaluationResources) {
                existingEvaluation = evaluationResource.getContent();
                evaluationUri = evaluationResource.getLink(Link.REL_SELF).getHref();
            }

        } catch (Exception ex) {
            log.info("Exception on saveRubricEvaluation: " + ex.getMessage());
            //no previous evaluation
        }

        // Get the actual association (necessary to get the rubrics association resource for persisting the evaluation)
        Resource<ToolItemRubricAssociation> rubricToolItemAssociationResource = getRubricAssociationResource(
                toolId, associatedItemId, null).get();

        String criterionJsonData = createCriterionJsonPayload(associatedItemId, evaluatedItemId, params,
                rubricToolItemAssociationResource);

        if (existingEvaluation == null) { // Create a new one

            String input = String.format("{ \"evaluatorId\" : \"%s\",\"evaluatedItemId\" : \"%s\", "
                    + "\"evaluatedItemOwnerId\" : \"%s\"," + "\"overallComment\" : \"%s\", "
                    + "\"toolItemRubricAssociation\" : \"%s\", " + "\"criterionOutcomes\" : [ %s ] " + "}",
                    evaluatorId, evaluatedItemId, evaluatedItemOwnerId, "",
                    rubricToolItemAssociationResource.getLink(Link.REL_SELF).getHref(), criterionJsonData);

            String requestUri = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                    + "evaluations/";
            String resultPost = postRubricResource(requestUri, input, toolId, null);
            log.debug("resultPost: " + resultPost);

        } else { // Update existing evaluation

            // Resource IDs return as null when using Spring HATEOAS due to https://github.com/spring-projects/spring-hateoas/issues/67
            // so ID is not added and the resource URI is where it is derived from.
            String input = String.format("{ \"evaluatorId\" : \"%s\",\"evaluatedItemId\" : \"%s\", "
                    + "\"evaluatedItemOwnerId\" : \"%s\", \"overallComment\" : \"%s\", \"toolItemRubricAssociation\" : \"%s\", \"criterionOutcomes\" : [ %s ], "
                    + "\"metadata\" : {\"created\" : \"%s\", \"ownerId\" : \"%s\", \"ownerType\" : \"%s\", \"creatorId\" : \"%s\"} }",
                    evaluatorId, evaluatedItemId, evaluatedItemOwnerId, existingEvaluation.getOverallComment(),
                    rubricToolItemAssociationResource.getLink(Link.REL_SELF).getHref(), criterionJsonData,
                    existingEvaluation.getMetadata().getCreated(),
                    existingEvaluation.getMetadata().getOwnerId(),
                    existingEvaluation.getMetadata().getOwnerType(),
                    existingEvaluation.getMetadata().getCreatorId());

            String resultPut = putRubricResource(evaluationUri, input, toolId);
            //lets update the actual one.
            log.debug("resultPUT: " + resultPut);
        }

    } catch (Exception e) {
        //TODO If we have an error here, maybe we should return say something to the user
        log.error("Error in SaveRubricEvaluation " + e.getMessage());
    }

}