Created
October 11, 2016 16:16
-
-
Save pulsar256/fe9333c97ea6d25356012337ce25cff6 to your computer and use it in GitHub Desktop.
Templated Links for spring-hateoas workaround
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.lang.StringUtils; | |
import org.springframework.core.DefaultParameterNameDiscoverer; | |
import org.springframework.hateoas.Link; | |
import org.springframework.hateoas.UriTemplate; | |
import org.springframework.hateoas.mvc.ControllerLinkBuilder; | |
import org.springframework.web.bind.annotation.RequestParam; | |
import org.springframework.web.util.UriComponentsBuilder; | |
import java.lang.annotation.Annotation; | |
import java.lang.reflect.Method; | |
import static org.springframework.hateoas.TemplateVariable.VariableType.REQUEST_PARAM; | |
public class Utils { | |
public static Link getTemplatedLink(final Method m, final String rel) { | |
DefaultParameterNameDiscoverer disco = new DefaultParameterNameDiscoverer(); | |
ControllerLinkBuilder builder = ControllerLinkBuilder.linkTo(m.getDeclaringClass(), m); | |
UriTemplate uriTemplate = new UriTemplate(UriComponentsBuilder.fromUri(builder.toUri()).build().toUriString()); | |
Annotation[][] parameterAnnotations = m.getParameterAnnotations(); | |
int param = 0; | |
for (Annotation[] parameterAnnotation : parameterAnnotations) { | |
for (Annotation annotation : parameterAnnotation) { | |
if (annotation.annotationType().equals(RequestParam.class)) { | |
RequestParam rpa = (RequestParam) annotation; | |
String parameterName = rpa.name(); | |
if (StringUtils.isEmpty(parameterName)) parameterName = disco.getParameterNames(m)[param]; | |
uriTemplate = uriTemplate.with(parameterName, REQUEST_PARAM); | |
} | |
} | |
param++; | |
} | |
return new Link(uriTemplate, rel); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment