org.springframework.hateoas.client.Traverson Java Examples

The following examples show how to use org.springframework.hateoas.client.Traverson. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getRubricEvaluationObjectId(String associationId, String userId, String toolId) {
    try {
        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;
}
 
Example #2
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<ToolItemRubricAssociation>> getRubricAssociationByRubric(String rubricId, String toSite) 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-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();
}
 
Example #3
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<Evaluation>> getRubricEvaluationsByAssociation(Long associationId) throws Exception {
    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-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();
}
 
Example #4
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getRubricEvaluationObjectId(String associationId, String userId, String toolId) {
    try {
        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;
}
 
Example #5
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<Evaluation>> getRubricEvaluationsByAssociation(Long associationId) throws Exception {
    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-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();
}
 
Example #6
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public Map<String, String> transferCopyEntities(String fromContext, String toContext, List<String> ids, List<String> options) {

    Map<String, String> transversalMap = new HashMap<>();
    try {
        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;
}
 
Example #7
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Collection<Resource<ToolItemRubricAssociation>> getRubricAssociationByRubric(String rubricId, String toSite) 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-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();
}
 
Example #8
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void restoreRubricAssociationsByItemIdPrefix(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();
            ToolItemRubricAssociation association = associationResource.getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, false);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Restoring association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error restoring rubric association for id {} : {}", itemId, e.getMessage());
    }
}
 
Example #9
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void softDeleteRubricAssociationsByItemIdPrefix(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();
            ToolItemRubricAssociation association = associationResource.getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, true);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Soft delete association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error soft deleting rubric association for item id prefix {} : {}", itemId, e.getMessage());
    }
}
 
Example #10
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Delete all the rubric associations starting with itemId.
 * @param itemId The formatted item id.
 */
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());
    }
}
 
Example #11
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public Map<String, String> transferCopyEntities(String fromContext, String toContext, List<String> ids, List<String> options) {

    Map<String, String> transversalMap = new HashMap<>();
    try {
        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;
}
 
Example #12
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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
 */
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();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId)));
    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;
}
 
Example #13
Source File: DiscoveredResourceUnitTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void verificationTriggersDiscovery() {

	Link link = new Link("target", "rel");

	when(this.provider.getServiceInstance()).thenReturn(new DefaultServiceInstance(
			"instance", "service", "localhost", 8080, false));
	when(this.builder.asTemplatedLink()).thenReturn(link);

	this.resource.verifyOrDiscover();

	then(this.resource.getLink()).isEqualTo(link);
	verify(this.provider, times(1)).getServiceInstance();
	verify(this.traversal, times(1)).buildTraversal(Matchers.any(Traverson.class));
}
 
Example #14
Source File: DiscoveredResourceUnitTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	when(this.traversal.buildTraversal(Matchers.any(Traverson.class)))
			.thenReturn(this.builder);

	this.resource = new DiscoveredResource(this.provider, this.traversal);
	this.resource.setRestOperations(this.operations);
}
 
Example #15
Source File: StarbucksClient.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void discoverStoreSearch() {

	Traverson traverson = new Traverson(URI.create(String.format(SERVICE_URI, port)), MediaTypes.HAL_JSON);

	// Set up path traversal
	TraversalBuilder builder = traverson. //
			follow("stores", "search", "by-location");

	// Log discovered
	log.info("");
	log.info("Discovered link: {}", builder.asTemplatedLink());
	log.info("");

	Map<String, Object> parameters = new HashMap<>();
	parameters.put("location", "40.740337,-73.995146");
	parameters.put("distance", "0.5miles");

	PagedModel<EntityModel<Store>> resources = builder.//
			withTemplateParameters(parameters).//
			toObject(new PagedModelType<EntityModel<Store>>() {});

	PageMetadata metadata = resources.getMetadata();

	log.info("Got {} of {} stores: ", resources.getContent().size(), metadata.getTotalElements());

	StreamSupport.stream(resources.spliterator(), false).//
			map(EntityModel::getContent).//
			forEach(store -> log.info("{} - {}", store.name, store.address));
}
 
Example #16
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void deleteSiteRubrics(String siteId) {
    try {
        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, siteId)));
        builder.withHeaders(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("siteId", siteId);
        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],siteId);
            for(Resource<ToolItemRubricAssociation> associationResource : assocs){
                String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
                deleteRubricResource(associationHref, RubricsConstants.RBCS_TOOL, siteId);
            }
            deleteRubricResource(rubricResource.getLink(Link.REL_SELF).getHref(), RubricsConstants.RBCS_TOOL, siteId);
        }
    } catch(Exception e){
        log.error("Rubrics: error trying to delete rubric -> {}" , e.getMessage());
    }
}
 
Example #17
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void deleteSiteRubrics(String siteId) {
    try {
        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, siteId)));
        builder.withHeaders(headers);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("siteId", siteId);
        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],siteId);
            for(Resource<ToolItemRubricAssociation> associationResource : assocs){
                String associationHref = associationResource.getLink(Link.REL_SELF).getHref();
                deleteRubricResource(associationHref, RubricsConstants.RBCS_TOOL, siteId);
            }
            deleteRubricResource(rubricResource.getLink(Link.REL_SELF).getHref(), RubricsConstants.RBCS_TOOL, siteId);
        }
    } catch(Exception e){
        log.error("Rubrics: error trying to delete rubric -> {}" , e.getMessage());
    }
}
 
Example #18
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void restoreRubricAssociationsByItemIdPrefix(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();
            ToolItemRubricAssociation association = associationResource.getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, false);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Restoring association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error restoring rubric association for id {} : {}", itemId, e.getMessage());
    }
}
 
Example #19
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void softDeleteRubricAssociationsByItemIdPrefix(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();
            ToolItemRubricAssociation association = associationResource.getContent();
            String created = association.getMetadata().getCreated().toString();
            String owner = association.getMetadata().getOwnerId();
            String ownerType = association.getMetadata().getOwnerType();
            String creatorId = association.getMetadata().getCreatorId();
            Map <String,Boolean> oldParams = association.getParameters();
            oldParams.put(RubricsConstants.RBCS_SOFT_DELETED, true);
            String input = "{\"toolId\" : \""+toolId+"\",\"itemId\" : \"" + association.getItemId() + "\",\"rubricId\" : " + association.getRubricId() + ",\"metadata\" : {\"created\" : \"" + created + "\",\"ownerId\" : \"" + owner +
            "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId + "\"},\"parameters\" : {" + setConfigurationParametersForDuplication(oldParams) + "}}";
            log.debug("Soft delete association {}", input);
            String resultPut = putRubricResource(associationHref, input, toolId, null);
            log.debug("resultPUT: {}",  resultPut);
        }
    } catch (Exception e) {
        log.warn("Error soft deleting rubric association for item id prefix {} : {}", itemId, e.getMessage());
    }
}
 
Example #20
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Delete all the rubric associations starting with itemId.
 * @param itemId The formatted item id.
 */
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());
    }
}
 
Example #21
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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
 */
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();
    headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(toolId, siteId)));
    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;
}
 
Example #22
Source File: TraversonFactory.java    From myfeed with Apache License 2.0 5 votes vote down vote up
public Traverson create(String serviceId) {
	ServiceInstance instance = loadBalancerClient.choose(serviceId);
	if (instance == null) {
		throw new IllegalStateException("No instances for service: "+serviceId);
	}
	return new Traverson(instance.getUri(), MediaTypes.HAL_JSON);
}
 
Example #23
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Instead of putting the creation link from the remote service in the template (a security concern), have a local
 * route for {@literal POST} requests. Gather up the information, and form a remote call, using {@link Traverson} to
 * fetch the {@literal employees} {@link Link}. Once a new employee is created, redirect back to the root URL.
 *
 * @param employee
 * @return
 * @throws URISyntaxException
 */
@PostMapping("/employees")
public String newEmployee(@ModelAttribute Employee employee) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	Link employeesLink = client.follow("employees").asLink();

	this.rest.postForEntity(employeesLink.expand().getHref(), employee, Employee.class);

	return "redirect:/";
}
 
Example #24
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the
 * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry
 * with the Thymeleaf template.
 *
 * @param model
 * @return
 * @throws URISyntaxException
 */
@GetMapping
public String index(Model model) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);

	CollectionModel<EntityModel<Employee>> employees = client //
			.follow("employees") //
			.toObject(new CollectionModelType<EntityModel<Employee>>() {});

	model.addAttribute("employee", new Employee());
	model.addAttribute("employees", employees);

	return "index";
}
 
Example #25
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Instead of putting the creation link from the remote service in the template (a security concern), have a local
 * route for {@literal POST} requests. Gather up the information, and form a remote call, using {@link Traverson} to
 * fetch the {@literal employees} {@link Link}. Once a new employee is created, redirect back to the root URL.
 *
 * @param employee
 * @return
 * @throws URISyntaxException
 */
@PostMapping("/employees")
public String newEmployee(@ModelAttribute Employee employee) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	Link employeesLink = client //
			.follow("employees") //
			.asLink();

	this.rest.postForEntity(employeesLink.expand().getHref(), employee, Employee.class);

	return "redirect:/";
}
 
Example #26
Source File: HomeController.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Get a listing of ALL {@link Employee}s by querying the remote services' root URI, and then "hopping" to the
 * {@literal employees} rel. NOTE: Also create a form-backed {@link Employee} object to allow creating a new entry
 * with the Thymeleaf template.
 *
 * @param model
 * @return
 * @throws URISyntaxException
 */
@GetMapping
public String index(Model model) throws URISyntaxException {

	Traverson client = new Traverson(new URI(REMOTE_SERVICE_ROOT_URI), MediaTypes.HAL_JSON);
	CollectionModel<EntityModel<Employee>> employees = client //
			.follow("employees") //
			.toObject(new CollectionModelType<EntityModel<Employee>>() {});

	model.addAttribute("employee", new Employee());
	model.addAttribute("employees", employees);

	return "index";
}
 
Example #27
Source File: TacoCloudClient.java    From spring-in-action-5-samples with Apache License 2.0 4 votes vote down vote up
public TacoCloudClient(RestTemplate rest, Traverson traverson) {
  this.rest = rest;
  this.traverson = traverson;
}
 
Example #28
Source File: TacoCloudClient.java    From spring-in-action-5-samples with Apache License 2.0 4 votes vote down vote up
public TacoCloudClient(RestTemplate rest, Traverson traverson) {
  this.rest = rest;
  this.traverson = traverson;
}
 
Example #29
Source File: TacoCloudClient.java    From spring-in-action-5-samples with Apache License 2.0 4 votes vote down vote up
public TacoCloudClient(RestTemplate rest, Traverson traverson) {
  this.rest = rest;
  this.traverson = traverson;
}
 
Example #30
Source File: TacoCloudClient.java    From spring-in-action-5-samples with Apache License 2.0 4 votes vote down vote up
public TacoCloudClient(RestTemplate rest, Traverson traverson) {
  this.rest = rest;
  this.traverson = traverson;
}