Add ability to parse arguments with parseOptionMap

The RestApiServlet wasn't able to handle command-line parsers which
included required arguments. These can now be specified by passing
a Set of which param names to look for and treat as arguments.

Change-Id: Ia1400c7decbb896f038ab016c063e9ee6e5991d9
Signed-off-by: Brad Larson <bklarson@gmail.com>
This commit is contained in:
Brad Larson 2012-07-16 12:39:52 -05:00
parent 547c586858
commit 05d942c324
2 changed files with 19 additions and 2 deletions

View File

@ -34,7 +34,9 @@ import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@ -182,11 +184,16 @@ public abstract class RestApiServlet extends HttpServlet {
public <T> boolean parse(T param, HttpServletRequest req,
HttpServletResponse res) throws IOException {
return parse(param, req, res, Collections.<String>emptySet());
}
public <T> boolean parse(T param, HttpServletRequest req,
HttpServletResponse res, Set<String> argNames) throws IOException {
CmdLineParser clp = parserFactory.create(param);
try {
@SuppressWarnings("unchecked")
Map<String, String[]> parameterMap = req.getParameterMap();
clp.parseOptionMap(parameterMap);
clp.parseOptionMap(parameterMap, argNames);
} catch (CmdLineException e) {
if (!clp.wasHelpRequestedByOption()) {
res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

View File

@ -54,9 +54,11 @@ import java.io.StringWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
/**
* Extended command line parser which handles --foo=value arguments.
@ -209,6 +211,12 @@ public class CmdLineParser {
public void parseOptionMap(Map<String, String[]> parameters)
throws CmdLineException {
parseOptionMap(parameters, Collections.<String>emptySet());
}
public void parseOptionMap(Map<String, String[]> parameters,
Set<String> argNames)
throws CmdLineException {
ArrayList<String> tmp = new ArrayList<String>();
for (Map.Entry<String, String[]> ent : parameters.entrySet()) {
String name = ent.getKey();
@ -230,7 +238,9 @@ public class CmdLineParser {
}
} else {
for (String value : ent.getValue()) {
tmp.add(name);
if (!argNames.contains(ent.getKey())) {
tmp.add(name);
}
tmp.add(value);
}
}