Skip to content

Instantly share code, notes, and snippets.

@daschl
Created March 3, 2014 08:24
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 daschl/9320698 to your computer and use it in GitHub Desktop.
Save daschl/9320698 to your computer and use it in GitHub Desktop.
package bench;
import java.net.URLEncoder;
/**
* A new Query implementation trimmed for performance.
*/
public class FastQuery {
private static final int PARAM_REDUCE_OFFSET = 0;
private static final int PARAM_LIMIT_OFFSET = 2;
/**
* Number of supported possible params for a query.
*/
private static final int NUM_PARAMS = 18;
/**
* Contains all stored params.
*/
private final String[] params;
/**
* Create a new {@link FastQuery}.
*/
public FastQuery() {
params = new String[NUM_PARAMS * 2];
}
/**
* Explicitly enable/disable the reduce function on the query.
*
* @param reduce if reduce should be enabled or not.
* @return the {@link FastQuery} object for proper chaining.
*/
public FastQuery setReduce(boolean reduce) {
params[PARAM_REDUCE_OFFSET] = "reduce";
params[PARAM_REDUCE_OFFSET+1] = Boolean.toString(reduce);
return this;
}
/**
* Limit the number of the returned documents to the specified number.
*
* @param limit the number of documents to return.
* @return the {@link FastQuery} object for proper chaining.
*/
public FastQuery setLimit(int limit) {
params[PARAM_LIMIT_OFFSET] = "limit";
params[PARAM_LIMIT_OFFSET+1] = Integer.toString(limit);
return this;
}
/**
* Returns the {@link FastQuery} as a HTTP-compatible query string.
*
* @return the stringified query.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("?");
for (int i = 0; i < params.length; i++) {
if (params[i] == null) {
i++;
continue;
}
boolean even = i % 2 == 0;
if (i > 0 && even) {
sb.append("&");
}
sb.append(params[i]);
if (even) {
sb.append("=");
}
}
return sb.toString();
}
/**
* Helper method to properly encode a string.
*
* This method can be overridden if a different encoding logic needs to be used.
*
* @param source source string.
* @return encoded target string.
*/
protected String encode(final String source) {
try {
return URLEncoder.encode(source, "UTF-8");
} catch(Exception ex) {
throw new RuntimeException("Could not prepare view argument: " + ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment