Skip to content

Instantly share code, notes, and snippets.

@kclay
Created January 31, 2014 22:18
Show Gist options
  • Save kclay/8744419 to your computer and use it in GitHub Desktop.
Save kclay/8744419 to your computer and use it in GitHub Desktop.
@get arbitrary parameters
public class ExtendedRestTemplate extends RestTemplate{
public SafeRestTemplate( RestTemplate from) {
setErrorHandler(fromTemplate.getErrorHandler());
setMessageConverters(fromTemplate.getMessageConverters());
setInterceptors(fromTemplate.getInterceptors());
setRequestFactory(fromTemplate.getRequestFactory());
}
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException {
UriTemplate uriTemplate = new HttpUrlTemplate(url);
URI expanded = uriTemplate.expand(urlVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException {
UriTemplate uriTemplate = new HttpUrlTemplate(url);
URI expanded = uriTemplate.expand(urlVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
/**
* HTTP-specific subclass of UriTemplate, overriding the encode method.
*/
private static class HttpUrlTemplate extends UriTemplate {
private static final long serialVersionUID = 1L;
private UriComponents uriComponents;
public HttpUrlTemplate(String uriTemplate) {
super(uriTemplate);
this.uriComponents = UriComponentsBuilder.fromUriString(uriTemplate).build();
}
@Override
@SuppressWarnings("deprecation")
protected URI encodeUri(String uri) {
try {
String encoded = UriUtils.encodeHttpUrl(uri, "UTF-8");
return new URI(encoded);
} catch ( UnsupportedEncodingException ex ) {
// should not happen, UTF-8 is always supported
throw new IllegalStateException(ex);
} catch ( URISyntaxException ex ) {
throw new IllegalArgumentException("Could not create HTTP URL from [" + uri + "]: " + ex, ex);
}
}
public static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
String[] parts;
for ( String param : params ) {
parts = param.split("=");
if ( parts.length != 2 ) continue;
String name = parts[ 0 ];
String value = parts[ 1 ];
map.put(name, value);
}
return map;
}
private static final String[] QUERY_KEYS = new String[]{ "{query}"};
private void fixQueryString(Map<String, ?> uriVariables) {
if ( uriComponents.getQuery() == null ) return;
String query = uriComponents.getQuery();
for ( String token : QUERY_KEYS ) {
if ( query.contains(token) ) {
String urlTemplate = this.toString().replace(token, "");
Map<String, String> vars = (Map<String, String>) uriVariables;
String lookup = token.replace("{", "").replace("}", "");
Map<String, String> map = getQueryMap(vars.get(lookup));
boolean added = false;
for ( String key : map.keySet() ) {
added = true;
urlTemplate += key + "=" + "{" + key + "}&";
vars.put(key, map.get(key));
}
if ( !added ) { // special case for when no query strings are passed .. yeah nasty
urlTemplate = urlTemplate.replace("?", "");
} else {
urlTemplate = urlTemplate.substring(0, urlTemplate.length() - 1);
}
uriComponents = UriComponentsBuilder.fromUriString(urlTemplate).build();
}
}
}
public URI expand(Map<String, ?> uriVariables) {
fixQueryString(uriVariables);
UriComponents expandedComponents = uriComponents.expand(uriVariables);
UriComponents encodedComponents = expandedComponents.encode();
String uri = encodedComponents.toUriString();
uri = uri.replace("(", "%28");
uri = uri.replace(")", "%29");
try {
return new URI(uri);
} catch ( URISyntaxException ex ) {
throw new IllegalStateException("Could not create URI object: " + ex.getMessage(), ex);
}
/*if ( expandedComponents.getPath().indexOf("/cart/") != -1 ) {
return expandedComponents.toUri();
} else {
} */
}
}
}
interface API extends RestClientSupport{
@Get("search/spots.json?{query}")
List<Spot> search(String query);
}
public class QueryString {
private Map<String, String> values = new HashMap<String, String>();
public QueryString put(String key, String value) {
if ( value != null && value.length() != 0 ) {
values.put(key, value);
}
return this;
}
public String[] toValues() {
return values.values().toArray(new String[ values.size() ]);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if ( values.size() > 0 ) {
// builder.append("?");
int length = values.size();
int index = 0;
for ( String key : values.keySet() ) {
builder.append(key).append("=").append(values.get(key));
if ( index < length - 1 ) {
builder.append("&");
}
}
}
return builder.toString();
}
}
API api = ....
api.setRestTemplate(new ExtendedResTemplate(api.getRestTemplate()));
api.search(new QueryString().put("soc",2349).put("coarse","true").toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment