Skip to content

Instantly share code, notes, and snippets.

@pulsar256
Created October 11, 2016 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pulsar256/fe9333c97ea6d25356012337ce25cff6 to your computer and use it in GitHub Desktop.
Save pulsar256/fe9333c97ea6d25356012337ce25cff6 to your computer and use it in GitHub Desktop.
Templated Links for spring-hateoas workaround
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