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:org.springsource.restbucks.PaymentProcessIntegrationTest.java

/**
 * Follows the {@code order} link and asserts only the self link being present so that no further navigation is
 * possible anymore.//  www.j  ava  2  s. co m
 * 
 * @param response
 * @throws Exception
 */
private void verifyOrderTaken(MockHttpServletResponse response) throws Exception {

    Link orderLink = links.findLinkWithRel(ORDER_REL, response.getContentAsString());
    MockHttpServletResponse orderResponse = mvc.perform(get(orderLink.getHref())). //
            andExpect(status().isOk()). // //
            andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
            andExpect(linkWithRelIsNotPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsNotPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsNotPresent(PAYMENT_REL)). //
            andExpect(jsonPath("$status", is("TAKEN"))). //
            andReturn().getResponse();

    log.info("Final order state: " + orderResponse.getContentAsString());
}

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

/**
 * Cancels the order by issuing a delete request. Verifies the resource being inavailable after that.
 * //from  www . j a  v a2 s.c  om
 * @param response the response that retrieved an order resource
 * @throws Exception
 */
private void cancelOrder(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();

    Link selfLink = links.findLinkWithRel(Link.REL_SELF, content);
    Link cancellationLink = links.findLinkWithRel(CANCEL_REL, content);

    mvc.perform(delete(cancellationLink.getHref())).andExpect(status().isNoContent());
    mvc.perform(get(selfLink.getHref())).andExpect(status().isNotFound());
}

From source file:com.github.hateoas.forms.spring.AffordanceBuilder.java

@Override
public Affordance withSelfRel() {
    return rel(Link.REL_SELF).build();
}

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 {/* w  w  w .jav a2  s  .  co  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:de.escalon.hypermedia.spring.uber.UberUtilsTest.java

@Test
public void linkGetToUberNode() throws Exception {
    Link link = new Link("/foo", Link.REL_SELF);
    UberNode linkNode = UberUtils.toUberLink(link);
    assertEquals(Arrays.asList(Link.REL_SELF), linkNode.getRel());
    assertEquals("/foo", linkNode.getUrl());
    assertNull(linkNode.getModel());//from   w w w.  j  a  v a  2  s .  c  o  m
    assertNull(linkNode.getAction());
}

From source file:de.escalon.hypermedia.spring.uber.UberUtilsTest.java

@Test
public void linkPostToUberNode() throws Exception {
    // TODO create a Link with variables separate from URITemplate for POST
    Link link = null; //new Link(new UriTemplate("/foo{?foo,bar}"), Link.REL_SELF, RequestMethod.POST.name());
    UberNode linkNode = UberUtils.toUberLink(link);
    assertEquals(Arrays.asList(Link.REL_SELF), linkNode.getRel());
    assertEquals("/foo", linkNode.getUrl());
    assertEquals("foo={foo}&bar={bar}", linkNode.getModel());
    assertEquals(UberAction.APPEND, linkNode.getAction());
}

From source file:org.dspace.app.rest.link.DSpaceResourceHalLinkFactory.java

protected void addLinks(DSpaceResource halResource, Pageable page, LinkedList<Link> list) throws Exception {
    RestAddressableModel data = halResource.getContent();

    try {//from   ww w  .  j ava  2s.  c  o m
        for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            String name = pd.getName();
            if (readMethod != null && !"class".equals(name)) {
                LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class);

                if (linkAnnotation != null) {
                    if (StringUtils.isNotBlank(linkAnnotation.name())) {
                        name = linkAnnotation.name();
                    }

                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    // no method is specified to retrieve the linked object(s) so check if it is already here
                    if (StringUtils.isBlank(linkAnnotation.method())) {
                        Object linkedObject = readMethod.invoke(data);

                        if (linkedObject instanceof RestAddressableModel
                                && linkAnnotation.linkClass().isAssignableFrom(linkedObject.getClass())) {
                            linkToSubResource = utils.linkToSingleResource((RestAddressableModel) linkedObject,
                                    name);
                        }

                        if (linkedObject != null || !linkAnnotation.optional()) {
                            halResource.add(linkToSubResource);
                        }
                    }

                } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) {
                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    halResource.add(linkToSubResource);
                }
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

    halResource.add(utils.linkToSingleResource(data, Link.REL_SELF));
}

From source file:org.dspace.app.rest.link.search.SearchFacetEntryHalLinkFactory.java

@Override
protected void addLinks(SearchFacetEntryResource halResource, Pageable pageable, LinkedList<Link> list)
        throws Exception {

    SearchFacetEntryRest facetData = halResource.getFacetData();
    DiscoveryResultsRest searchData = halResource.getSearchData();

    String query = searchData == null ? null : searchData.getQuery();
    String dsoType = searchData == null ? null : searchData.getDsoType();
    String scope = searchData == null ? null : searchData.getScope();

    UriComponentsBuilder uriBuilder = uriBuilder(
            getMethodOn().getFacetValues(facetData.getName(), null, query, dsoType, scope, null, null));

    addFilterParams(uriBuilder, searchData);

    //If our rest data contains a list of values, construct the page links. Otherwise, only add a self link
    if (CollectionUtils.isNotEmpty(facetData.getValues())) {
        PageImpl page = new PageImpl<>(facetData.getValues(), new PageRequest(0, facetData.getFacetLimit()),
                facetData.getValues().size() + (BooleanUtils.isTrue(facetData.isHasMore()) ? 1 : 0));

        halResource.setPageHeader(new EmbeddedPageHeader(uriBuilder, page, false));

    } else {//from   ww  w.j  a  v a  2 s  .c  o m
        list.add(buildLink(Link.REL_SELF, uriBuilder.build().toUriString()));
    }

}

From source file:org.dspace.app.rest.model.hateoas.DSpaceResource.java

public DSpaceResource(T data, Utils utils, String... rels) {
    this.data = data;

    if (data != null) {
        try {//from   w w w  . j a  v  a 2s. com
            LinksRest links = data.getClass().getDeclaredAnnotation(LinksRest.class);
            if (links != null && rels != null) {
                List<String> relsList = Arrays.asList(rels);
                for (LinkRest linkAnnotation : links.links()) {
                    if (!relsList.contains(linkAnnotation.name())) {
                        continue;
                    }
                    String name = linkAnnotation.name();
                    Link linkToSubResource = utils.linkToSubResource(data, name);
                    String apiCategory = data.getCategory();
                    String model = data.getType();
                    LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model,
                            linkAnnotation.name());

                    if (!linkRepository.isEmbeddableRelation(data, linkAnnotation.name())) {
                        continue;
                    }
                    try {
                        //RestModel linkClass = linkAnnotation.linkClass().newInstance();
                        Method[] methods = linkRepository.getClass().getMethods();
                        boolean found = false;
                        for (Method m : methods) {
                            if (StringUtils.equals(m.getName(), linkAnnotation.method())) {
                                // TODO add support for single linked object other than for collections
                                Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m.invoke(
                                        linkRepository, null, ((BaseObjectRest) data).getId(), null, null);
                                EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult,
                                        null);
                                embedded.put(name, ep);
                                found = true;
                            }
                        }
                        // TODO custom exception
                        if (!found) {
                            throw new RuntimeException("Method for relation " + linkAnnotation.name()
                                    + " not found: " + linkAnnotation.method());
                        }
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }

            for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) {
                Method readMethod = pd.getReadMethod();
                String name = pd.getName();
                if (readMethod != null && !"class".equals(name)) {
                    LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class);

                    if (linkAnnotation != null) {
                        if (StringUtils.isNotBlank(linkAnnotation.name())) {
                            name = linkAnnotation.name();
                        }
                        Link linkToSubResource = utils.linkToSubResource(data, name);
                        // no method is specified to retrieve the linked object(s) so check if it is already here
                        if (StringUtils.isBlank(linkAnnotation.method())) {
                            this.add(linkToSubResource);
                            Object linkedObject = readMethod.invoke(data);
                            Object wrapObject = linkedObject;
                            if (linkedObject instanceof RestModel) {
                                RestModel linkedRM = (RestModel) linkedObject;
                                wrapObject = utils
                                        .getResourceRepository(linkedRM.getCategory(), linkedRM.getType())
                                        .wrapResource(linkedRM);
                            } else {
                                if (linkedObject instanceof List) {
                                    List<RestModel> linkedRMList = (List<RestModel>) linkedObject;
                                    if (linkedRMList.size() > 0) {

                                        DSpaceRestRepository<RestModel, ?> resourceRepository = utils
                                                .getResourceRepository(linkedRMList.get(0).getCategory(),
                                                        linkedRMList.get(0).getType());
                                        // TODO should we force pagination also of embedded resource? 
                                        // This will force a pagination with size 10 for embedded collections as well
                                        //                                 int pageSize = 1;
                                        //                                 PageImpl<RestModel> page = new PageImpl(
                                        //                                       linkedRMList.subList(0,
                                        //                                             linkedRMList.size() > pageSize ? pageSize : linkedRMList.size()), new PageRequest(0, pageSize), linkedRMList.size()); 
                                        PageImpl<RestModel> page = new PageImpl(linkedRMList);
                                        wrapObject = new EmbeddedPage(linkToSubResource.getHref(),
                                                page.map(resourceRepository::wrapResource), linkedRMList);
                                    } else {
                                        wrapObject = null;
                                    }
                                }
                            }
                            if (linkedObject != null) {
                                embedded.put(name, wrapObject);
                            } else {
                                embedded.put(name, null);
                            }
                            Method writeMethod = pd.getWriteMethod();
                            writeMethod.invoke(data, new Object[] { null });
                        } else {
                            // call the link repository
                            try {
                                //RestModel linkClass = linkAnnotation.linkClass().newInstance();
                                String apiCategory = data.getCategory();
                                String model = data.getType();
                                LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory,
                                        model, linkAnnotation.name());
                                Method[] methods = linkRepository.getClass().getMethods();
                                boolean found = false;
                                for (Method m : methods) {
                                    if (StringUtils.equals(m.getName(), linkAnnotation.method())) {
                                        // TODO add support for single linked object other than for collections
                                        Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m
                                                .invoke(linkRepository, null, ((BaseObjectRest) data).getId(),
                                                        null, null);
                                        EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(),
                                                pageResult, null);
                                        embedded.put(name, ep);
                                        found = true;
                                    }
                                }
                                // TODO custom exception
                                if (!found) {
                                    throw new RuntimeException("Method for relation " + linkAnnotation.name()
                                            + " not found: " + linkAnnotation.method());
                                }
                            } catch (IllegalAccessException | IllegalArgumentException
                                    | InvocationTargetException e) {
                                throw new RuntimeException(e.getMessage(), e);
                            }
                        }
                    } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) {
                        Link linkToSubResource = utils.linkToSubResource(data, name);
                        this.add(linkToSubResource);
                        RestModel linkedObject = (RestModel) readMethod.invoke(data);
                        if (linkedObject != null) {
                            embedded.put(name, utils
                                    .getResourceRepository(linkedObject.getCategory(), linkedObject.getType())
                                    .wrapResource(linkedObject));
                        } else {
                            embedded.put(name, null);
                        }

                        Method writeMethod = pd.getWriteMethod();
                        writeMethod.invoke(data, new Object[] { null });
                    }
                }
            }
        } catch (IntrospectionException | IllegalArgumentException | IllegalAccessException
                | InvocationTargetException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        this.add(utils.linkToSingleResource(data, Link.REL_SELF));
    }
}

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

/**
 * call the rubrics-service to save the binding between assignment and rubric
 * @param params A hashmap with all the rbcs params comming from the component. The tool should generate it.
 * @param tool the tool id, something like "sakai.assignment"
 * @param id the id of the element to//from www. j  ava  2s .c o m
 */

public void saveRubricAssociation(String tool, String id, HashMap<String, String> params) {

    String associationHref = null;
    String created = "";
    String owner = "";
    Map<String, Boolean> oldParams = new HashMap<>();

    try {
        Optional<Resource<ToolItemRubricAssociation>> associationResource = getRubricAssociationResource(tool,
                id);
        if (associationResource.isPresent()) {
            associationHref = associationResource.get().getLink(Link.REL_SELF).getHref();
            ToolItemRubricAssociation association = associationResource.get().getContent();
            created = association.getMetadata().getCreated().toString();
            owner = association.getMetadata().getOwner();
            oldParams = association.getParameters();
        }

        //we will create a new one or update if the parameter rbcs-associate is true
        String nowTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
        if (params.get("rbcs-associate").equals("1")) {

            if (associationHref == null) { // create a new one.
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get("rbcs-rubricslist") + ",\"metadata\" : {\"created\" : \"" + nowTime
                        + "\",\"modified\" : \"" + nowTime + "\",\"owner\" : \""
                        + userDirectoryService.getCurrentUser().getId() + "\"},\"parameters\" : {"
                        + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("New association " + input);
                String query = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                        + "rubric-associations/";
                String resultPost = postRubricResource(query, input, tool);
                log.debug("resultPost: " + resultPost);
            } else {
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get("rbcs-rubricslist") + ",\"metadata\" : {\"created\" : \"" + created
                        + "\",\"modified\" : \"" + nowTime + "\",\"owner\" : \"" + owner
                        + "\"},\"parameters\" : {" + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("Existing association update" + input);
                String resultPut = putRubricResource(associationHref, input, tool);
                //update the actual one.
                log.debug("resultPUT: " + resultPut);
            }
        } else {
            // We delete the association
            if (associationHref != null) {
                deleteRubricAssociation(associationHref, tool);
            }
        }

    } catch (Exception e) {
        //TODO If we have an error here, maybe we should return say something to the user
    }
}