Example usage for org.springframework.hateoas.client Traverson Traverson

List of usage examples for org.springframework.hateoas.client Traverson Traverson

Introduction

In this page you can find the example usage for org.springframework.hateoas.client Traverson Traverson.

Prototype

public Traverson(URI baseUri, List<MediaType> mediaTypes) 

Source Link

Document

Creates a new Traverson interacting with the given base URI and using the given MediaType s to interact with the service.

Usage

From source file:example.stores.StarbucksClient.java

public static void main(String[] args) {

    Traverson traverson = new Traverson(URI.create("http://localhost:8080"), MediaTypes.HAL_JSON);

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

    PagedResources<Resource<Store>> resources = traverson. //
            follow("stores", "search", "by-location").//
            withTemplateParameters(parameters).//
            toObject(TYPE_REFERENCE);/* w  w w  . j  a  va 2s . com*/

    PageMetadata metadata = resources.getMetadata();

    System.out.println(
            String.format("Got %s of %s stores: ", resources.getContent().size(), metadata.getTotalElements()));

    for (Resource<Store> resource : resources) {

        Store store = resource.getContent();

        System.out.println(String.format("- %s - %s", store.name, store.address));
    }
}

From source file:curly.commons.web.rest.TraversonFactory.java

public Traverson create(String serviceId) {
    ServiceInstance instance = loadBalancerClient.choose(serviceId);
    return new Traverson(instance.getUri(), MediaTypes.HAL_JSON);
}

From source file:io.curly.commons.web.rest.TraversonFactory.java

public Traverson create(String serviceId) {
    ServiceInstance instance = loadBalancerClient.choose(serviceId);
    if (instance != null)
        return new Traverson(instance.getUri(), MediaTypes.HAL_JSON);
    else//from ww  w. j a  va2 s  .  c  om
        throw new IllegalStateException("Instance is null!");
}

From source file:com.greglturnquist.springdatarest.HoppingRightAlong.java

public HoppingRightAlong() throws URISyntaxException {
    traverson = new Traverson(new URI("http://localhost:8080/api/"), MediaTypes.HAL_JSON);
}

From source file:example.customers.integration.StoreIntegration.java

private void discoverByLocationLink() {

    try {/*from  ww w  . j a va 2 s  .  c  o  m*/
        URI storesUri = URI.create(env.getProperty("integration.stores.uri"));
        log.info("Trying to access the stores system at {}", storesUri);

        Traverson traverson = new Traverson(storesUri, MediaTypes.HAL_JSON);
        this.storesByLocationLink = traverson.follow("stores", "search", "by-location").asLink();

        log.info("Found stores-by-location link pointing to {}.", storesByLocationLink.getHref());

    } catch (RuntimeException o_O) {
        this.storesByLocationLink = null;
        log.info("Stores system unavailable. Got: ", o_O.getMessage());
    }
}

From source file:example.springdata.rest.stores.StarbucksClient.java

@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");

    PagedResources<Resource<Store>> resources = builder.//
            withTemplateParameters(parameters).//
            toObject(new PagedResourcesType<Resource<Store>>() {
            });/* w ww  .  j  a va2 s.com*/

    PageMetadata metadata = resources.getMetadata();

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

    StreamSupport.stream(resources.spliterator(), false).//
            map(Resource::getContent).//
            forEach(store -> log.info("{} - {}", store.name, store.address));
}

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;// ww w . j  a  v a 2 s. c  om
    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

/**
 * 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//  ww  w .j av  a  2s .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;/*from w  w  w.jav 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("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());
    }

}

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//from  w  ww . j a va2 s .c  o  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;
}