Created
January 13, 2012 16:13
-
-
Save odrotbohm/1607252 to your computer and use it in GitHub Desktop.
This file contains 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
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