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.sakaiproject.rubrics.logic.RubricsServiceImpl.java

private String createCriterionJsonPayload(String associatedItemId, String evaluatedItemId,
        Map<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   w  ww .j  a  v  a  2  s. c  om
    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(RubricsConstants.RBCS_PREFIX + evaluatedItemId + "-" + associatedItemId + "-criterion");

        if (StringUtils.isNotBlank(criterionData.getValue().get(RubricsConstants.RBCS_PREFIX + evaluatedItemId
                + "-" + associatedItemId + "-criterion-override"))) {
            pointsAdjusted = true;
            points = criterionData.getValue().get(RubricsConstants.RBCS_PREFIX + evaluatedItemId + "-"
                    + associatedItemId + "-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(RubricsConstants.RBCS_PREFIX + evaluatedItemId + "-"
                                                + associatedItemId + "-criterion-comment")),
                        pointsAdjusted, selectedRatingId);
    }

    return criterionJsonData;
}

From source file:org.sakaiproject.rubrics.logic.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 v a  2 s.co m
 */
protected Optional<Resource<ToolItemRubricAssociation>> getRubricAssociationResource(String toolId,
        String associatedToolItemId, String siteId) 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();
    if (siteId != null) {
        headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId)));
    } else {
        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 String getRubricEvaluationObjectId(String associationId, String userId, String toolId) {
    try {//from   w  w w. java  2 s  .  c o m
        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-association-and-user");

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

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("associationId", associationId);
        parameters.put("userId", userId);

        String response = builder.withTemplateParameters(parameters).toObject(String.class);
        if (StringUtils.isNotEmpty(response)) {
            return response.replace("\"", "");
        }
    } catch (Exception e) {
        log.warn("Error {} while getting a rubric evaluation in assignment {} for user {}", e.getMessage(),
                associationId, userId);
    }
    return null;
}

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

/**
 * Delete all the rubric associations starting with itemId.
 * @param itemId The formatted item id.//from   w ww  . jav  a2s  .co  m
 */
public void deleteRubricAssociationsByItemIdPrefix(String itemId, String toolId) {
    try {
        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-item-id-prefix");

        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", itemId);

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

        for (Resource<ToolItemRubricAssociation> associationResource : associationResources) {
            String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
            deleteRubricEvaluationsForAssociation(associationHref, toolId);
            deleteRubricResource(associationHref, toolId, null);
            hasAssociatedRubricCache.remove(toolId + "#" + itemId);
        }
    } catch (Exception e) {
        log.warn("Error deleting rubric association for id {} : {}", itemId, e.getMessage());
    }
}

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

protected Collection<Resource<Evaluation>> getRubricEvaluationsByAssociation(Long associationId)
        throws Exception {
    TypeReferences.ResourcesType<Resource<Evaluation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Evaluation>>() {
    };//from ww w .  j a  va  2  s . c o  m

    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-association-id");

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

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("toolItemRubricAssociationId", associationId);
    Resources<Resource<Evaluation>> evaluationResources = builder.withTemplateParameters(parameters)
            .toObject(resourceParameterizedTypeReference);

    return evaluationResources.getContent();
}

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

@Override
public Map<String, String> transferCopyEntities(String fromContext, String toContext, List<String> ids,
        List<String> options) {

    Map<String, String> transversalMap = new HashMap<>();
    try {/*w w w .  j a va 2 s.  c om*/
        TypeReferences.ResourcesType<Resource<Rubric>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Rubric>>() {
        };
        URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
        Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
        Traverson.TraversalBuilder builder = traverson.follow("rubrics", "search", "rubrics-from-site");

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

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("siteId", fromContext);

        Resources<Resource<Rubric>> rubricResources = builder.withTemplateParameters(parameters)
                .toObject(resourceParameterizedTypeReference);
        for (Resource<Rubric> rubricResource : rubricResources) {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers2 = new HttpHeaders();
            headers2.setContentType(MediaType.APPLICATION_JSON);
            headers2.add("Authorization",
                    String.format("Bearer %s", generateJsonWebToken(RubricsConstants.RBCS_TOOL, toContext)));
            HttpEntity<?> requestEntity = new HttpEntity<>(headers2);
            ResponseEntity<Rubric> rubricEntity = restTemplate.exchange(
                    rubricResource.getLink(Link.REL_SELF).getHref() + "?projection=inlineRubric",
                    HttpMethod.GET, requestEntity, Rubric.class);
            Rubric rEntity = rubricEntity.getBody();
            String newId = cloneRubricToSite(String.valueOf(rEntity.getId()), toContext);
            String oldId = String.valueOf(rEntity.getId());
            transversalMap.put(RubricsConstants.RBCS_PREFIX + oldId, RubricsConstants.RBCS_PREFIX + newId);
        }
    } catch (Exception ex) {
        log.info("Exception on duplicateRubricsFromSite: " + ex.getMessage());
    }
    return transversalMap;
}

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

@Override
public Map<String, String> transferCopyEntities(String fromContext, String toContext, List<String> ids,
        List<String> options, boolean cleanup) {

    if (cleanup) {
        try {/*from www.  java  2 s .  c  o  m*/
            TypeReferences.ResourcesType<Resource<Rubric>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<Rubric>>() {
            };
            URI apiBaseUrl = new URI(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX);
            Traverson traverson = new Traverson(apiBaseUrl, MediaTypes.HAL_JSON);
            Traverson.TraversalBuilder builder = traverson.follow("rubrics", "search", "rubrics-from-site");

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

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("siteId", toContext);
            Resources<Resource<Rubric>> rubricResources = builder.withTemplateParameters(parameters)
                    .toObject(resourceParameterizedTypeReference);
            for (Resource<Rubric> rubricResource : rubricResources) {
                String[] rubricSplitted = rubricResource.getLink(Link.REL_SELF).getHref().split("/");
                Collection<Resource<ToolItemRubricAssociation>> assocs = getRubricAssociationByRubric(
                        rubricSplitted[rubricSplitted.length - 1], toContext);
                for (Resource<ToolItemRubricAssociation> associationResource : assocs) {
                    String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
                    deleteRubricResource(associationHref, RubricsConstants.RBCS_TOOL, toContext);
                }
                deleteRubricResource(rubricResource.getLink(Link.REL_SELF).getHref(),
                        RubricsConstants.RBCS_TOOL, toContext);
            }
        } catch (Exception e) {
            log.error("Rubrics - transferCopyEntities: error trying to delete rubric -> {}", e.getMessage());
        }
    }
    return transferCopyEntities(fromContext, toContext, ids, null);
}

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

private String cloneRubricToSite(String rubricId, String toSite) {
    try {//  www. j ava 2s.  c  o m
        String url = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX + "rubrics/clone";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization",
                String.format("Bearer %s", generateJsonWebToken(RubricsConstants.RBCS_TOOL, toSite)));
        headers.add("x-copy-source", rubricId);
        headers.add("site", toSite);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
        HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<Rubric> rubricEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                Rubric.class);
        Rubric rub = rubricEntity.getBody();
        return String.valueOf(rub.getId());
    } catch (Exception e) {
        log.error("Exception when cloning rubric {} to site {} : {}", rubricId, toSite, e.getMessage());
    }
    return null;
}

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

protected Collection<Resource<ToolItemRubricAssociation>> getRubricAssociationByRubric(String rubricId,
        String toSite) throws Exception {
    TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resource<ToolItemRubricAssociation>>() {
    };/*ww w  . j  a va2 s.c o m*/

    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-rubric-id");

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

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("rubricId", Long.valueOf(rubricId));
    Resources<Resource<ToolItemRubricAssociation>> associationResources = builder
            .withTemplateParameters(parameters).toObject(resourceParameterizedTypeReference);

    return associationResources.getContent();
}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Assign this payload to the given {@link HttpOutputMessage}.
 * @param message the message to assign this payload to
 * @throws IOException in case of I/O errors
 *///from  www . ja va2  s  .  com
public void assignTo(HttpOutputMessage message) throws IOException {
    Assert.notNull(message, "Message must not be null");
    HttpHeaders headers = message.getHeaders();
    headers.setContentLength(this.data.remaining());
    headers.add(SEQ_HEADER, Long.toString(getSequence()));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    WritableByteChannel body = Channels.newChannel(message.getBody());
    while (this.data.hasRemaining()) {
        body.write(this.data);
    }
    body.close();
}