Example usage for org.springframework.hateoas Link REL_SELF

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

Introduction

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

Prototype

LinkRelation REL_SELF

To view the source code for org.springframework.hateoas Link REL_SELF.

Click Source Link

Usage

From source file:com.sra.biotech.submittool.persistence.service.SubmissionServiceImpl.java

public List<Submission> findByStatus(String status) {

    SubmissionResources resources = restTemplate.getForObject(
            getSubmissionUrlTemplate() + "/search/findByStatus/?status={status}", SubmissionResources.class,
            status);//from   w  ww . jav  a  2 s .com

    if (resources == null || CollectionUtils.isEmpty(resources.getContent())) {
        return Collections.emptyList();
    }

    Link listSelfLink = resources.getLink(Link.REL_SELF);
    Collection<SubmissionResource> content = resources.getContent();

    if (!content.isEmpty()) {
        SubmissionResource firstSubmissionResource = content.iterator().next();
        Link linkToFirstResource = firstSubmissionResource.getLink(Link.REL_SELF);
        System.out.println("href = " + linkToFirstResource.getHref());
        System.out.println("rel = " + linkToFirstResource.getRel());
    }

    return resources.unwrap();
}

From source file:org.jug.bg.rest.hateoas.spring.poll.resource.PollResource.java

/**
 * Builds links to all embedded resources.
 *
 * @param embeddedResources Embedded resources for which links will be built.
 *
 * @return List of links to embedded resources. If no resources are provided the result is an empty list.
 *//* ww  w  .j a v  a 2  s.c o m*/
private List<Link> buildLinksToEmbeddedResources(List<AlternativePayload> embeddedResources) {
    if (embeddedResources.isEmpty()) {
        return Collections.emptyList();
    }
    List<Link> linksList = new ArrayList<>();

    // what is to be done is using the self link of the embedded resources and building links to them.
    for (AlternativePayload alternative : embeddedResources) {

        // Note that withRel(...) method is a factory method! I.e. we do not modify alternative's original self link
        Link alternativeLink = alternative.getLink(Link.REL_SELF).withRel("alternatives");

        linksList.add(alternativeLink);
    }
    return linksList;
}

From source file:io.onedecision.engine.decisions.model.dmn.DmnModel.java

@JsonIgnore
public Link getId() {
    return getLink(Link.REL_SELF);
}

From source file:com.github.hateoas.forms.spring.uber.UberUtilsTest.java

@Test
public void identifiableToUberNode() throws Exception {
    BeanResource bean = new BeanResource();
    String canonicalUrl = "http://www.example.com/bean/1";
    bean.add(new Link(canonicalUrl, Link.REL_SELF));
    UberNode node = new UberNode();
    UberUtils.toUberData(node, bean);/*  ww  w .  j av  a 2 s. co m*/
    System.out.println(new ObjectMapper().writeValueAsString(node));
    UberNode selfRel = node.getFirstByRel(Link.REL_SELF);
    assertEquals(canonicalUrl, selfRel.getUrl());
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Looks up the first {@link Order} from the orders representation using a JSONPath expression of
 * {@value #FIRST_ORDER_EXPRESSION}. Looks up the {@value Link#REL_SELF} link from the nested object and follows it to
 * lookup the representation. Verifies the {@code self}, {@code cancel}, and {@code update} link to be present.
 * /*w ww.  j  a v a 2s  .  co  m*/
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse accessFirstOrder(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    String order = JsonPath.read(content, FIRST_ORDER_EXPRESSION).toString();
    Link orderLink = getDiscovererFor(source).findLinkWithRel("self", order);

    log.info(String.format("Picking first order using JSONPath expression %s", FIRST_ORDER_EXPRESSION));
    log.info(String.format("Discovered self link pointing to %s Following", orderLink));

    return mvc.perform(get(orderLink.getHref())). //
            andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
            andExpect(linkWithRelIsPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsPresent(PAYMENT_REL)).//
            andReturn().getResponse();
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Looks up the first {@link Order} from the orders representation using a JSONPath expression of
 * {@value #FIRST_ORDER_EXPRESSION}. Looks up the {@value Link#REL_SELF} link from the nested object and follows it to
 * lookup the representation. Verifies the {@code self}, {@code cancel}, and {@code update} link to be present.
 * //from  www  .  j  a va 2  s  .co  m
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse accessFirstOrder(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    String order = JsonPath.parse(content).read(JsonPath.compile(FIRST_ORDER_EXPRESSION), JSONObject.class)
            .toString();
    Link orderLink = getDiscovererFor(source).findLinkWithRel("self", order).expand();

    LOG.info(String.format("Picking first order using JSONPath expression %s", FIRST_ORDER_EXPRESSION));
    LOG.info(String.format("Discovered self link pointing to %s Following", orderLink));

    return mvc.perform(get(orderLink.getHref())). //
            andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
            andExpect(linkWithRelIsPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsPresent(PAYMENT_REL)).//
            andReturn().getResponse();
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Triggers the payment of an {@link Order} by following the {@code payment} link and submitting a credit card number
 * to it. Verifies that we get a {@code 201 Created} and the response contains an {@code order} link. After the
 * payment has been triggered we fake a cancellation to make sure it is rejected with a {@code 404 Not found}.
 * /*from   www.j  av a 2 s.  c  o m*/
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse triggerPayment(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();
    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link paymentLink = discoverer.findLinkWithRel(PAYMENT_REL, content);

    log.info(String.format("Discovered payment link pointing to %s", paymentLink));

    assertThat(paymentLink, not(nullValue()));

    log.info("Triggering payment");

    ResultActions action = mvc.perform(
            put(paymentLink.getHref()).content("\"1234123412341234\"").contentType(MediaType.APPLICATION_JSON));

    MockHttpServletResponse result = action.andExpect(status().isCreated()). //
            andExpect(linkWithRelIsPresent(ORDER_REL)). //
            andReturn().getResponse();

    log.info("Payment triggered");

    // Make sure we cannot cheat and cancel the order after it has been payed
    log.info("Faking a cancel request to make sure it's forbidden");
    Link selfLink = discoverer.findLinkWithRel(Link.REL_SELF, content);
    mvc.perform(delete(selfLink.getHref())).andExpect(status().isMethodNotAllowed());

    return result;
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Triggers the payment of an {@link Order} by following the {@code payment} link and submitting a credit card number
 * to it. Verifies that we get a {@code 201 Created} and the response contains an {@code order} link. After the
 * payment has been triggered we fake a cancellation to make sure it is rejected with a {@code 404 Not found}.
 * //from ww w.  j  a va  2s  .c  om
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse triggerPayment(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();
    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link paymentLink = discoverer.findLinkWithRel(PAYMENT_REL, content);

    LOG.info(String.format("Discovered payment link pointing to %s", paymentLink));

    assertThat(paymentLink, not(nullValue()));

    LOG.info("Triggering payment");

    ResultActions action = mvc.perform(put(paymentLink.getHref()).//
            content("\"1234123412341234\"").//
            contentType(MediaType.APPLICATION_JSON).//
            accept(MediaTypes.HAL_JSON));

    MockHttpServletResponse result = action.andExpect(status().isCreated()). //
            andExpect(linkWithRelIsPresent(ORDER_REL)). //
            andReturn().getResponse();

    LOG.info("Payment triggered");

    // Make sure we cannot cheat and cancel the order after it has been payed
    LOG.info("Faking a cancel request to make sure it's forbidden");
    Link selfLink = discoverer.findLinkWithRel(Link.REL_SELF, content).expand();
    mvc.perform(delete(selfLink.getHref())).andExpect(status().isMethodNotAllowed());

    return result;
}

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  www  . 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);
    }
}