Example usage for org.springframework.hateoas Link isTemplated

List of usage examples for org.springframework.hateoas Link isTemplated

Introduction

In this page you can find the example usage for org.springframework.hateoas Link isTemplated.

Prototype

public boolean isTemplated() 

Source Link

Document

Returns whether or not the link is templated.

Usage

From source file:nu.yona.server.subscriptions.rest.BuddyController.java

private String stripTemplateParameters(Link link) {
    String linkString = link.getHref();
    if (link.isTemplated()) {
        return linkString.substring(0, linkString.indexOf('{'));
    }// w w  w .  j  a  v  a 2s  .co  m
    return linkString;
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

@Override
public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    try {//from   w ww  .j a v  a 2  s . c o  m
        Collection<Link> simpleLinks = new ArrayList<Link>();
        Collection<Affordance> affordances = new ArrayList<Affordance>();
        Collection<Link> templatedLinks = new ArrayList<Link>();
        Collection<Affordance> collectionAffordances = new ArrayList<Affordance>();
        Link selfRel = null;
        for (Link link : links) {
            if (link instanceof Affordance) {
                final Affordance affordance = (Affordance) link;
                final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    // TODO: consider to use Link href for template even if it is not compatible
                    if (affordance.getUriTemplateComponents().hasVariables()) {
                        // TODO resolve rel against context
                        if ("hydra:search".equals(affordance.getRel())
                                || Cardinality.SINGLE == affordance.getCardinality()) {
                            templatedLinks.add(affordance);
                        } else {
                            collectionAffordances.add(affordance);
                        }
                    } else {
                        // if all required variables are satisfied, the url can be used as identifier
                        // by stripping optional variables
                        if (!affordance.isSelfRel() && Cardinality.COLLECTION == affordance.getCardinality()) {
                            collectionAffordances.add(affordance);
                        } else {
                            affordances.add(affordance);
                        }
                    }
                } else {
                    if (affordance.isTemplated()) {
                        templatedLinks.add(affordance);
                    } else {
                        simpleLinks.add(affordance);
                    }
                }
            } else if (link.isTemplated()) {
                templatedLinks.add(link);
            } else {
                simpleLinks.add(link);
            }
            if ("self".equals(link.getRel())) {
                selfRel = link;
            }
        }

        for (Link templatedLink : templatedLinks) {
            // templated affordance might turn out to have all variables satisfied or
            // only optional unsatisfied variables
            ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(templatedLink);
            // TODO handle rev here
            String rel = templatedLink.getRel();
            writeIriTemplate(rel, templatedLink.getHref(), templatedLink.getVariableNames(),
                    actionDescriptorForHttpGet, jgen);
        }
        @SuppressWarnings("unchecked")
        Deque<LdContext> contextStack = (Deque<LdContext>) serializerProvider
                .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
        String currentVocab = (contextStack != null && !contextStack.isEmpty()) ? contextStack.peek().vocab
                : null;

        // related collections
        if (!collectionAffordances.isEmpty()) {

            jgen.writeArrayFieldStart("hydra:collection");

            for (Affordance collectionAffordance : collectionAffordances) {
                jgen.writeStartObject();
                jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection");
                PartialUriTemplateComponents templateComponents = collectionAffordance
                        .getUriTemplateComponents();
                if (!collectionAffordance.isBaseUriTemplated()
                        && !collectionAffordance.hasUnsatisfiedRequiredVariables()) {
                    String collectionUri = templateComponents.getBaseUri() + templateComponents.getQueryHead();
                    jgen.writeStringField(JsonLdKeywords.AT_ID, collectionUri);
                }
                if (templateComponents.hasVariables()) {
                    ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(
                            collectionAffordance);
                    writeIriTemplate("hydra:search", templateComponents.toString(),
                            templateComponents.getVariableNames(), actionDescriptorForHttpGet, jgen);
                }
                jgen.writeObjectFieldStart("hydra:manages");
                // do we have a collection holder which is not owner of the affordance?
                TypedResource collectionHolder = collectionAffordance.getCollectionHolder();
                if (collectionAffordance.getRev() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRev());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:object", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:object", selfRel.getHref());
                    }
                } else if (collectionAffordance.getRel() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRel());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:subject", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:subject", selfRel.getHref());
                    }
                }
                jgen.writeEndObject(); // end manages

                List<ActionDescriptor> actionDescriptors = collectionAffordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeArrayFieldStart("hydra:operation");
                }
                writeActionDescriptors(jgen, currentVocab, actionDescriptors);
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeEndArray(); // end hydra:operation
                }

                jgen.writeEndObject(); // end collection
            }
            jgen.writeEndArray();
        }

        for (Affordance affordance : affordances) {
            final String rel = affordance.getRel();
            List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();

            if (!actionDescriptors.isEmpty()) {
                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeObjectFieldStart(rel); // begin rel
                }
                jgen.writeStringField(JsonLdKeywords.AT_ID, affordance.getHref());
                jgen.writeArrayFieldStart("hydra:operation");
            }

            writeActionDescriptors(jgen, currentVocab, actionDescriptors);

            if (!actionDescriptors.isEmpty()) {
                jgen.writeEndArray(); // end hydra:operation

                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeEndObject(); // end rel
                }
            }
        }

        for (Link simpleLink : simpleLinks) {
            final String rel = simpleLink.getRel();
            if (Link.REL_SELF.equals(rel)) {
                jgen.writeStringField("@id", simpleLink.getHref());
            } else {
                String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
                jgen.writeObjectFieldStart(linkAttributeName);
                jgen.writeStringField("@id", simpleLink.getHref());
                jgen.writeEndObject();
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

@Override
public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    try {/*from  w ww  .  java2  s .  c o m*/
        Collection<Link> simpleLinks = new ArrayList<Link>();
        Collection<Affordance> affordances = new ArrayList<Affordance>();
        Collection<Link> templatedLinks = new ArrayList<Link>();
        Collection<Affordance> templatedAffordances = new ArrayList<Affordance>();
        for (Link link : links) {
            if (link instanceof Affordance) {
                final Affordance affordance = (Affordance) link;
                final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    if (affordance.isTemplated()) {
                        templatedAffordances.add(affordance);
                    } else {
                        affordances.add(affordance);
                    }
                } else {
                    if (affordance.isTemplated()) {
                        templatedLinks.add(affordance);
                    } else {
                        simpleLinks.add(affordance);
                    }
                }
            } else if (link.isTemplated()) {
                templatedLinks.add(link);
            } else {
                simpleLinks.add(link);
            }
        }

        for (Affordance templatedAffordance : templatedAffordances) {
            jgen.writeObjectFieldStart(templatedAffordance.getRel());

            jgen.writeStringField("@type", "hydra:IriTemplate");
            jgen.writeStringField("hydra:template", templatedAffordance.getHref());
            final List<ActionDescriptor> actionDescriptors = templatedAffordance.getActionDescriptors();
            ActionDescriptor actionDescriptor = actionDescriptors.get(0);
            jgen.writeArrayFieldStart("hydra:mapping");
            writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getPathVariableNames());
            writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getRequestParamNames());
            jgen.writeEndArray();

            jgen.writeEndObject();
        }
        for (Link templatedLink : templatedLinks) {
            // we only have the template, no access to method params
            jgen.writeObjectFieldStart(templatedLink.getRel());

            jgen.writeStringField("@type", "hydra:IriTemplate");
            jgen.writeStringField("hydra:template", templatedLink.getHref());

            jgen.writeArrayFieldStart("hydra:mapping");
            writeHydraVariableMapping(jgen, null, templatedLink.getVariableNames());
            jgen.writeEndArray();

            jgen.writeEndObject();
        }

        Deque<String> vocabStack = (Deque<String>) serializerProvider
                .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
        String currentVocab = vocabStack != null ? vocabStack.peek() : null;

        for (Affordance affordance : affordances) {
            final String rel = affordance.getRel();
            List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
            if (!actionDescriptors.isEmpty()) {
                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeObjectFieldStart(rel); // begin rel
                }
                jgen.writeStringField(JacksonHydraSerializer.AT_ID, affordance.getHref());
                jgen.writeArrayFieldStart("hydra:operation");
            }

            for (ActionDescriptor actionDescriptor : actionDescriptors) {
                jgen.writeStartObject(); // begin a hydra:Operation

                final String semanticActionType = actionDescriptor.getSemanticActionType();
                if (semanticActionType != null) {
                    jgen.writeStringField("@type", semanticActionType);
                }
                jgen.writeStringField("hydra:method", actionDescriptor.getHttpMethod().name());

                final ActionInputParameter requestBodyInputParameter = actionDescriptor.getRequestBody();
                if (requestBodyInputParameter != null) {

                    jgen.writeObjectFieldStart("hydra:expects"); // begin hydra:expects

                    final Class<?> clazz = requestBodyInputParameter.getNestedParameterType();
                    final Expose classExpose = clazz.getAnnotation(Expose.class);
                    final String typeName;
                    if (classExpose != null) {
                        typeName = classExpose.value();
                    } else {
                        typeName = requestBodyInputParameter.getNestedParameterType().getSimpleName();
                    }
                    jgen.writeStringField("@type", typeName);

                    jgen.writeArrayFieldStart("hydra:supportedProperty"); // begin hydra:supportedProperty
                    // TODO check need for actionDescriptor and requestBodyInputParameter here:
                    recurseSupportedProperties(jgen, currentVocab, clazz, actionDescriptor,
                            requestBodyInputParameter, requestBodyInputParameter.getCallValue());
                    jgen.writeEndArray(); // end hydra:supportedProperty

                    jgen.writeEndObject(); // end hydra:expects
                }

                jgen.writeEndObject(); // end hydra:Operation
            }

            if (!actionDescriptors.isEmpty()) {
                jgen.writeEndArray(); // end hydra:operation

                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeEndObject(); // end rel
                }
            }
        }

        for (Link simpleLink : simpleLinks) {
            final String rel = simpleLink.getRel();
            if (Link.REL_SELF.equals(rel)) {
                jgen.writeStringField("@id", simpleLink.getHref());
            } else {
                String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
                jgen.writeObjectFieldStart(linkAttributeName);
                jgen.writeStringField("@id", simpleLink.getHref());
                jgen.writeEndObject();
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.data.rest.tests.mongodb.MongoWebTests.java

/**
 * @see DATAREST-247/*from w  w w.  ja v a 2s .c om*/
 */
@Test
public void executeQueryMethodWithPrimitiveReturnType() throws Exception {

    Link profiles = client.discoverUnique("profiles");
    Link profileSearches = client.discoverUnique(profiles, "search");
    Link countByTypeLink = client.discoverUnique(profileSearches, "countByType");

    assertThat(countByTypeLink.isTemplated(), is(true));
    assertThat(countByTypeLink.getVariableNames(), hasItem("type"));

    MockHttpServletResponse response = client.request(countByTypeLink.expand("Twitter"));
    assertThat(response.getContentAsString(), is("1"));
}

From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

/**
 * @see DATAREST-384/*  ww  w  .  j  a  v a2 s . c  o m*/
 */
@Test
public void execturesSearchThatTakesASort() throws Exception {

    Link booksLink = client.discoverUnique("books");
    Link searchLink = client.discoverUnique(booksLink, "search");
    Link findBySortedLink = client.discoverUnique(searchLink, "find-by-sorted");

    // Assert sort options advertised
    assertThat(findBySortedLink.isTemplated(), is(true));
    assertThat(findBySortedLink.getVariableNames(), hasItems("sort", "projection"));

    // Assert results returned as specified
    client.follow(findBySortedLink.expand("title,desc")).//
            andExpect(jsonPath("$._embedded.books[0].title").value("Spring Data (Second Edition)")).//
            andExpect(jsonPath("$._embedded.books[1].title").value("Spring Data")).//
            andExpect(client.hasLinkWithRel("self"));

    client.follow(findBySortedLink.expand("title,asc")).//
            andExpect(jsonPath("$._embedded.books[0].title").value("Spring Data")).//
            andExpect(jsonPath("$._embedded.books[1].title").value("Spring Data (Second Edition)")).//
            andExpect(client.hasLinkWithRel("self"));
}

From source file:org.springframework.hateoas.LinkUnitTest.java

/**
 * @see #137//from w w  w .  java  2  s.  co m
 */
@Test
public void isTemplatedIfSourceContainsTemplateVariables() {

    Link link = new Link("/foo{?page}");

    assertThat(link.isTemplated(), is(true));
    assertThat(link.getVariableNames(), hasSize(1));
    assertThat(link.getVariableNames(), hasItem("page"));
    assertThat(link.expand("2"), is(new Link("/foo?page=2")));
}

From source file:org.springframework.hateoas.LinkUnitTest.java

/**
 * @see #137//from   ww w.j a  va 2 s. c  om
 */
@Test
public void isntTemplatedIfSourceDoesNotContainTemplateVariables() {

    Link link = new Link("/foo");

    assertThat(link.isTemplated(), is(false));
    assertThat(link.getVariableNames(), hasSize(0));
}