Created
December 24, 2012 00:24
-
-
Save codefromthecrypt/4366867 to your computer and use it in GitHub Desktop.
level 1 uri parser
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
/** | |
* | |
* @param template | |
* URI string that can be in level 1 <a href="http://tools.ietf.org/html/rfc6570">RFC6570</a> form. | |
* | |
* @param variables | |
* to the URI string | |
* @throws IllegalArgumentException | |
* if there's a problem in the input data | |
*/ | |
public static String expand(String template, Map<String, ?> variables) { | |
if (template.length() < 3) // skip expansion if there's no valid variables set. ex. {a} is the first valid | |
return template.toString(); | |
boolean inVar = false; | |
char last = '|';// dummy initializer; only concerned with slashes | |
StringBuilder var = new StringBuilder(); | |
StringBuilder builder = new StringBuilder(); | |
for (char c : Lists.charactersOf(template)) { | |
switch (c) { | |
case '{': | |
inVar = true; | |
break; | |
case '}': | |
inVar = false; | |
String key = var.toString(); | |
Object value = variables.get(var.toString()); | |
checkArgument(value != null, "unresolved template parameter %s in %s", key, template); | |
builder.append(value); | |
var = new StringBuilder(); | |
break; | |
case '/': | |
if (last == '/') | |
break; // make sure we don't do double-slashing in the path | |
default: | |
if (inVar) | |
var.append(c); | |
else | |
builder.append(c); | |
} | |
last = c; | |
} | |
return builder.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment