Till Westmann has uploaded a new change for review.

  https://asterix-gerrit.ics.uci.edu/1201

Change subject: add support for JSON encoded requests
......................................................................

add support for JSON encoded requests

Change-Id: I1cc934d5dd984b476d4adb1755572d2e2f451985
---
M 
asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
1 file changed, 60 insertions(+), 27 deletions(-)


  git pull ssh://asterix-gerrit.ics.uci.edu:29418/asterixdb 
refs/changes/01/1201/1

diff --git 
a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
 
b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
index 132737b..6c98afa 100644
--- 
a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
+++ 
b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
@@ -56,6 +56,8 @@
 import org.apache.hyracks.api.client.IHyracksClientConnection;
 import org.apache.hyracks.api.dataset.IHyracksDataset;
 import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.json.JSONException;
+import org.json.JSONObject;
 
 public class QueryServiceServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
@@ -71,10 +73,9 @@
     }
 
     public enum Parameter {
-        // Standard
         STATEMENT("statement"),
         FORMAT("format"),
-        // Asterix
+        CLIENT_ID("client_context_id"),
         PRETTY("pretty");
 
         private final String str;
@@ -121,6 +122,7 @@
 
     public enum ResultFields {
         REQUEST_ID("requestID"),
+        CLIENT_ID("clientContextID"),
         SIGNATURE("signature"),
         TYPE("type"),
         STATUS("status"),
@@ -217,6 +219,13 @@
         }
     }
 
+    static class RequestParameters {
+        String statement;
+        String format;
+        boolean pretty;
+        String clientContextID;
+    }
+
     private static String getParameterValue(String content, String attribute) {
         if (content == null || attribute == null) {
             return null;
@@ -255,11 +264,7 @@
         return SessionConfig.OutputFormat.CLEAN_JSON;
     }
 
-    /**
-     * Construct a SessionConfig with the appropriate output writer and
-     * output-format based on the Accept: header and other servlet parameters.
-     */
-    private static SessionConfig createSessionConfig(HttpServletRequest 
request, PrintWriter resultWriter) {
+    private static SessionConfig createSessionConfig(RequestParameters param, 
PrintWriter resultWriter) {
         SessionConfig.ResultDecorator resultPrefix = (AlgebricksAppendable 
app) -> {
             app.append("\t\"");
             app.append(ResultFields.RESULTS.str());
@@ -272,16 +277,14 @@
             return app;
         };
 
-        final String formatstr = 
toLower(request.getParameter(Parameter.FORMAT.str()));
-        SessionConfig.OutputFormat format = getFormat(formatstr);
+        SessionConfig.OutputFormat format = getFormat(param.format);
         SessionConfig sessionConfig = new SessionConfig(resultWriter, format, 
resultPrefix, resultPostfix);
         sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, true);
-        boolean indentJson = 
Boolean.parseBoolean(request.getParameter(Parameter.PRETTY.str()));
-        sessionConfig.set(SessionConfig.FORMAT_INDENT_JSON, indentJson);
+        sessionConfig.set(SessionConfig.FORMAT_INDENT_JSON, param.pretty);
         sessionConfig.set(SessionConfig.FORMAT_QUOTE_RECORD,
                 format != SessionConfig.OutputFormat.CLEAN_JSON && format != 
SessionConfig.OutputFormat.LOSSLESS_JSON);
-        sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER,
-                format == SessionConfig.OutputFormat.CSV && 
"present".equals(getParameterValue(formatstr, "header")));
+        sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, format == 
SessionConfig.OutputFormat.CSV
+                && "present".equals(getParameterValue(param.format, 
"header")));
         return sessionConfig;
     }
 
@@ -305,6 +308,12 @@
         UUID requestId = UUID.randomUUID();
         printField(pw, ResultFields.REQUEST_ID.str(), requestId.toString());
         return requestId;
+    }
+
+    private static void printClientContextID(PrintWriter pw, RequestParameters 
params) {
+        if (params.clientContextID != null && 
!params.clientContextID.isEmpty()) {
+            printField(pw, ResultFields.CLIENT_ID.str(), 
params.clientContextID);
+        }
     }
 
     private static void printSignature(PrintWriter pw) {
@@ -370,16 +379,9 @@
     }
 
     @Override
-    protected void doPost(HttpServletRequest request, HttpServletResponse 
response)
-            throws ServletException, IOException {
-        String query = request.getParameter(Parameter.STATEMENT.str());
+    protected void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException {
         try {
-            if (query == null) {
-                StringWriter sw = new StringWriter();
-                IOUtils.copy(request.getInputStream(), sw, 
StandardCharsets.UTF_8.name());
-                query = sw.toString();
-            }
-            handleRequest(request, response, query);
+            handleRequest(getRequestParameters(request), response);
         } catch (IOException e) {
             // Servlet methods should not throw exceptions
             // http://cwe.mitre.org/data/definitions/600.html
@@ -387,13 +389,43 @@
         }
     }
 
-    private void handleRequest(HttpServletRequest request, HttpServletResponse 
response, String query)
-            throws IOException {
+    private RequestParameters getRequestParameters(HttpServletRequest request) 
throws IOException {
+        final String contentType = request.getContentType();
+        RequestParameters param = new RequestParameters();
+        if (MediaType.JSON.str().equals(contentType)) {
+            StringWriter sw = new StringWriter();
+            IOUtils.copy(request.getInputStream(), sw, 
StandardCharsets.UTF_8.name());
+            try {
+                JSONObject jsonRequest = new JSONObject(sw.toString());
+                param.statement = 
jsonRequest.getString(Parameter.STATEMENT.str());
+                param.format = 
toLower(jsonRequest.optString(Parameter.FORMAT.str()));
+                param.pretty = jsonRequest.optBoolean(Parameter.PRETTY.str());
+                param.clientContextID = 
jsonRequest.optString(Parameter.CLIENT_ID.str());
+            } catch (JSONException e) {
+                // if the JSON parsing fails, the statement is empty and we 
get an empty statement error
+                GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), 
e);
+            }
+        } else {
+            String statement = request.getParameter(Parameter.STATEMENT.str());
+            if (statement == null) {
+                StringWriter sw = new StringWriter();
+                IOUtils.copy(request.getInputStream(), sw, 
StandardCharsets.UTF_8.name());
+                statement = sw.toString();
+            }
+            param.statement = statement;
+            param.format = 
toLower(request.getParameter(Parameter.FORMAT.str()));
+            param.pretty = 
Boolean.parseBoolean(request.getParameter(Parameter.PRETTY.str()));
+            param.clientContextID = 
request.getParameter(Parameter.CLIENT_ID.str());
+        }
+        return param;
+    }
+
+    private void handleRequest(RequestParameters param, HttpServletResponse 
response) throws IOException {
         long elapsedStart = System.nanoTime();
         final StringWriter stringWriter = new StringWriter();
         final PrintWriter resultWriter = new PrintWriter(stringWriter);
 
-        SessionConfig sessionConfig = createSessionConfig(request, 
resultWriter);
+        SessionConfig sessionConfig = createSessionConfig(param, resultWriter);
         response.setCharacterEncoding("utf-8");
         response.setContentType(MediaType.JSON.str());
 
@@ -404,10 +436,11 @@
 
         resultWriter.print("{\n");
         printRequestId(resultWriter);
+        printClientContextID(resultWriter, param);
         printSignature(resultWriter);
         printType(resultWriter, sessionConfig);
         try {
-            if (query == null || query.isEmpty()) {
+            if (param.statement == null || param.statement.isEmpty()) {
                 throw new AsterixException("Empty request, no statement 
provided");
             }
             IHyracksClientConnection hcc;
@@ -421,7 +454,7 @@
                     context.setAttribute(HYRACKS_DATASET_ATTR, hds);
                 }
             }
-            IParser parser = 
compilationProvider.getParserFactory().createParser(query);
+            IParser parser = 
compilationProvider.getParserFactory().createParser(param.statement);
             List<Statement> aqlStatements = parser.parse();
             MetadataManager.INSTANCE.init();
             IStatementExecutor translator = 
statementExecutorFactory.create(aqlStatements, sessionConfig,

-- 
To view, visit https://asterix-gerrit.ics.uci.edu/1201
To unsubscribe, visit https://asterix-gerrit.ics.uci.edu/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I1cc934d5dd984b476d4adb1755572d2e2f451985
Gerrit-PatchSet: 1
Gerrit-Project: asterixdb
Gerrit-Branch: master
Gerrit-Owner: Till Westmann <ti...@apache.org>

Reply via email to