Skip to content

Instantly share code, notes, and snippets.

@odrotbohm
Created January 13, 2012 16:13
Show Gist options
  • Save odrotbohm/1607252 to your computer and use it in GitHub Desktop.
Save odrotbohm/1607252 to your computer and use it in GitHub Desktop.
public class UriBuilder {
private UriComponents builder;
private UriBuilder(UriComponentsBuilder builder) {
this.builder = builder.build();
}
public static UriBuilder uriFor(Class<?> controller) {
RequestMapping annotation = controller.getAnnotation(RequestMapping.class);
String[] mapping = (String[]) AnnotationUtils.getValue(annotation);
if (mapping.length > 1) {
throw new IllegalStateException("Multiple controller mappings defined! Unable to build URI!");
}
UriBuilder builder = new UriBuilder(ServletUriComponentsBuilder.fromCurrentServletMapping());
return mapping.length == 0 ? builder : builder.slash(mapping[0]);
}
public UriBuilder slash(Object object) {
String resource = StringUtils.trimLeadingCharacter(object.toString(), '/');
resource = StringUtils.trimTrailingCharacter(resource, '/');
return new UriBuilder(UriComponentsBuilder.fromUri(builder.toUri()).pathSegment(resource.split("/")));
}
@Override
public String toString() {
return builder.encode().toUriString();
}
public URI toUri() {
return builder.encode().toUri();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment