[Solved] Return link from Hateos


Based on your comments & question for migration this is what I am suggesting:

Map<LinkRelation, Optional<Link>> links = new HashMap<LinkRelation, Optional<Link>>();

links.put(IanaLinkRelations.SELF, Optional.of(response.getLink(IanaLinkRelations.SELF)));

links.put(IanaLinkRelations.NEXT, Optional.of(response.getLink(IanaLinkRelations.NEXT)));

links.put(IanaLinkRelations.PREVIOUS, Optional.of(response.getLink(IanaLinkRelations.PREVIOUS)));

….

//calling addLinlk

addLink(apmCoreBaseUrl, response, links, IanaLinkRelations.SELF);

addLink(apmCoreBaseUrl, response, links, IanaLinkRelations.NEXT);

addLink(apmCoreBaseUrl, response, links, IanaLinkRelations.PREVIOUS);

And inside addLink:

private void addLink(String baseUrl, RegistrationsResource response, Map<LinkRelation, Optional> links, LinkRelation rel) {

    links.get(rel).ifPresent(x->{
     Link link = x;
     String href = baseUrl;
    if (link.getHref().contains("?")) {
      href = href + link.getHref().substring(link.getHref().indexOf('?'));
    }
    link = Link.of(href, rel);
    response.add(link);
    });
  }

Tested with Java 11 & spring-hateoas 1.5.0. If you have any different versions, please let me know.

Edit

As per OP mentioned, they are using hateoas version 2.6.7.
The response reference in OP’s code is custom class which extending RepresentationModel. So response.getLink(..) will return type of Optional<Link>.
So below workaround will work :

Map<LinkRelation, Optional<Link>> links = new HashMap<LinkRelation, Optional<Link>>();

links.put(IanaLinkRelations.SELF, response.getLink(IanaLinkRelations.SELF));

No changes in addLink & no changes in calling addLink required, my original answer still valid for other operations.

12

solved Return link from Hateos