Replace Servlets with Netty Based HTTP Servers
Change-Id: I3d552d4eb8c868535ca4c41cbcf7e352217b18ae
Reviewed-on: https://asterix-gerrit.ics.uci.edu/1429
Tested-by: Jenkins <jenkins@fulliautomatix.ics.uci.edu>
BAD: Jenkins <jenkins@fulliautomatix.ics.uci.edu>
Integration-Tests: Jenkins <jenkins@fulliautomatix.ics.uci.edu>
Reviewed-by: Till Westmann <tillw@apache.org>
diff --git a/asterixdb/asterix-app/pom.xml b/asterixdb/asterix-app/pom.xml
index f4667d0..77ca6ef 100644
--- a/asterixdb/asterix-app/pom.xml
+++ b/asterixdb/asterix-app/pom.xml
@@ -32,12 +32,10 @@
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
-
<properties>
<appendedResourcesDirectory>${basedir}/src/main/appended-resources</appendedResourcesDirectory>
<sonar.sources>pom.xml,src/main/java,src/main/resources</sonar.sources>
</properties>
-
<build>
<plugins>
<plugin>
@@ -62,7 +60,6 @@
</goals>
</execution>
</executions>
-
<configuration>
<!--
If you'd like to tell the plugin where your .git directory is,
@@ -80,7 +77,6 @@
at source assembly time) is used in this case -->
<failOnNoGitDirectory>false</failOnNoGitDirectory>
</configuration>
-
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
@@ -165,33 +161,33 @@
</plugin>
</plugins>
<pluginManagement>
- <plugins>
+ <plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>org.apache.asterix</groupId>
- <artifactId>asterix-test-datagenerator-maven-plugin</artifactId>
- <versionRange>[0.8.9-SNAPSHOT,)</versionRange>
- <goals>
- <goal>generate-testdata</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>org.apache.asterix</groupId>
+ <artifactId>asterix-test-datagenerator-maven-plugin</artifactId>
+ <versionRange>[0.8.9-SNAPSHOT,)</versionRange>
+ <goals>
+ <goal>generate-testdata</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore />
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
</pluginManagement>
</build>
<dependencies>
@@ -201,10 +197,6 @@
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-server</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
</dependency>
<dependency>
@@ -228,6 +220,10 @@
<artifactId>hyracks-api</artifactId>
</dependency>
<dependency>
+ <groupId>org.apache.hyracks</groupId>
+ <artifactId>hyracks-http</artifactId>
+ </dependency>
+ <dependency>
<groupId>org.apache.asterix</groupId>
<artifactId>asterix-algebra</artifactId>
<version>${project.version}</version>
@@ -484,5 +480,10 @@
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-all</artifactId>
+ <version>4.1.6.Final</version>
+ </dependency>
</dependencies>
-</project>
+</project>
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/APIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ApiServlet.java
similarity index 60%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/APIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ApiServlet.java
index b693407..c38e0a9 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/APIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ApiServlet.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
@@ -29,14 +29,11 @@
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import org.apache.asterix.app.result.ResultReader;
import org.apache.asterix.app.result.ResultUtil;
@@ -55,38 +52,48 @@
import org.apache.hyracks.api.client.IHyracksClientConnection;
import org.apache.hyracks.api.dataset.IHyracksDataset;
import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
-public class APIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(APIServlet.class.getName());
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class ApiServlet extends AbstractServlet {
+
+ private static final Logger LOGGER = Logger.getLogger(ApiServlet.class.getName());
public static final String HTML_STATEMENT_SEPARATOR = "<!-- BEGIN -->";
private final ILangCompilationProvider aqlCompilationProvider;
private final ILangCompilationProvider sqlppCompilationProvider;
- private final transient IStatementExecutorFactory statementExectorFactory;
+ private final IStatementExecutorFactory statementExectorFactory;
- public APIServlet(ILangCompilationProvider aqlCompilationProvider,
- ILangCompilationProvider sqlppCompilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ public ApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider aqlCompilationProvider, ILangCompilationProvider sqlppCompilationProvider,
+ IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths);
this.aqlCompilationProvider = aqlCompilationProvider;
this.sqlppCompilationProvider = sqlppCompilationProvider;
this.statementExectorFactory = statementExecutorFactory;
}
- @Override
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ public void doPost(IServletRequest request, IServletResponse response) {
// Query language
ILangCompilationProvider compilationProvider = "AQL".equals(request.getParameter("query-language"))
? aqlCompilationProvider : sqlppCompilationProvider;
IParserFactory parserFactory = compilationProvider.getParserFactory();
// Output format.
+ PrintWriter out = response.writer();
OutputFormat format;
- boolean csv_and_header = false;
+ boolean csvAndHeader = false;
String output = request.getParameter("output-format");
try {
format = OutputFormat.valueOf(output);
} catch (IllegalArgumentException e) {
- LOGGER.info(output + ": unsupported output-format, using " + OutputFormat.CLEAN_JSON + " instead");
+ LOGGER.log(Level.INFO,
+ output + ": unsupported output-format, using " + OutputFormat.CLEAN_JSON + " instead", e);
// Default output format
format = OutputFormat.CLEAN_JSON;
}
@@ -99,35 +106,37 @@
String printOptimizedLogicalPlanParam = request.getParameter("print-optimized-logical-plan");
String printJob = request.getParameter("print-job");
String executeQuery = request.getParameter("execute-query");
- response.setCharacterEncoding("utf-8");
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc;
- IHyracksDataset hds;
-
try {
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
-
- hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
- if (hds == null) {
- hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
- context.setAttribute(HYRACKS_DATASET_ATTR, hds);
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ try {
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ synchronized (ctx) {
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
+ ctx.put(HYRACKS_DATASET_ATTR, hds);
+ }
}
}
IParser parser = parserFactory.createParser(query);
List<Statement> aqlStatements = parser.parse();
SessionConfig sessionConfig = new SessionConfig(out, format, true, isSet(executeQuery), true);
sessionConfig.set(SessionConfig.FORMAT_HTML, true);
- sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, csv_and_header);
+ sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, csvAndHeader);
sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, isSet(wrapperArray));
sessionConfig.setOOBData(isSet(printExprParam), isSet(printRewrittenExprParam),
isSet(printLogicalPlanParam), isSet(printOptimizedLogicalPlanParam), isSet(printJob));
MetadataManager.INSTANCE.init();
IStatementExecutor translator =
statementExectorFactory.create(aqlStatements, sessionConfig, compilationProvider);
- double duration = 0;
+ double duration;
long startTime = System.currentTimeMillis();
translator.compileAndExecute(hcc, hds, IStatementExecutor.ResultDelivery.IMMEDIATE);
long endTime = System.currentTimeMillis();
@@ -143,63 +152,86 @@
}
}
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ public void doGet(IServletRequest request, IServletResponse response) {
String resourcePath = null;
- String requestURI = request.getRequestURI();
+ String requestURI = request.getHttpRequest().uri();
- if (requestURI.equals("/")) {
- response.setContentType("text/html");
+ if ("/".equals(requestURI)) {
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
resourcePath = "/webui/querytemplate.html";
} else {
resourcePath = requestURI;
}
- try (InputStream is = APIServlet.class.getResourceAsStream(resourcePath)) {
+ try (InputStream is = ApiServlet.class.getResourceAsStream(resourcePath)) {
if (is == null) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
-
// Special handler for font files and .png resources
if (resourcePath.endsWith(".png")) {
-
BufferedImage img = ImageIO.read(is);
- OutputStream outputStream = response.getOutputStream();
+ IServletResponse.setContentType(response, IServlet.ContentType.IMG_PNG);
+ OutputStream outputStream = response.outputStream();
String formatName = "png";
- response.setContentType("image/png");
ImageIO.write(img, formatName, outputStream);
outputStream.close();
return;
}
+ String type = IServlet.ContentType.mime(QueryWebInterfaceServlet.extension(resourcePath));
+ IServletResponse.setContentType(response, "".equals(type) ? IServlet.ContentType.TEXT_PLAIN : type,
+ IServlet.Encoding.UTF8);
+ writeOutput(response, is, resourcePath);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure handling request", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ }
- response.setCharacterEncoding("utf-8");
- InputStreamReader isr = new InputStreamReader(is);
+ private void writeOutput(IServletResponse response, InputStream is, String resourcePath) throws IOException {
+ try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
- BufferedReader br = new BufferedReader(isr);
String line;
try {
line = br.readLine();
} catch (NullPointerException e) {
- LOGGER.log(Level.WARNING, "NPE reading resource " + resourcePath
- + ", assuming JDK-8080094; returning 404", e);
+ LOGGER.log(Level.WARNING,
+ "NPE reading resource " + resourcePath + ", assuming JDK-8080094; returning 404", e);
// workaround lame JDK bug where a broken InputStream is returned in case the resourcePath is a
// directory; see https://bugs.openjdk.java.net/browse/JDK-8080094
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
-
while (line != null) {
sb.append(line);
line = br.readLine();
}
-
- PrintWriter out = response.getWriter();
+ PrintWriter out = response.writer();
out.println(sb.toString());
}
}
private static boolean isSet(String requestParameter) {
- return (requestParameter != null && requestParameter.equals("true"));
+ return requestParameter != null && "true".equals(requestParameter);
}
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ response.setStatus(HttpResponseStatus.OK);
+ if (request.getHttpRequest().method() == HttpMethod.GET) {
+ doGet(request, response);
+ } else if (request.getHttpRequest().method() == HttpMethod.POST) {
+ doPost(request, response);
+ } else {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ }
+ }
+
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterApiServlet.java
similarity index 78%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterApiServlet.java
index 988b5bb..6fd6c47 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterApiServlet.java
@@ -16,37 +16,40 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-import org.apache.asterix.common.config.AsterixProperties;
-import org.apache.asterix.common.config.ExternalProperties;
-import org.apache.asterix.common.utils.JSONUtil;
import org.apache.asterix.common.config.AbstractProperties;
import org.apache.asterix.common.config.ReplicationProperties;
+import org.apache.asterix.common.utils.JSONUtil;
import org.apache.asterix.runtime.util.ClusterStateManager;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class ClusterAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(ClusterAPIServlet.class.getName());
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+public class ClusterApiServlet extends AbstractServlet {
+
+ private static final Logger LOGGER = Logger.getLogger(ClusterApiServlet.class.getName());
+ private static final Pattern PARENT_DIR = Pattern.compile("/[^./]+/\\.\\./");
+ private static final Pattern REPLICATION_PROPERTY = Pattern.compile("^replication\\.");
protected static final String NODE_ID_KEY = "node_id";
protected static final String CONFIG_URI_KEY = "configUri";
protected static final String STATS_URI_KEY = "statsUri";
@@ -56,26 +59,19 @@
protected static final String VERSION_URI_KEY = "versionUri";
protected static final String DIAGNOSTICS_URI_KEY = "diagnosticsUri";
protected static final String REPLICATION_URI_KEY = "replicationUri";
- private static final Pattern PARENT_DIR = Pattern.compile("/[^./]+/\\.\\./");
- private static final Pattern REPLICATION_PROPERTY = Pattern.compile("^replication\\.");
private final ObjectMapper om = new ObjectMapper();
- @Override
- public final void doGet(HttpServletRequest request, HttpServletResponse response) {
- try {
- getUnsafe(request, response);
- } catch (IOException e) {
- LOGGER.log(Level.WARNING, "Unhandled IOException thrown from " + getClass().getName() + " get impl", e);
- }
+ public ClusterApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
}
- protected void getUnsafe(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
- PrintWriter responseWriter = response.getWriter();
+ protected void getUnsafe(IServletRequest request, IServletResponse response) throws IOException {
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
+ PrintWriter responseWriter = response.writer();
try {
ObjectNode json;
- switch (request.getPathInfo() == null ? "" : request.getPathInfo()) {
+ response.setStatus(HttpResponseStatus.OK);
+ switch (path(request)) {
case "":
json = getClusterStateJSON(request, "");
break;
@@ -88,13 +84,13 @@
default:
throw new IllegalArgumentException();
}
- response.setStatus(HttpServletResponse.SC_OK);
responseWriter.write(JSONUtil.convertNode(json));
} catch (IllegalArgumentException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
} catch (Exception e) {
LOGGER.log(Level.INFO, "exception thrown for " + request, e);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ responseWriter.write(e.toString());
}
responseWriter.flush();
}
@@ -128,13 +124,15 @@
return AbstractProperties.getImplementations();
}
- protected ObjectNode getClusterStateJSON(HttpServletRequest request, String pathToNode) {
+ protected ObjectNode getClusterStateJSON(IServletRequest request, String pathToNode) {
ObjectNode json = ClusterStateManager.INSTANCE.getClusterStateDescription();
Map<String, Object> allProperties = getAllClusterProperties();
json.putPOJO("config", allProperties);
ArrayNode ncs = (ArrayNode) json.get("ncs");
- final StringBuilder requestURL = new StringBuilder(request.getRequestURL());
+ final StringBuilder requestURL = new StringBuilder("http://");
+ requestURL.append(request.getHeader(HttpHeaderNames.HOST));
+ requestURL.append(request.getHttpRequest().uri());
if (requestURL.charAt(requestURL.length() - 1) != '/') {
requestURL.append('/');
}
@@ -175,4 +173,18 @@
}
return clusterURL;
}
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.GET) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ try {
+ getUnsafe(request, response);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Unhandled IOException thrown from " + getClass().getName() + " get impl", e);
+ }
+ }
+
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterCCDetailsAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterControllerDetailsApiServlet.java
similarity index 69%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterCCDetailsAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterControllerDetailsApiServlet.java
index 569d5a0..4419e8a 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterCCDetailsAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ClusterControllerDetailsApiServlet.java
@@ -16,61 +16,68 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import java.io.IOException;
import java.io.PrintWriter;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.hyracks.api.client.IHyracksClientConnection;
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class ClusterCCDetailsAPIServlet extends ClusterAPIServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(ClusterCCDetailsAPIServlet.class.getName());
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class ClusterControllerDetailsApiServlet extends ClusterApiServlet {
+
+ private static final Logger LOGGER = Logger.getLogger(ClusterControllerDetailsApiServlet.class.getName());
private final ObjectMapper om = new ObjectMapper();
+ public ClusterControllerDetailsApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
+
@Override
- protected void getUnsafe(HttpServletRequest request, HttpServletResponse response) throws IOException {
- PrintWriter responseWriter = response.getWriter();
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
+ protected void getUnsafe(IServletRequest request, IServletResponse response) throws IOException {
+ PrintWriter responseWriter = response.writer();
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
try {
ObjectNode json;
- if (request.getPathInfo() == null) {
+ response.setStatus(HttpResponseStatus.OK);
+ if ("".equals(path(request))) {
json = (ObjectNode) getClusterStateJSON(request, "../").get("cc");
} else {
json = processNode(request, hcc);
}
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
responseWriter.write(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(json));
} catch (IllegalArgumentException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
} catch (Exception e) {
LOGGER.log(Level.INFO, "exception thrown for " + request, e);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ responseWriter.write(e.toString());
}
responseWriter.flush();
}
- private ObjectNode processNode(HttpServletRequest request, IHyracksClientConnection hcc) throws Exception {
- String pathInfo = request.getPathInfo();
+ private ObjectNode processNode(IServletRequest request, IHyracksClientConnection hcc)
+ throws Exception {
+ String pathInfo = path(request);
if (pathInfo.endsWith("/")) {
throw new IllegalArgumentException();
}
String[] parts = pathInfo.substring(1).split("/");
- if (request.getPathInfo() == null) {
+ if ("".equals(pathInfo)) {
return (ObjectNode) getClusterStateJSON(request, "../../").get("cc");
} else if (parts.length == 1) {
switch (parts[0]) {
@@ -97,5 +104,4 @@
}
return (ObjectNode) om.readTree(dump);
}
-
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ConnectorAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ConnectorApiServlet.java
similarity index 79%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ConnectorAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ConnectorApiServlet.java
index 78801b8..d832672 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ConnectorAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ConnectorApiServlet.java
@@ -16,8 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
@@ -25,12 +24,10 @@
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.asterix.metadata.MetadataManager;
import org.apache.asterix.metadata.MetadataTransactionContext;
import org.apache.asterix.metadata.declared.MetadataProvider;
@@ -40,26 +37,47 @@
import org.apache.asterix.util.FlushDatasetUtils;
import org.apache.hyracks.api.client.IHyracksClientConnection;
import org.apache.hyracks.api.client.NodeControllerInfo;
+import org.apache.hyracks.api.io.FileSplit;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.apache.hyracks.api.io.FileSplit;
-/***
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+/**
* The REST API that takes a dataverse name and a dataset name as the input
* and returns an array of file splits (IP, file-path) of the dataset in LOSSLESS_JSON.
* It is mostly used by external runtime, e.g., Pregelix or IMRU to pull data
* in parallel from existing AsterixDB datasets.
- *
- * @author yingyi
*/
-public class ConnectorAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
+public class ConnectorApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(ConnectorApiServlet.class.getName());
+
+ public ConnectorApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
@Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- PrintWriter out = response.getWriter();
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.GET) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ response.setStatus(HttpResponseStatus.OK);
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ PrintWriter out = response.writer();
try {
ObjectMapper om = new ObjectMapper();
ObjectNode jsonResponse = om.createObjectNode();
@@ -71,13 +89,8 @@
out.flush();
return;
}
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc = null;
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
- }
-
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
// Metadata transaction begins.
MetadataManager.INSTANCE.init();
MetadataTransactionContext mdTxnCtx = MetadataManager.INSTANCE.beginTransaction();
@@ -120,7 +133,7 @@
out.write(jsonResponse.toString());
out.flush();
} catch (Exception e) {
- e.printStackTrace();
+ LOGGER.log(Level.WARNING, "Failure handling a request", e);
out.println(e.getMessage());
out.flush();
e.printStackTrace(out);
@@ -128,7 +141,7 @@
}
private void formResponseObject(ObjectNode jsonResponse, FileSplit[] fileSplits, ARecordType recordType,
- String primaryKeys, boolean temp, Map<String, NodeControllerInfo> nodeMap) throws Exception {
+ String primaryKeys, boolean temp, Map<String, NodeControllerInfo> nodeMap) {
ObjectMapper om = new ObjectMapper();
ArrayNode partititons = om.createArrayNode();
// Whether the dataset is temp or not
@@ -139,7 +152,7 @@
jsonResponse.set("type", recordType.toJSON());
// Generates file partitions.
for (FileSplit split : fileSplits) {
- String ipAddress = nodeMap.get(split.getNodeName()).getNetworkAddress().getAddress().toString();
+ String ipAddress = nodeMap.get(split.getNodeName()).getNetworkAddress().getAddress();
String path = split.getPath();
FilePartition partition = new FilePartition(ipAddress, path);
partititons.add(partition.toObjectNode());
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DDLAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DdlApiServlet.java
similarity index 66%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DDLAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DdlApiServlet.java
index 19a7609..bcc6914 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DDLAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DdlApiServlet.java
@@ -16,26 +16,26 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
-import javax.servlet.http.HttpServletRequest;
+import java.util.concurrent.ConcurrentMap;
import org.apache.asterix.compiler.provider.ILangCompilationProvider;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.translator.IStatementExecutorFactory;
+import org.apache.hyracks.http.server.IServletRequest;
-public class DDLAPIServlet extends RESTAPIServlet {
- private static final long serialVersionUID = 1L;
- private static final byte ALLOWED_CATEGORIES = Statement.Category.QUERY | Statement.Category.UPDATE
- | Statement.Category.DDL;
+public class DdlApiServlet extends RestApiServlet {
+ private static final byte ALLOWED_CATEGORIES =
+ Statement.Category.QUERY | Statement.Category.UPDATE | Statement.Category.DDL;
- public DDLAPIServlet(ILangCompilationProvider compilationProvider,
- IStatementExecutorFactory statementExecutorFactory) {
- super(compilationProvider, statementExecutorFactory);
+ public DdlApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths, compilationProvider, statementExecutorFactory);
}
@Override
- protected String getQueryParameter(HttpServletRequest request) {
+ protected String getQueryParameter(IServletRequest request) {
return request.getParameter("ddl");
}
@@ -48,4 +48,5 @@
protected String getErrorMessage() {
return "Invalid statement: Non-DDL statement %s to the DDL API.";
}
+
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DiagnosticsAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DiagnosticsApiServlet.java
similarity index 77%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DiagnosticsAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DiagnosticsApiServlet.java
index 4416d5c..d91352d 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/DiagnosticsAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/DiagnosticsApiServlet.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
@@ -27,56 +27,63 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
+
+import org.apache.asterix.api.http.servlet.ServletConstants;
import org.apache.asterix.runtime.util.AppContextInfo;
import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class DiagnosticsAPIServlet extends ClusterNodeDetailsAPIServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(DiagnosticsAPIServlet.class.getName());
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class DiagnosticsApiServlet extends NodeControllerDetailsApiServlet {
+ private static final Logger LOGGER = Logger.getLogger(DiagnosticsApiServlet.class.getName());
+
+ public DiagnosticsApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
@Override
- protected void getUnsafe(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
- PrintWriter responseWriter = response.getWriter();
+ protected void getUnsafe(IServletRequest request, IServletResponse response) throws IOException {
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
+ PrintWriter responseWriter = response.writer();
ObjectNode json;
ObjectMapper om = new ObjectMapper();
+ response.setStatus(HttpResponseStatus.OK);
om.enable(SerializationFeature.INDENT_OUTPUT);
try {
- if (request.getPathInfo() != null) {
+ if (!"".equals(path(request))) {
throw new IllegalArgumentException();
}
json = getClusterDiagnosticsJSON();
- response.setStatus(HttpServletResponse.SC_OK);
responseWriter.write(om.writerWithDefaultPrettyPrinter().writeValueAsString(json));
} catch (IllegalStateException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
+ response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
} catch (IllegalArgumentException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
} catch (Exception e) {
LOGGER.log(Level.INFO, "exception thrown for " + request, e);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ responseWriter.write(e.toString());
}
responseWriter.flush();
}
private ObjectNode getClusterDiagnosticsJSON() throws Exception {
ObjectMapper om = new ObjectMapper();
- final ServletContext context = getServletContext();
- IHyracksClientConnection hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
- ExecutorService executor = (ExecutorService) context.getAttribute(ServletConstants.EXECUTOR_SERVICE);
-
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ ExecutorService executor = (ExecutorService) ctx.get(ServletConstants.EXECUTOR_SERVICE);
Map<String, Future<ObjectNode>> ccFutureData = new HashMap<>();
ccFutureData.put("threaddump",
executor.submit(() -> fixupKeys((ObjectNode) om.readTree(hcc.getThreadDump(null)))));
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FeedServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FeedServlet.java
new file mode 100644
index 0000000..ac79088
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FeedServlet.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.api.http.server;
+
+import java.awt.image.BufferedImage;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.imageio.ImageIO;
+
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class FeedServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(FeedServlet.class.getName());
+
+ public FeedServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ try {
+ response.setStatus(HttpResponseStatus.OK);
+ String resourcePath;
+ String requestURI = request.getHttpRequest().uri();
+
+ if ("/".equals(requestURI)) {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML);
+ resourcePath = "/feed/home.html";
+ } else {
+ resourcePath = requestURI;
+ }
+
+ InputStream is = FeedServlet.class.getResourceAsStream(resourcePath);
+ if (is == null) {
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
+ return;
+ }
+
+ // Special handler for font files and .png resources
+ if (resourcePath.endsWith(".png")) {
+
+ BufferedImage img = ImageIO.read(is);
+ OutputStream outputStream = response.outputStream();
+ String formatName = "png";
+ IServletResponse.setContentType(response, IServlet.ContentType.IMG_PNG);
+ ImageIO.write(img, formatName, outputStream);
+ return;
+ }
+
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ InputStreamReader isr = new InputStreamReader(is);
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader(isr);
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line + "\n");
+ line = br.readLine();
+ }
+
+ PrintWriter out = response.writer();
+ out.println(sb.toString());
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure handling request", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ }
+}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FullAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FullApiServlet.java
similarity index 74%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FullAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FullApiServlet.java
index 0f86ec6..7788136 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FullAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/FullApiServlet.java
@@ -16,29 +16,24 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
-import javax.servlet.http.HttpServletRequest;
+import java.util.concurrent.ConcurrentMap;
import org.apache.asterix.compiler.provider.ILangCompilationProvider;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.translator.IStatementExecutorFactory;
+import org.apache.hyracks.http.server.IServletRequest;
-public class FullAPIServlet extends RESTAPIServlet {
+public class FullApiServlet extends RestApiServlet {
- private static final long serialVersionUID = 1L;
private static final String AQL_STMT_PARAM_NAME = "aql";
private static final byte ALLOWED_CATEGORIES = Statement.Category.QUERY | Statement.Category.UPDATE
| Statement.Category.DDL | Statement.Category.PROCEDURE;
- public FullAPIServlet(ILangCompilationProvider compilationProvider,
- IStatementExecutorFactory statementExecutorFactory) {
- super(compilationProvider, statementExecutorFactory);
- }
-
- @Override
- protected String getQueryParameter(HttpServletRequest request) {
- return request.getParameter(AQL_STMT_PARAM_NAME);
+ public FullApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths, compilationProvider, statementExecutorFactory);
}
@Override
@@ -50,4 +45,9 @@
protected String getErrorMessage() {
throw new IllegalStateException();
}
+
+ @Override
+ protected String getQueryParameter(IServletRequest request) {
+ return request.getParameter(AQL_STMT_PARAM_NAME);
+ }
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterNodeDetailsAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/NodeControllerDetailsApiServlet.java
similarity index 76%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterNodeDetailsAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/NodeControllerDetailsApiServlet.java
index d737ad8..c1423e7 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ClusterNodeDetailsAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/NodeControllerDetailsApiServlet.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
@@ -25,64 +25,64 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import org.apache.asterix.runtime.util.ClusterStateManager;
+import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-import org.apache.asterix.runtime.util.ClusterStateManager;
-import org.apache.hyracks.api.client.IHyracksClientConnection;
import com.fasterxml.jackson.databind.node.ArrayNode;
-
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class ClusterNodeDetailsAPIServlet extends ClusterAPIServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(ClusterNodeDetailsAPIServlet.class.getName());
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class NodeControllerDetailsApiServlet extends ClusterApiServlet {
+
+ private static final Logger LOGGER = Logger.getLogger(NodeControllerDetailsApiServlet.class.getName());
private final ObjectMapper om = new ObjectMapper();
- @Override
- public void init() throws ServletException{
+ public NodeControllerDetailsApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
om.enable(SerializationFeature.INDENT_OUTPUT);
}
@Override
- protected void getUnsafe(HttpServletRequest request, HttpServletResponse response) throws IOException {
- PrintWriter responseWriter = response.getWriter();
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
+ protected void getUnsafe(IServletRequest request, IServletResponse response) throws IOException {
+ PrintWriter responseWriter = response.writer();
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
try {
ObjectNode json;
- if (request.getPathInfo() == null) {
+ response.setStatus(HttpResponseStatus.OK);
+ if ("".equals(path(request))) {
json = om.createObjectNode();
json.set("ncs", getClusterStateJSON(request, "../").get("ncs"));
} else {
json = processNode(request, hcc);
}
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
responseWriter.write(om.writerWithDefaultPrettyPrinter().writeValueAsString(json));
} catch (IllegalStateException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
+ response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
} catch (IllegalArgumentException e) { // NOSONAR - exception not logged or rethrown
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
} catch (Exception e) {
LOGGER.log(Level.INFO, "exception thrown for " + request, e);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ responseWriter.write(e.toString());
}
responseWriter.flush();
}
- private ObjectNode processNode(HttpServletRequest request, IHyracksClientConnection hcc)
+ private ObjectNode processNode(IServletRequest request, IHyracksClientConnection hcc)
throws Exception {
- String pathInfo = request.getPathInfo();
+ String pathInfo = path(request);
if (pathInfo.endsWith("/")) {
throw new IllegalArgumentException();
}
@@ -126,11 +126,11 @@
}
}
- protected ObjectNode fixupKeys(ObjectNode json) {
+ protected ObjectNode fixupKeys(ObjectNode json) {
// TODO (mblow): generate the keys with _ to begin with
List<String> keys = new ArrayList<>();
- for (Iterator iter = json.fieldNames(); iter.hasNext(); ) {
- keys.add((String) iter.next());
+ for (Iterator<String> iter = json.fieldNames(); iter.hasNext();) {
+ keys.add(iter.next());
}
for (String key : keys) {
String newKey = key.replace('-', '_');
@@ -151,12 +151,12 @@
json.remove("rrd-ptr");
List<String> keys = new ArrayList<>();
- for (Iterator iter = json.fieldNames(); iter.hasNext(); ) {
- keys.add((String) iter.next());
+ for (Iterator<String> iter = json.fieldNames(); iter.hasNext();) {
+ keys.add(iter.next());
}
final ArrayNode gcNames = (ArrayNode) json.get("gc-names");
- final ArrayNode gcCollectionTimes = (ArrayNode) json.get("gc-collection-times");
+ final ArrayNode gcCollectionTimes = (ArrayNode) json.get("gc-collection-times");
final ArrayNode gcCollectionCounts = (ArrayNode) json.get("gc-collection-counts");
for (String key : keys) {
@@ -181,8 +181,8 @@
for (int i = 0; i < gcNames.size(); i++) {
ObjectNode gc = om.createObjectNode();
gc.set("name", gcNames.get(i));
- gc.set("collection-time", ((ArrayNode)gcCollectionTimes.get(i)).get(index));
- gc.set("collection-count", ((ArrayNode)gcCollectionCounts.get(i)).get(index));
+ gc.set("collection-time", ((ArrayNode) gcCollectionTimes.get(i)).get(index));
+ gc.set("collection-count", ((ArrayNode) gcCollectionCounts.get(i)).get(index));
gcs.add(gc);
}
json.set("gcs", gcs);
@@ -211,5 +211,4 @@
}
return (ObjectNode) om.readTree(dump);
}
-
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryApiServlet.java
similarity index 72%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryApiServlet.java
index cc70324..917d9a8 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryApiServlet.java
@@ -16,25 +16,25 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
-import javax.servlet.http.HttpServletRequest;
+import java.util.concurrent.ConcurrentMap;
import org.apache.asterix.compiler.provider.ILangCompilationProvider;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.translator.IStatementExecutorFactory;
+import org.apache.hyracks.http.server.IServletRequest;
-public class QueryAPIServlet extends RESTAPIServlet {
- private static final long serialVersionUID = 1L;
+public class QueryApiServlet extends RestApiServlet {
private static final byte ALLOWED_CATEGORIES = Statement.Category.QUERY;
- public QueryAPIServlet(ILangCompilationProvider compilationProvider,
- IStatementExecutorFactory queryTranslatorFactory) {
- super(compilationProvider, queryTranslatorFactory);
+ public QueryApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths, compilationProvider, statementExecutorFactory);
}
@Override
- protected String getQueryParameter(HttpServletRequest request) {
+ protected String getQueryParameter(IServletRequest request) {
return request.getParameter("query");
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryResultAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryResultApiServlet.java
similarity index 60%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryResultAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryResultApiServlet.java
index b250690..6240f51 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryResultAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryResultApiServlet.java
@@ -16,22 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
import java.io.IOException;
import java.io.PrintWriter;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.asterix.api.http.servlet.HyracksProperties;
import org.apache.asterix.app.result.ResultReader;
import org.apache.asterix.app.result.ResultUtil;
import org.apache.asterix.common.exceptions.AsterixException;
@@ -43,21 +39,42 @@
import org.apache.hyracks.api.dataset.ResultSetId;
import org.apache.hyracks.api.job.JobId;
import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class QueryResultAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = Logger.getLogger(QueryResultAPIServlet.class.getName());
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class QueryResultApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(QueryResultApiServlet.class.getName());
+
+ public QueryResultApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
@Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- int respCode = HttpServletResponse.SC_OK;
- response.setContentType("text/html"); // TODO this seems wrong ...
- response.setCharacterEncoding("utf-8");
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.GET) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ response.setStatus(HttpResponseStatus.OK);
+ // TODO this seems wrong ...
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
String strHandle = request.getParameter("handle");
- PrintWriter out = response.getWriter();
- ServletContext context = getServletContext();
+ PrintWriter out = response.writer();
IHyracksClientConnection hcc;
IHyracksDataset hds;
@@ -70,17 +87,20 @@
String strIP = hp.getHyracksIPAddress();
int port = hp.getHyracksPort();
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
- if (hcc == null) {
- hcc = new HyracksConnection(strIP, port);
- context.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
- }
-
- hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
- if (hds == null) {
- hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
- context.setAttribute(HYRACKS_DATASET_ATTR, hds);
+ hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hcc == null || hds == null) {
+ synchronized (ctx) {
+ hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hcc == null) {
+ hcc = new HyracksConnection(strIP, port);
+ ctx.put(HYRACKS_CONNECTION_ATTR, hcc);
+ }
+ if (hds == null) {
+ hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
+ ctx.put(HYRACKS_DATASET_ATTR, hds);
+ }
}
}
ObjectMapper om = new ObjectMapper();
@@ -88,7 +108,6 @@
ArrayNode handle = (ArrayNode) handleObj.get("handle");
JobId jobId = new JobId(handle.get(0).asLong());
ResultSetId rsId = new ResultSetId(handle.get(1).asLong());
-
ResultReader resultReader = new ResultReader(hds);
resultReader.open(jobId, rsId);
@@ -98,17 +117,17 @@
// way to send the same OutputFormat value here as was
// originally determined there. Need to save this value on
// some object that we can obtain here.
- SessionConfig sessionConfig = RESTAPIServlet.initResponse(request, response);
+ SessionConfig sessionConfig = RestApiServlet.initResponse(request, response);
ResultUtil.printResults(resultReader, sessionConfig, new Stats(), null);
} catch (Exception e) {
- respCode = HttpServletResponse.SC_BAD_REQUEST;
+ response.setStatus(HttpResponseStatus.BAD_REQUEST);
out.println(e.getMessage());
LOGGER.log(Level.WARNING, "Error retrieving result", e);
}
- response.setStatus(respCode);
if (out.checkError()) {
LOGGER.warning("Error flushing output writer");
}
}
+
}
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/server/QueryServiceServlet.java
similarity index 85%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryServiceServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryServiceServlet.java
index a0454fd..b302bab 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/server/QueryServiceServlet.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
@@ -27,20 +27,10 @@
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.asterix.app.result.ResultReader;
import org.apache.asterix.app.result.ResultUtil;
import org.apache.asterix.app.translator.QueryTranslator;
@@ -58,26 +48,54 @@
import org.apache.asterix.translator.IStatementExecutor.Stats;
import org.apache.asterix.translator.IStatementExecutorFactory;
import org.apache.asterix.translator.SessionConfig;
-import org.apache.commons.io.IOUtils;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.prettyprint.AlgebricksAppendable;
import org.apache.hyracks.api.client.IHyracksClientConnection;
import org.apache.hyracks.api.dataset.IHyracksDataset;
import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
-public class QueryServiceServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class QueryServiceServlet extends AbstractServlet {
private static final Logger LOGGER = Logger.getLogger(QueryServiceServlet.class.getName());
- private final transient ILangCompilationProvider compilationProvider;
- private final transient IStatementExecutorFactory statementExecutorFactory;
+ private final ILangCompilationProvider compilationProvider;
+ private final IStatementExecutorFactory statementExecutorFactory;
- public QueryServiceServlet(ILangCompilationProvider compilationProvider,
+ public QueryServiceServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider,
IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths);
this.compilationProvider = compilationProvider;
this.statementExecutorFactory = statementExecutorFactory;
}
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.POST) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ try {
+ handleRequest(getRequestParameters(request), response);
+ } catch (IOException e) {
+ // Servlet methods should not throw exceptions
+ // http://cwe.mitre.org/data/definitions/600.html
+ GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ }
+ }
+
public enum Parameter {
STATEMENT("statement"),
FORMAT("format"),
@@ -96,22 +114,6 @@
}
}
- private enum MediaType {
- CSV("text/csv"),
- JSON("application/json"),
- ADM("application/x-adm");
-
- private final String str;
-
- MediaType(String str) {
- this.str = str;
- }
-
- public String str() {
- return str;
- }
- }
-
private enum Attribute {
HEADER("header"),
LOSSLESS("lossless");
@@ -199,7 +201,7 @@
}
}
- enum TimeUnit {
+ public enum TimeUnit {
SEC("s", 9),
MILLI("ms", 6),
MICRO("µs", 3),
@@ -213,7 +215,7 @@
this.nanoDigits = nanoDigits;
}
- static String formatNanos(long nanoTime) {
+ public static String formatNanos(long nanoTime) {
final String strTime = String.valueOf(nanoTime);
final int len = strTime.length();
for (TimeUnit tu : TimeUnit.values()) {
@@ -277,13 +279,13 @@
private static SessionConfig.OutputFormat getFormat(String format) {
if (format != null) {
- if (format.startsWith(MediaType.CSV.str())) {
+ if (format.startsWith(IServlet.ContentType.CSV)) {
return SessionConfig.OutputFormat.CSV;
}
- if (format.equals(MediaType.ADM.str())) {
+ if (format.equals(IServlet.ContentType.APPLICATION_ADM)) {
return SessionConfig.OutputFormat.ADM;
}
- if (format.startsWith(MediaType.JSON.str())) {
+ if (format.startsWith(IServlet.ContentType.APPLICATION_JSON)) {
return Boolean.parseBoolean(getParameterValue(format, Attribute.LOSSLESS.str()))
? SessionConfig.OutputFormat.LOSSLESS_JSON : SessionConfig.OutputFormat.CLEAN_JSON;
}
@@ -308,7 +310,6 @@
}
};
-
SessionConfig.ResultDecorator resultPostfix = (AlgebricksAppendable app) -> app.append("\t,\n");
SessionConfig.ResultDecorator handlePrefix = new SessionConfig.ResultDecorator() {
@@ -324,8 +325,8 @@
SessionConfig.ResultDecorator handlePostfix = (AlgebricksAppendable app) -> app.append(",\n");
SessionConfig.OutputFormat format = getFormat(param.format);
- SessionConfig sessionConfig = new SessionConfig(resultWriter, format, resultPrefix, resultPostfix, handlePrefix,
- handlePostfix);
+ SessionConfig sessionConfig = new SessionConfig(resultWriter, format, resultPrefix, resultPostfix,
+ handlePrefix, handlePostfix);
sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, true);
sessionConfig.set(SessionConfig.FORMAT_INDENT_JSON, param.pretty);
sessionConfig.set(SessionConfig.FORMAT_QUOTE_RECORD,
@@ -370,10 +371,10 @@
private static void printType(PrintWriter pw, SessionConfig sessionConfig) {
switch (sessionConfig.fmt()) {
case ADM:
- printField(pw, ResultFields.TYPE.str(), MediaType.ADM.str());
+ printField(pw, ResultFields.TYPE.str(), IServlet.ContentType.APPLICATION_ADM);
break;
case CSV:
- String contentType = MediaType.CSV.str() + "; header="
+ String contentType = IServlet.ContentType.CSV + "; header="
+ (sessionConfig.is(SessionConfig.FORMAT_CSV_HEADER) ? "present" : "absent");
printField(pw, ResultFields.TYPE.str(), contentType);
break;
@@ -396,7 +397,6 @@
pw.print(ResultFields.ERRORS.str());
pw.print("\": [{ \n");
printField(pw, ErrorField.CODE.str(), "1");
-
final String msg = rootCause.getMessage();
printField(pw, ErrorField.MSG.str(), JSONUtil.escape(msg != null ? msg : rootCause.getClass().getSimpleName()),
addStack);
@@ -419,17 +419,6 @@
pw.print("\t}\n");
}
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
- try {
- handleRequest(getRequestParameters(request), response);
- } catch (IOException e) {
- // Servlet methods should not throw exceptions
- // http://cwe.mitre.org/data/definitions/600.html
- GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
- }
- }
-
private String getOptText(JsonNode node, String fieldName) {
final JsonNode value = node.get(fieldName);
return value != null ? value.asText() : null;
@@ -440,12 +429,12 @@
return value != null ? value.asBoolean() : defaultValue;
}
- private RequestParameters getRequestParameters(HttpServletRequest request) throws IOException {
- final String contentTypeParam = request.getContentType();
+ private RequestParameters getRequestParameters(IServletRequest request) throws IOException {
+ final String contentTypeParam = request.getHttpRequest().headers().get(HttpHeaderNames.CONTENT_TYPE);
int sep = contentTypeParam.indexOf(';');
final String contentType = sep < 0 ? contentTypeParam.trim() : contentTypeParam.substring(0, sep).trim();
RequestParameters param = new RequestParameters();
- if (MediaType.JSON.str().equals(contentType)) {
+ if (IServlet.ContentType.APPLICATION_JSON.equals(contentType)) {
try {
JsonNode jsonRequest = new ObjectMapper().readTree(getRequestBody(request));
param.statement = jsonRequest.get(Parameter.STATEMENT.str()).asText();
@@ -470,10 +459,8 @@
return param;
}
- private static String getRequestBody(HttpServletRequest request) throws IOException {
- StringWriter sw = new StringWriter();
- IOUtils.copy(request.getInputStream(), sw, StandardCharsets.UTF_8.name());
- return sw.toString();
+ private static String getRequestBody(IServletRequest request) throws IOException {
+ return request.getHttpRequest().content().toString(StandardCharsets.UTF_8);
}
private static QueryTranslator.ResultDelivery parseResultDelivery(String mode) {
@@ -486,7 +473,7 @@
}
}
- private void handleRequest(RequestParameters param, HttpServletResponse response) throws IOException {
+ private void handleRequest(RequestParameters param, IServletResponse response) throws IOException {
LOGGER.info(param.toString());
long elapsedStart = System.nanoTime();
final StringWriter stringWriter = new StringWriter();
@@ -495,10 +482,9 @@
QueryTranslator.ResultDelivery delivery = parseResultDelivery(param.mode);
SessionConfig sessionConfig = createSessionConfig(param, resultWriter);
- response.setCharacterEncoding("utf-8");
- response.setContentType(MediaType.JSON.str());
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
- int respCode = HttpServletResponse.SC_OK;
+ HttpResponseStatus status = HttpResponseStatus.OK;
Stats stats = new Stats();
long execStart = -1;
long execEnd = -1;
@@ -517,15 +503,15 @@
if (param.statement == null || param.statement.isEmpty()) {
throw new AsterixException("Empty request, no statement provided");
}
- IHyracksClientConnection hcc;
- IHyracksDataset hds;
- ServletContext context = getServletContext();
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
- hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
- if (hds == null) {
- hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
- context.setAttribute(HYRACKS_DATASET_ATTR, hds);
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ synchronized (ctx) {
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
+ ctx.put(HYRACKS_DATASET_ATTR, hds);
+ }
}
}
IParser parser = compilationProvider.getParserFactory().createParser(param.statement);
@@ -541,12 +527,12 @@
GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
printError(resultWriter, pe);
printStatus(resultWriter, ResultStatus.FATAL);
- respCode = HttpServletResponse.SC_BAD_REQUEST;
+ status = HttpResponseStatus.BAD_REQUEST;
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
printError(resultWriter, e);
printStatus(resultWriter, ResultStatus.FATAL);
- respCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
} finally {
if (execStart == -1) {
execEnd = -1;
@@ -562,9 +548,9 @@
GlobalConfig.ASTERIX_LOGGER.log(Level.FINE, result);
- response.setStatus(respCode);
- response.getWriter().print(result);
- if (response.getWriter().checkError()) {
+ response.setStatus(status);
+ response.writer().print(result);
+ if (response.writer().checkError()) {
LOGGER.warning("Error flushing output writer");
}
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryStatusApiServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryStatusApiServlet.java
new file mode 100644
index 0000000..197a39c
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryStatusApiServlet.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.api.http.server;
+
+import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
+import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.asterix.app.result.ResultReader;
+import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.api.dataset.IHyracksDataset;
+import org.apache.hyracks.api.dataset.ResultSetId;
+import org.apache.hyracks.api.job.JobId;
+import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class QueryStatusApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(QueryStatusApiServlet.class.getName());
+
+ public QueryStatusApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.GET) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ response.setStatus(HttpResponseStatus.OK);
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ String strHandle = request.getParameter("handle");
+ PrintWriter out = response.writer();
+ try {
+ IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ synchronized (ctx) {
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ hds = new HyracksDataset((IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR),
+ ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
+ ctx.put(HYRACKS_DATASET_ATTR, hds);
+ }
+ }
+ }
+ ObjectMapper om = new ObjectMapper();
+ JsonNode handleObj = om.readTree(strHandle);
+ JsonNode handle = handleObj.get("handle");
+ JobId jobId = new JobId(handle.get(0).asLong());
+ ResultSetId rsId = new ResultSetId(handle.get(1).asLong());
+
+ /* TODO(madhusudancs): We need to find a way to LOSSLESS_JSON serialize default format obtained from
+ * metadataProvider in the AQLTranslator and store it as part of the result handle.
+ */
+ ResultReader resultReader = new ResultReader(hds);
+ resultReader.open(jobId, rsId);
+
+ ObjectNode jsonResponse = om.createObjectNode();
+ String status;
+ switch (resultReader.getStatus()) {
+ case RUNNING:
+ status = "RUNNING";
+ break;
+ case SUCCESS:
+ status = "SUCCESS";
+ break;
+ default:
+ status = "ERROR";
+ break;
+ }
+ jsonResponse.put("status", status);
+ out.write(jsonResponse.toString());
+
+ } catch (Exception e) {
+ LOGGER.log(Level.SEVERE, "Failure handling a request", e);
+ out.println(e.getMessage());
+ e.printStackTrace(out);
+ }
+ }
+
+}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryWebInterfaceServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryWebInterfaceServlet.java
new file mode 100644
index 0000000..d924cf1
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/QueryWebInterfaceServlet.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.api.http.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.asterix.common.config.ExternalProperties;
+import org.apache.asterix.runtime.util.AppContextInfo;
+import org.apache.commons.io.IOUtils;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class QueryWebInterfaceServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(QueryWebInterfaceServlet.class.getName());
+
+ public QueryWebInterfaceServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ try {
+ if (request.getHttpRequest().method() == HttpMethod.GET) {
+ doGet(request, response);
+ } else if (request.getHttpRequest().method() == HttpMethod.POST) {
+ doPost(response);
+ } else {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ }
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure setting content type", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ }
+
+ private void doGet(IServletRequest request, IServletResponse response) throws IOException {
+ String resourcePath = null;
+ String requestURI = request.getHttpRequest().uri();
+ response.setStatus(HttpResponseStatus.OK);
+
+ if ("/".equals(requestURI)) {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_HTML);
+ resourcePath = "/queryui/queryui.html";
+ } else {
+ resourcePath = requestURI;
+ }
+
+ try (InputStream is = QueryWebInterfaceServlet.class.getResourceAsStream(resourcePath)) {
+ if (is == null) {
+ response.setStatus(HttpResponseStatus.NOT_FOUND);
+ return;
+ }
+ int i = resourcePath.lastIndexOf('.');
+ if (i >= 0) {
+ String extension = resourcePath.substring(i);
+ String mime = IServlet.ContentType.mime(extension);
+ if (mime != null) {
+ OutputStream out = response.outputStream();
+ IServletResponse.setContentType(response, mime);
+ try {
+ IOUtils.copy(is, out);
+ } catch (Exception e) {
+ LOGGER.log(Level.WARNING, "Failure copying response", e);
+ } finally {
+ if (out != null) {
+ IOUtils.closeQuietly(out);
+ }
+ IOUtils.closeQuietly(is);
+ }
+ return;
+ }
+ }
+ response.setStatus(HttpResponseStatus.BAD_REQUEST);
+ }
+ }
+
+ private void doPost(IServletResponse response) throws IOException {
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON, IServlet.Encoding.UTF8);
+ ExternalProperties externalProperties = AppContextInfo.INSTANCE.getExternalProperties();
+ response.setStatus(HttpResponseStatus.OK);
+ ObjectMapper om = new ObjectMapper();
+ ObjectNode obj = om.createObjectNode();
+ try {
+ PrintWriter out = response.writer();
+ obj.put("api_port", String.valueOf(externalProperties.getAPIServerPort()));
+ out.println(obj.toString());
+ return;
+ } catch (Exception e) {
+ LOGGER.log(Level.SEVERE, "Failure writing response", e);
+ }
+ try {
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ } catch (Exception e) {
+ LOGGER.log(Level.SEVERE, "Failure setting response status", e);
+ }
+ }
+
+ public static String extension(String path) {
+ int i = path.lastIndexOf('.');
+ return i < 1 ? "" : path.substring(i);
+ }
+}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/RestApiServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/RestApiServlet.java
new file mode 100644
index 0000000..c2d1d33
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/RestApiServlet.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.api.http.server;
+
+import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
+import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.asterix.app.result.ResultReader;
+import org.apache.asterix.app.result.ResultUtil;
+import org.apache.asterix.app.translator.QueryTranslator;
+import org.apache.asterix.common.config.GlobalConfig;
+import org.apache.asterix.common.exceptions.AsterixException;
+import org.apache.asterix.compiler.provider.ILangCompilationProvider;
+import org.apache.asterix.lang.aql.parser.TokenMgrError;
+import org.apache.asterix.lang.common.base.IParser;
+import org.apache.asterix.lang.common.base.IParserFactory;
+import org.apache.asterix.lang.common.base.Statement;
+import org.apache.asterix.metadata.MetadataManager;
+import org.apache.asterix.translator.IStatementExecutor;
+import org.apache.asterix.translator.IStatementExecutorFactory;
+import org.apache.asterix.translator.SessionConfig;
+import org.apache.asterix.translator.SessionConfig.OutputFormat;
+import org.apache.hyracks.algebricks.core.algebra.prettyprint.AlgebricksAppendable;
+import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.api.dataset.IHyracksDataset;
+import org.apache.hyracks.client.dataset.HyracksDataset;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public abstract class RestApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(RestApiServlet.class.getName());
+ private final ILangCompilationProvider compilationProvider;
+ private final IParserFactory parserFactory;
+ private final IStatementExecutorFactory statementExecutorFactory;
+
+ public RestApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths);
+ this.compilationProvider = compilationProvider;
+ this.parserFactory = compilationProvider.getParserFactory();
+ this.statementExecutorFactory = statementExecutorFactory;
+ }
+
+ /**
+ * Initialize the Content-Type of the response, and construct a
+ * SessionConfig with the appropriate output writer and output-format
+ * based on the Accept: header and other servlet parameters.
+ */
+ static SessionConfig initResponse(IServletRequest request, IServletResponse response) throws IOException {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_PLAIN, IServlet.Encoding.UTF8);
+
+ // CLEAN_JSON output is the default; most generally useful for a
+ // programmatic HTTP API
+ OutputFormat format = OutputFormat.CLEAN_JSON;
+ // First check the "output" servlet parameter.
+ String output = request.getParameter("output");
+ String accept = request.getHeader("Accept");
+ if (accept == null) {
+ accept = "";
+ }
+ if (output != null) {
+ if ("CSV".equals(output)) {
+ format = OutputFormat.CSV;
+ } else if ("ADM".equals(output)) {
+ format = OutputFormat.ADM;
+ }
+ } else {
+ // Second check the Accept: HTTP header.
+ if (accept.contains("application/x-adm")) {
+ format = OutputFormat.ADM;
+ } else if (accept.contains("text/csv")) {
+ format = OutputFormat.CSV;
+ }
+ }
+
+ // If it's JSON, check for the "lossless" flag
+
+ if (format == OutputFormat.CLEAN_JSON
+ && ("true".equals(request.getParameter("lossless")) || accept.contains("lossless=true"))) {
+ format = OutputFormat.LOSSLESS_JSON;
+ }
+
+ SessionConfig.ResultDecorator handlePrefix =
+ (AlgebricksAppendable app) -> app.append("{ \"").append("handle").append("\": ");
+ SessionConfig.ResultDecorator handlePostfix = (AlgebricksAppendable app) -> app.append(" }");
+
+ SessionConfig sessionConfig =
+ new SessionConfig(response.writer(), format, null, null, handlePrefix, handlePostfix);
+
+ // If it's JSON or ADM, check for the "wrapper-array" flag. Default is
+ // "true" for JSON and "false" for ADM. (Not applicable for CSV.)
+ boolean wrapperArray;
+ switch (format) {
+ case CLEAN_JSON:
+ case LOSSLESS_JSON:
+ wrapperArray = true;
+ break;
+ default:
+ wrapperArray = false;
+ break;
+ }
+ String wrapperParam = request.getParameter("wrapper-array");
+ if (wrapperParam != null) {
+ wrapperArray = Boolean.valueOf(wrapperParam);
+ } else if (accept.contains("wrap-array=true")) {
+ wrapperArray = true;
+ } else if (accept.contains("wrap-array=false")) {
+ wrapperArray = false;
+ }
+ sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, wrapperArray);
+ // Now that format is set, output the content-type
+ switch (format) {
+ case ADM:
+ IServletResponse.setContentType(response, "application/x-adm");
+ break;
+ case CLEAN_JSON:
+ // No need to reflect "clean-ness" in output type; fall through
+ case LOSSLESS_JSON:
+ IServletResponse.setContentType(response, "application/json");
+ break;
+ case CSV:
+ // Check for header parameter or in Accept:.
+ if ("present".equals(request.getParameter("header")) || accept.contains("header=present")) {
+ IServletResponse.setContentType(response, "text/csv; header=present");
+ sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, true);
+ } else {
+ IServletResponse.setContentType(response, "text/csv; header=absent");
+ }
+ break;
+ }
+ return sessionConfig;
+ }
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ try {
+ String query = query(request);
+ // enable cross-origin resource sharing
+ response.setHeader("Access-Control-Allow-Origin", "*");
+ response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
+
+ SessionConfig sessionConfig = initResponse(request, response);
+ QueryTranslator.ResultDelivery resultDelivery = whichResultDelivery(request);
+ try {
+ response.setStatus(HttpResponseStatus.OK);
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
+ IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ synchronized (ctx) {
+ hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
+ if (hds == null) {
+ hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
+ ctx.put(HYRACKS_DATASET_ATTR, hds);
+ }
+ }
+ }
+ IParser parser = parserFactory.createParser(query);
+ List<Statement> aqlStatements = parser.parse();
+ validate(aqlStatements);
+ MetadataManager.INSTANCE.init();
+ IStatementExecutor translator =
+ statementExecutorFactory.create(aqlStatements, sessionConfig, compilationProvider);
+ translator.compileAndExecute(hcc, hds, resultDelivery);
+ } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
+ GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
+ String errorMessage = ResultUtil.buildParseExceptionMessage(pe, query);
+ ObjectNode errorResp =
+ ResultUtil.getErrorResponse(2, errorMessage, "", ResultUtil.extractFullStackTrace(pe));
+ sessionConfig.out().write(new ObjectMapper().writeValueAsString(errorResp));
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ } catch (Exception e) {
+ GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ ResultUtil.apiErrorHandler(sessionConfig.out(), e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ }
+ } catch (Exception e) {
+ LOGGER.log(Level.WARNING, "Failure handling request", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ }
+
+ //TODO: Both Get and Post of this API must use the same parameter names
+ private String query(IServletRequest request) {
+ if (request.getHttpRequest().method() == HttpMethod.POST) {
+ return request.getHttpRequest().content().toString(StandardCharsets.UTF_8);
+ } else {
+ return getQueryParameter(request);
+ }
+ }
+
+ private void validate(List<Statement> aqlStatements) throws AsterixException {
+ for (Statement st : aqlStatements) {
+ if ((st.getCategory() & getAllowedCategories()) == 0) {
+ throw new AsterixException(String.format(getErrorMessage(), st.getKind()));
+ }
+ }
+ }
+
+ protected QueryTranslator.ResultDelivery whichResultDelivery(IServletRequest request) {
+ String mode = request.getParameter("mode");
+ if (mode != null) {
+ if ("asynchronous".equals(mode) || "async".equals(mode)) {
+ return QueryTranslator.ResultDelivery.ASYNC;
+ } else if ("asynchronous-deferred".equals(mode) || "deferred".equals(mode)) {
+ return QueryTranslator.ResultDelivery.DEFERRED;
+ }
+ }
+ return QueryTranslator.ResultDelivery.IMMEDIATE;
+ }
+
+ protected abstract String getQueryParameter(IServletRequest request);
+
+ protected abstract byte getAllowedCategories();
+
+ protected abstract String getErrorMessage();
+}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ShutdownAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ShutdownApiServlet.java
similarity index 68%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ShutdownAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ShutdownApiServlet.java
index d07166e..25be651 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/ShutdownAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/ShutdownApiServlet.java
@@ -16,42 +16,50 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
+import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
+import java.util.logging.Logger;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.asterix.common.config.GlobalConfig;
import org.apache.asterix.runtime.util.ClusterStateManager;
import org.apache.hyracks.api.client.IHyracksClientConnection;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-public class ShutdownAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class ShutdownApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(ShutdownApiServlet.class.getName());
public static final String NODE_ID_KEY = "node_id";
public static final String NCSERVICE_PID = "ncservice_pid";
public static final String INI = "ini";
public static final String PID = "pid";
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
+ public ShutdownApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.POST) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
boolean terminateNCServices = "true".equalsIgnoreCase(request.getParameter("all"));
Thread t = new Thread(() -> {
try {
@@ -61,9 +69,15 @@
}
}, "Shutdown Servlet Worker");
- response.setContentType("application/json");
- response.setCharacterEncoding("utf-8");
- response.setStatus(HttpServletResponse.SC_ACCEPTED);
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.APPLICATION_JSON,
+ IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure handling request", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ response.setStatus(HttpResponseStatus.ACCEPTED);
ObjectMapper om = new ObjectMapper();
ObjectNode jsonObject = om.createObjectNode();
try {
@@ -81,7 +95,7 @@
}
}
jsonObject.set("cluster", clusterState);
- final PrintWriter writer = response.getWriter();
+ final PrintWriter writer = response.writer();
writer.print(om.writeValueAsString(jsonObject));
writer.close();
} catch (Exception e) {
@@ -89,4 +103,5 @@
}
t.start();
}
+
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/UpdateAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/UpdateApiServlet.java
similarity index 72%
rename from asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/UpdateAPIServlet.java
rename to asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/UpdateApiServlet.java
index 1c62cdb..1c173d2 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/UpdateAPIServlet.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/UpdateApiServlet.java
@@ -16,25 +16,25 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.asterix.api.http.servlet;
+package org.apache.asterix.api.http.server;
-import javax.servlet.http.HttpServletRequest;
+import java.util.concurrent.ConcurrentMap;
import org.apache.asterix.compiler.provider.ILangCompilationProvider;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.translator.IStatementExecutorFactory;
+import org.apache.hyracks.http.server.IServletRequest;
-public class UpdateAPIServlet extends RESTAPIServlet {
- private static final long serialVersionUID = 1L;
+public class UpdateApiServlet extends RestApiServlet {
private static final byte ALLOWED_CATEGORIES = Statement.Category.QUERY | Statement.Category.UPDATE;
- public UpdateAPIServlet(ILangCompilationProvider compilationProvider,
- IStatementExecutorFactory statementExecutorFactory) {
- super(compilationProvider, statementExecutorFactory);
+ public UpdateApiServlet(ConcurrentMap<String, Object> ctx, String[] paths,
+ ILangCompilationProvider compilationProvider, IStatementExecutorFactory statementExecutorFactory) {
+ super(ctx, paths, compilationProvider, statementExecutorFactory);
}
@Override
- protected String getQueryParameter(HttpServletRequest request) {
+ protected String getQueryParameter(IServletRequest request) {
return request.getParameter("statements");
}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/VersionApiServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/VersionApiServlet.java
new file mode 100644
index 0000000..e5ceccc
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/server/VersionApiServlet.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.api.http.server;
+
+import static org.apache.asterix.api.http.servlet.ServletConstants.ASTERIX_BUILD_PROP_ATTR;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.asterix.runtime.util.AppContextInfo;
+import org.apache.hyracks.http.server.AbstractServlet;
+import org.apache.hyracks.http.server.IServlet;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class VersionApiServlet extends AbstractServlet {
+ private static final Logger LOGGER = Logger.getLogger(VersionApiServlet.class.getName());
+
+ public VersionApiServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ super(ctx, paths);
+ }
+
+ @Override
+ public void handle(IServletRequest request, IServletResponse response) {
+ if (request.getHttpRequest().method() != HttpMethod.GET) {
+ response.setStatus(HttpResponseStatus.METHOD_NOT_ALLOWED);
+ return;
+ }
+ response.setStatus(HttpResponseStatus.OK);
+ AppContextInfo props = (AppContextInfo) ctx.get(ASTERIX_BUILD_PROP_ATTR);
+ Map<String, String> buildProperties = props.getBuildProperties().getAllProps();
+ ObjectMapper om = new ObjectMapper();
+ ObjectNode responseObject = om.createObjectNode();
+ for (Map.Entry<String, String> e : buildProperties.entrySet()) {
+ responseObject.put(e.getKey(), e.getValue());
+ }
+ try {
+ IServletResponse.setContentType(response, IServlet.ContentType.TEXT_PLAIN, IServlet.Encoding.UTF8);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failure handling request", e);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ return;
+ }
+ PrintWriter responseWriter = response.writer();
+ responseWriter.write(responseObject.toString());
+ responseWriter.flush();
+ }
+
+}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FeedServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FeedServlet.java
deleted file mode 100644
index 6c8019d..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/FeedServlet.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.api.http.servlet;
-
-import java.awt.image.BufferedImage;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-
-import javax.imageio.ImageIO;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class FeedServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- String resourcePath = null;
- String requestURI = request.getRequestURI();
-
- if (requestURI.equals("/")) {
- response.setContentType("text/html");
- resourcePath = "/feed/home.html";
- } else {
- resourcePath = requestURI;
- }
-
- InputStream is = FeedServlet.class.getResourceAsStream(resourcePath);
- if (is == null) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
- return;
- }
-
- // Special handler for font files and .png resources
- if (resourcePath.endsWith(".png")) {
-
- BufferedImage img = ImageIO.read(is);
- OutputStream outputStream = response.getOutputStream();
- String formatName = "png";
- response.setContentType("image/png");
- ImageIO.write(img, formatName, outputStream);
- outputStream.close();
- return;
-
- }
-
- response.setCharacterEncoding("utf-8");
- InputStreamReader isr = new InputStreamReader(is);
- StringBuilder sb = new StringBuilder();
- BufferedReader br = new BufferedReader(isr);
- String line = br.readLine();
-
- while (line != null) {
- sb.append(line + "\n");
- line = br.readLine();
- }
-
- String outStr = null;
- outStr = sb.toString();
-
- PrintWriter out = response.getWriter();
- out.println(outStr);
- }
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryStatusAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryStatusAPIServlet.java
deleted file mode 100644
index 6d1b1b2..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryStatusAPIServlet.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.api.http.servlet;
-
-import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
-import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.asterix.app.result.ResultReader;
-import org.apache.hyracks.api.client.IHyracksClientConnection;
-import org.apache.hyracks.api.dataset.IHyracksDataset;
-import org.apache.hyracks.api.dataset.ResultSetId;
-import org.apache.hyracks.api.job.JobId;
-import org.apache.hyracks.client.dataset.HyracksDataset;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
-public class QueryStatusAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- String strHandle = request.getParameter("handle");
- PrintWriter out = response.getWriter();
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc;
- IHyracksDataset hds;
-
- try {
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
-
- hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
- if (hds == null) {
- hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
- context.setAttribute(HYRACKS_DATASET_ATTR, hds);
- }
- }
- ObjectMapper om = new ObjectMapper();
- JsonNode handleObj = om.readTree(strHandle);
- JsonNode handle = handleObj.get("handle");
- JobId jobId = new JobId(handle.get(0).asLong());
- ResultSetId rsId = new ResultSetId(handle.get(1).asLong());
-
- /* TODO(madhusudancs): We need to find a way to LOSSLESS_JSON serialize default format obtained from
- * metadataProvider in the AQLTranslator and store it as part of the result handle.
- */
- ResultReader resultReader = new ResultReader(hds);
- resultReader.open(jobId, rsId);
-
- ObjectNode jsonResponse = om.createObjectNode();
- String status;
- switch (resultReader.getStatus()) {
- case RUNNING:
- status = "RUNNING";
- break;
- case FAILED:
- status = "ERROR";
- break;
- case SUCCESS:
- status = "SUCCESS";
- break;
- default:
- status = "ERROR";
- break;
- }
- jsonResponse.put("status", status);
- out.write(jsonResponse.toString());
-
- } catch (Exception e) {
- out.println(e.getMessage());
- e.printStackTrace(out);
- }
- }
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryWebInterfaceServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryWebInterfaceServlet.java
deleted file mode 100644
index d3e5556..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/QueryWebInterfaceServlet.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.api.http.servlet;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.apache.asterix.common.config.ExternalProperties;
-import org.apache.asterix.runtime.util.AppContextInfo;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class QueryWebInterfaceServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static final HashMap<String, String> fileMimePair = new HashMap<>();
- private static final Log LOG = LogFactory.getLog(QueryWebInterfaceServlet.class);
-
- public QueryWebInterfaceServlet() {
- fileMimePair.put("png", "image/png");
- fileMimePair.put("eot", "application/vnd.ms-fontobject");
- fileMimePair.put("svg", "image/svg+xml\t");
- fileMimePair.put("ttf", "application/x-font-ttf");
- fileMimePair.put("woff", "application/x-font-woff");
- fileMimePair.put("woff2", "application/x-font-woff");
- fileMimePair.put("html", "text/html");
- fileMimePair.put("css", "text/css");
- fileMimePair.put("js", "application/javascript");
- }
-
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
- String resourcePath = null;
- String requestURI = request.getRequestURI();
-
- if ("/".equals(requestURI)) {
- response.setContentType("text/html");
- resourcePath = "/queryui/queryui.html";
- } else {
- resourcePath = requestURI;
- }
-
- try (InputStream is = APIServlet.class.getResourceAsStream(resourcePath)) {
- if (is == null) {
- try {
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
- } catch (IllegalStateException | IOException e) {
- LOG.error(e);
- }
- return;
- }
- // Multiple MIME type support
- for (Map.Entry<String, String> entry : fileMimePair.entrySet()) {
- OutputStream out = null;
- if (resourcePath.endsWith(entry.getKey())) {
- response.setContentType(entry.getValue());
- try {
- out = response.getOutputStream();
- IOUtils.copy(is, out);
-
- } catch (IOException e) {
- LOG.info(e);
- } finally {
-
- if (out != null) {
- IOUtils.closeQuietly(out);
- }
- IOUtils.closeQuietly(is);
-
- }
- return;
- }
- }
- try {
- response.sendError(HttpServletResponse.SC_BAD_REQUEST);
- } catch (IllegalStateException | IOException e) {
- LOG.error(e);
- }
- }
- }
-
- @Override
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setCharacterEncoding("utf-8");
- response.setContentType("application/json");
- ExternalProperties externalProperties = AppContextInfo.INSTANCE.getExternalProperties();
- ObjectMapper om = new ObjectMapper();
- ObjectNode obj = om.createObjectNode();
- try {
- PrintWriter out = response.getWriter();
- obj.put("api_port", String.valueOf(externalProperties.getAPIServerPort()));
- out.println(obj.toString());
- return;
- } catch (Exception e) {
- LOG.error(e);
- }
-
- try {
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- } catch (IllegalStateException | IOException e) {
- LOG.error(e);
- }
- }
-
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/RESTAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/RESTAPIServlet.java
deleted file mode 100644
index dd030b0..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/RESTAPIServlet.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.api.http.servlet;
-
-import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
-import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.logging.Level;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.asterix.app.result.ResultReader;
-import org.apache.asterix.app.result.ResultUtil;
-import org.apache.asterix.app.translator.QueryTranslator;
-import org.apache.asterix.common.config.GlobalConfig;
-import org.apache.asterix.common.exceptions.AsterixException;
-import org.apache.asterix.compiler.provider.ILangCompilationProvider;
-import org.apache.asterix.lang.aql.parser.TokenMgrError;
-import org.apache.asterix.lang.common.base.IParser;
-import org.apache.asterix.lang.common.base.IParserFactory;
-import org.apache.asterix.lang.common.base.Statement;
-import org.apache.asterix.metadata.MetadataManager;
-import org.apache.asterix.translator.IStatementExecutor;
-import org.apache.asterix.translator.IStatementExecutorFactory;
-import org.apache.asterix.translator.SessionConfig;
-import org.apache.asterix.translator.SessionConfig.OutputFormat;
-import org.apache.commons.io.IOUtils;
-import org.apache.hyracks.algebricks.core.algebra.prettyprint.AlgebricksAppendable;
-import org.apache.hyracks.api.client.IHyracksClientConnection;
-import org.apache.hyracks.api.dataset.IHyracksDataset;
-import org.apache.hyracks.client.dataset.HyracksDataset;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
-abstract class RESTAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- private final ILangCompilationProvider compilationProvider;
- private final IParserFactory parserFactory;
- private final transient IStatementExecutorFactory statementExecutorFactory;
-
- public RESTAPIServlet(ILangCompilationProvider compilationProvider,
- IStatementExecutorFactory statementExecutorFactory) {
- this.compilationProvider = compilationProvider;
- this.parserFactory = compilationProvider.getParserFactory();
- this.statementExecutorFactory = statementExecutorFactory;
- }
-
- /**
- * Initialize the Content-Type of the response, and construct a
- * SessionConfig with the appropriate output writer and output-format
- * based on the Accept: header and other servlet parameters.
- */
- static SessionConfig initResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.setCharacterEncoding("utf-8");
-
- // CLEAN_JSON output is the default; most generally useful for a
- // programmatic HTTP API
- OutputFormat format = OutputFormat.CLEAN_JSON;
-
- // First check the "output" servlet parameter.
- String output = request.getParameter("output");
- String accept = request.getHeader("Accept");
- if (accept == null) {
- accept = "";
- }
- if (output != null) {
- if (output.equals("CSV")) {
- format = OutputFormat.CSV;
- } else if (output.equals("ADM")) {
- format = OutputFormat.ADM;
- }
- } else {
- // Second check the Accept: HTTP header.
- if (accept.contains("application/x-adm")) {
- format = OutputFormat.ADM;
- } else if (accept.contains("text/csv")) {
- format = OutputFormat.CSV;
- }
- }
-
- // If it's JSON, check for the "lossless" flag
-
- if (format == OutputFormat.CLEAN_JSON
- && ("true".equals(request.getParameter("lossless")) || accept.contains("lossless=true"))) {
- format = OutputFormat.LOSSLESS_JSON;
- }
-
- SessionConfig.ResultDecorator handlePrefix = (AlgebricksAppendable app) -> app.append("{ \"").append("handle")
- .append("\": ");
- SessionConfig.ResultDecorator handlePostfix = (AlgebricksAppendable app) -> app.append(" }");
-
- SessionConfig sessionConfig = new SessionConfig(response.getWriter(), format, null, null, handlePrefix,
- handlePostfix);
-
- // If it's JSON or ADM, check for the "wrapper-array" flag. Default is
- // "true" for JSON and "false" for ADM. (Not applicable for CSV.)
- boolean wrapper_array;
- switch (format) {
- case CLEAN_JSON:
- case LOSSLESS_JSON:
- wrapper_array = true;
- break;
- default:
- wrapper_array = false;
- break;
- }
- String wrapper_param = request.getParameter("wrapper-array");
- if (wrapper_param != null) {
- wrapper_array = Boolean.valueOf(wrapper_param);
- } else if (accept.contains("wrap-array=true")) {
- wrapper_array = true;
- } else if (accept.contains("wrap-array=false")) {
- wrapper_array = false;
- }
- sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, wrapper_array);
-
- // Now that format is set, output the content-type
- switch (format) {
- case ADM:
- response.setContentType("application/x-adm");
- break;
- case CLEAN_JSON:
- // No need to reflect "clean-ness" in output type; fall through
- case LOSSLESS_JSON:
- response.setContentType("application/json");
- break;
- case CSV: {
- // Check for header parameter or in Accept:.
- if ("present".equals(request.getParameter("header")) || accept.contains("header=present")) {
- response.setContentType("text/csv; header=present");
- sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, true);
- } else {
- response.setContentType("text/csv; header=absent");
- }
- }
- }
-
- return sessionConfig;
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- StringWriter sw = new StringWriter();
- IOUtils.copy(request.getInputStream(), sw, StandardCharsets.UTF_8.name());
- String query = sw.toString();
- handleRequest(request, response, query);
- }
-
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- String query = getQueryParameter(request);
- handleRequest(request, response, query);
- }
-
- public void handleRequest(HttpServletRequest request, HttpServletResponse response, String query)
- throws IOException {
- // enable cross-origin resource sharing
- response.addHeader("Access-Control-Allow-Origin", "*");
- response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
-
- SessionConfig sessionConfig = initResponse(request, response);
- QueryTranslator.ResultDelivery resultDelivery = whichResultDelivery(request);
-
- ServletContext context = getServletContext();
- IHyracksClientConnection hcc;
- IHyracksDataset hds;
-
- try {
- synchronized (context) {
- hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
- hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
- if (hds == null) {
- hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
- context.setAttribute(HYRACKS_DATASET_ATTR, hds);
- }
- }
-
- IParser parser = parserFactory.createParser(query);
- List<Statement> aqlStatements = parser.parse();
- if (!containsForbiddenStatements(aqlStatements)) {
- MetadataManager.INSTANCE.init();
- IStatementExecutor translator =
- statementExecutorFactory.create(aqlStatements, sessionConfig, compilationProvider);
- translator.compileAndExecute(hcc, hds, resultDelivery);
- }
- } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
- GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
- String errorMessage = ResultUtil.buildParseExceptionMessage(pe, query);
- ObjectNode errorResp =
- ResultUtil.getErrorResponse(2, errorMessage, "", ResultUtil.extractFullStackTrace(pe));
- sessionConfig.out().write(new ObjectMapper().writeValueAsString(errorResp));
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- } catch (Exception e) {
- GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
- ResultUtil.apiErrorHandler(sessionConfig.out(), e);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- private boolean containsForbiddenStatements(List<Statement> aqlStatements) throws AsterixException {
- for (Statement st : aqlStatements) {
- if ((st.getCategory() & getAllowedCategories()) == 0) {
- throw new AsterixException(String.format(getErrorMessage(), st.getKind()));
- }
- }
- return false;
- }
-
- protected QueryTranslator.ResultDelivery whichResultDelivery(HttpServletRequest request) {
- String mode = request.getParameter("mode");
- if (mode != null) {
- if ("asynchronous".equals(mode) || "async".equals(mode)) {
- return QueryTranslator.ResultDelivery.ASYNC;
- } else if ("asynchronous-deferred".equals(mode) || "deferred".equals(mode)) {
- return QueryTranslator.ResultDelivery.DEFERRED;
- }
- }
- return QueryTranslator.ResultDelivery.IMMEDIATE;
- }
-
- protected abstract String getQueryParameter(HttpServletRequest request);
-
- protected abstract byte getAllowedCategories();
-
- protected abstract String getErrorMessage();
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/VersionAPIServlet.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/VersionAPIServlet.java
deleted file mode 100644
index 398a355..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/api/http/servlet/VersionAPIServlet.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.api.http.servlet;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.apache.asterix.runtime.util.AppContextInfo;
-
-import static org.apache.asterix.api.http.servlet.ServletConstants.ASTERIX_BUILD_PROP_ATTR;
-
-public class VersionAPIServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- ServletContext context = getServletContext();
- AppContextInfo props = (AppContextInfo) context.getAttribute(ASTERIX_BUILD_PROP_ATTR);
- Map<String, String> buildProperties = props.getBuildProperties().getAllProps();
- ObjectMapper om = new ObjectMapper();
- ObjectNode responseObject = om.createObjectNode();
- for (Map.Entry<String, String> e : buildProperties.entrySet()) {
- responseObject.put(e.getKey(), e.getValue());
- }
- response.setCharacterEncoding("utf-8");
- PrintWriter responseWriter = response.getWriter();
- responseWriter.write(responseObject.toString());
- response.setStatus(HttpServletResponse.SC_OK);
- responseWriter.flush();
- }
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/external/FeedWorkCollection.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/external/FeedWorkCollection.java
index f42beb3..6be7af9 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/external/FeedWorkCollection.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/external/FeedWorkCollection.java
@@ -88,7 +88,7 @@
DataverseDecl dataverseDecl = new DataverseDecl(
new Identifier(request.getReceivingFeedId().getDataverse()));
SubscribeFeedStatement subscribeStmt = new SubscribeFeedStatement(locations, request);
- List<Statement> statements = new ArrayList<Statement>();
+ List<Statement> statements = new ArrayList<>();
statements.add(dataverseDecl);
statements.add(subscribeStmt);
IStatementExecutor translator = qtFactory.create(statements, pc, compilationProvider);
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/result/ResultUtil.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/result/ResultUtil.java
index 80b8ffe..3afb653 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/result/ResultUtil.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/result/ResultUtil.java
@@ -33,8 +33,6 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.asterix.api.http.servlet.APIServlet;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.translator.IStatementExecutor.Stats;
import org.apache.asterix.translator.SessionConfig;
@@ -43,8 +41,9 @@
import org.apache.hyracks.algebricks.core.algebra.prettyprint.AlgebricksAppendable;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.log4j.Logger;
-import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class ResultUtil {
@@ -244,7 +243,7 @@
String errorTemplate = defaultTemplate;
try {
String resourcePath = "/webui/errortemplate_message.html";
- InputStream is = APIServlet.class.getResourceAsStream(resourcePath);
+ InputStream is = ResultUtil.class.getResourceAsStream(resourcePath);
InputStreamReader isr = new InputStreamReader(is);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/translator/QueryTranslator.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/translator/QueryTranslator.java
index f039271..d60ed37 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/translator/QueryTranslator.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/app/translator/QueryTranslator.java
@@ -46,7 +46,7 @@
import org.apache.asterix.active.IActiveEntityEventsListener;
import org.apache.asterix.algebra.extension.IExtensionStatement;
import org.apache.asterix.api.common.APIFramework;
-import org.apache.asterix.api.http.servlet.APIServlet;
+import org.apache.asterix.api.http.server.ApiServlet;
import org.apache.asterix.app.external.ExternalIndexingOperations;
import org.apache.asterix.app.external.FeedJoint;
import org.apache.asterix.app.external.FeedOperations;
@@ -284,7 +284,7 @@
try {
for (Statement stmt : statements) {
if (sessionConfig.is(SessionConfig.FORMAT_HTML)) {
- sessionConfig.out().println(APIServlet.HTML_STATEMENT_SEPARATOR);
+ sessionConfig.out().println(ApiServlet.HTML_STATEMENT_SEPARATOR);
}
validateOperation(activeDefaultDataverse, stmt);
rewriteStatement(stmt); // Rewrite the statement's AST.
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/drivers/AsterixWebServer.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/drivers/AsterixWebServer.java
deleted file mode 100644
index f0eac39..0000000
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/drivers/AsterixWebServer.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.asterix.drivers;
-
-import org.apache.asterix.api.http.servlet.APIServlet;
-import org.apache.asterix.app.translator.DefaultStatementExecutorFactory;
-import org.apache.asterix.compiler.provider.AqlCompilationProvider;
-import org.apache.asterix.compiler.provider.SqlppCompilationProvider;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-
-public class AsterixWebServer {
- public static void main(String[] args) throws Exception {
- Server server = new Server(8080);
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
- server.setHandler(context);
-
- context.addServlet(new ServletHolder(new APIServlet(new AqlCompilationProvider(),
- new SqlppCompilationProvider(), new DefaultStatementExecutorFactory())), "/*");
- server.start();
- server.join();
- }
-}
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/CCApplicationEntryPoint.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/CCApplicationEntryPoint.java
index 5756e7d..3a8852e 100644
--- a/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/CCApplicationEntryPoint.java
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/CCApplicationEntryPoint.java
@@ -21,7 +21,6 @@
import static org.apache.asterix.api.http.servlet.ServletConstants.ASTERIX_BUILD_PROP_ATTR;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
-import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -29,24 +28,24 @@
import javax.servlet.Servlet;
import org.apache.asterix.active.ActiveLifecycleListener;
-import org.apache.asterix.api.http.servlet.APIServlet;
-import org.apache.asterix.api.http.servlet.ClusterAPIServlet;
-import org.apache.asterix.api.http.servlet.ClusterCCDetailsAPIServlet;
-import org.apache.asterix.api.http.servlet.ClusterNodeDetailsAPIServlet;
-import org.apache.asterix.api.http.servlet.ConnectorAPIServlet;
-import org.apache.asterix.api.http.servlet.DDLAPIServlet;
-import org.apache.asterix.api.http.servlet.DiagnosticsAPIServlet;
-import org.apache.asterix.api.http.servlet.FeedServlet;
-import org.apache.asterix.api.http.servlet.FullAPIServlet;
-import org.apache.asterix.api.http.servlet.QueryAPIServlet;
-import org.apache.asterix.api.http.servlet.QueryResultAPIServlet;
-import org.apache.asterix.api.http.servlet.QueryServiceServlet;
-import org.apache.asterix.api.http.servlet.QueryStatusAPIServlet;
-import org.apache.asterix.api.http.servlet.QueryWebInterfaceServlet;
+import org.apache.asterix.api.http.server.ApiServlet;
+import org.apache.asterix.api.http.server.FullApiServlet;
+import org.apache.asterix.api.http.server.ClusterApiServlet;
+import org.apache.asterix.api.http.server.ClusterControllerDetailsApiServlet;
+import org.apache.asterix.api.http.server.ConnectorApiServlet;
+import org.apache.asterix.api.http.server.DdlApiServlet;
+import org.apache.asterix.api.http.server.DiagnosticsApiServlet;
+import org.apache.asterix.api.http.server.FeedServlet;
+import org.apache.asterix.api.http.server.NodeControllerDetailsApiServlet;
+import org.apache.asterix.api.http.server.QueryApiServlet;
+import org.apache.asterix.api.http.server.QueryResultApiServlet;
+import org.apache.asterix.api.http.server.QueryServiceServlet;
+import org.apache.asterix.api.http.server.QueryStatusApiServlet;
+import org.apache.asterix.api.http.server.QueryWebInterfaceServlet;
+import org.apache.asterix.api.http.server.ShutdownApiServlet;
+import org.apache.asterix.api.http.server.UpdateApiServlet;
+import org.apache.asterix.api.http.server.VersionApiServlet;
import org.apache.asterix.api.http.servlet.ServletConstants;
-import org.apache.asterix.api.http.servlet.ShutdownAPIServlet;
-import org.apache.asterix.api.http.servlet.UpdateAPIServlet;
-import org.apache.asterix.api.http.servlet.VersionAPIServlet;
import org.apache.asterix.app.cc.CompilerExtensionManager;
import org.apache.asterix.app.cc.ResourceIdManager;
import org.apache.asterix.app.external.ExternalLibraryUtils;
@@ -55,7 +54,7 @@
import org.apache.asterix.common.config.ExternalProperties;
import org.apache.asterix.common.config.MetadataProperties;
import org.apache.asterix.common.library.ILibraryManager;
-import org.apache.asterix.common.utils.ServletUtil.Servlets;
+import org.apache.asterix.common.utils.LetUtil.Lets;
import org.apache.asterix.external.library.ExternalLibraryManager;
import org.apache.asterix.messaging.CCMessageBroker;
import org.apache.asterix.metadata.MetadataManager;
@@ -73,7 +72,8 @@
import org.apache.hyracks.api.messages.IMessageBroker;
import org.apache.hyracks.control.cc.ClusterControllerService;
import org.apache.hyracks.control.common.controllers.CCConfig;
-import org.eclipse.jetty.server.Server;
+import org.apache.hyracks.http.server.HttpServer;
+import org.apache.hyracks.http.server.IServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
@@ -81,13 +81,11 @@
public class CCApplicationEntryPoint implements ICCApplicationEntryPoint {
private static final Logger LOGGER = Logger.getLogger(CCApplicationEntryPoint.class.getName());
-
- private List<Server> servers;
-
private static IAsterixStateProxy proxy;
protected ICCApplicationContext appCtx;
protected CompilerExtensionManager ccExtensionManager;
private IJobCapacityController jobCapacityController;
+ protected WebManager webManager;
@Override
public void start(ICCApplicationContext ccAppCtx, String[] args) throws Exception {
@@ -124,14 +122,11 @@
AppContextInfo.INSTANCE.getCCApplicationContext()
.addJobLifecycleListener(ActiveLifecycleListener.INSTANCE);
- servers = configureServers();
-
- for (Server server : servers) {
- server.start();
- }
-
+ // create event loop groups
+ webManager = new WebManager();
+ configureServers();
+ webManager.start();
ClusterManagerProvider.getClusterManager().registerSubscriber(GlobalRecoveryManager.instance());
-
ccAppCtx.addClusterLifecycleListener(ClusterLifecycleListener.INSTANCE);
ccAppCtx.setMessageBroker(messageBroker);
@@ -142,15 +137,11 @@
return AppContextInfo.INSTANCE.getExtensionProperties().getExtensions();
}
- protected List<Server> configureServers() throws Exception {
- ExternalProperties externalProperties = AppContextInfo.INSTANCE.getExternalProperties();
-
- List<Server> serverList = new ArrayList<>();
- serverList.add(setupWebServer(externalProperties));
- serverList.add(setupJSONAPIServer(externalProperties));
- serverList.add(setupFeedServer(externalProperties));
- serverList.add(setupQueryWebServer(externalProperties));
- return serverList;
+ protected void configureServers() throws Exception {
+ webManager.add(setupWebServer(AppContextInfo.INSTANCE.getExternalProperties()));
+ webManager.add(setupJSONAPIServer(AppContextInfo.INSTANCE.getExternalProperties()));
+ webManager.add(setupFeedServer(AppContextInfo.INSTANCE.getExternalProperties()));
+ webManager.add(setupQueryWebServer(AppContextInfo.INSTANCE.getExternalProperties()));
}
@Override
@@ -160,14 +151,7 @@
LOGGER.info("Stopping Asterix cluster controller");
}
AsterixStateProxy.unregisterRemoteObject();
- // Stop servers
- for (Server server : servers) {
- server.stop();
- }
- // Make sure servers are stopped before proceeding
- for (Server server : servers) {
- server.join();
- }
+ webManager.stop();
}
protected IHyracksClientConnection getNewHyracksClientConnection() throws Exception {
@@ -176,77 +160,62 @@
return new HyracksConnection(strIP, port);
}
- protected Server setupWebServer(ExternalProperties externalProperties) throws Exception {
-
- Server webServer = new Server(externalProperties.getWebInterfacePort());
-
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
-
+ protected HttpServer setupWebServer(ExternalProperties externalProperties) throws Exception {
+ HttpServer webServer = new HttpServer(webManager.getBosses(), webManager.getWorkers(), externalProperties
+ .getWebInterfacePort());
IHyracksClientConnection hcc = getNewHyracksClientConnection();
- context.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
-
- webServer.setHandler(context);
- context.addServlet(new ServletHolder(new APIServlet(ccExtensionManager.getAqlCompilationProvider(),
- ccExtensionManager.getSqlppCompilationProvider(), ccExtensionManager.getQueryTranslatorFactory())),
- "/*");
-
+ webServer.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
+ webServer.addLet(new ApiServlet(webServer.ctx(), new String[] { "/*" }, ccExtensionManager
+ .getAqlCompilationProvider(), ccExtensionManager.getSqlppCompilationProvider(), ccExtensionManager
+ .getQueryTranslatorFactory()));
return webServer;
}
- protected Server setupJSONAPIServer(ExternalProperties externalProperties) throws Exception {
- Server jsonAPIServer = new Server(externalProperties.getAPIServerPort());
-
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
-
+ protected HttpServer setupJSONAPIServer(ExternalProperties externalProperties) throws Exception {
+ HttpServer jsonAPIServer = new HttpServer(webManager.getBosses(), webManager.getWorkers(), externalProperties
+ .getAPIServerPort());
IHyracksClientConnection hcc = getNewHyracksClientConnection();
- context.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
- context.setAttribute(ASTERIX_BUILD_PROP_ATTR, AppContextInfo.INSTANCE);
- context.setAttribute(ServletConstants.EXECUTOR_SERVICE,
+ jsonAPIServer.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
+ jsonAPIServer.setAttribute(ASTERIX_BUILD_PROP_ATTR, AppContextInfo.INSTANCE);
+ jsonAPIServer.setAttribute(ServletConstants.EXECUTOR_SERVICE,
((ClusterControllerService) appCtx.getControllerService()).getExecutor());
- jsonAPIServer.setHandler(context);
-
// AQL rest APIs.
- addServlet(context, Servlets.AQL_QUERY);
- addServlet(context, Servlets.AQL_UPDATE);
- addServlet(context, Servlets.AQL_DDL);
- addServlet(context, Servlets.AQL);
+ addLet(jsonAPIServer, Lets.AQL_QUERY);
+ addLet(jsonAPIServer, Lets.AQL_UPDATE);
+ addLet(jsonAPIServer, Lets.AQL_DDL);
+ addLet(jsonAPIServer, Lets.AQL);
// SQL+x+ rest APIs.
- addServlet(context, Servlets.SQLPP_QUERY);
- addServlet(context, Servlets.SQLPP_UPDATE);
- addServlet(context, Servlets.SQLPP_DDL);
- addServlet(context, Servlets.SQLPP);
+ addLet(jsonAPIServer, Lets.SQLPP_QUERY);
+ addLet(jsonAPIServer, Lets.SQLPP_UPDATE);
+ addLet(jsonAPIServer, Lets.SQLPP_DDL);
+ addLet(jsonAPIServer, Lets.SQLPP);
// Other APIs.
- addServlet(context, Servlets.QUERY_STATUS);
- addServlet(context, Servlets.QUERY_RESULT);
- addServlet(context, Servlets.QUERY_SERVICE);
- addServlet(context, Servlets.CONNECTOR);
- addServlet(context, Servlets.SHUTDOWN);
- addServlet(context, Servlets.VERSION);
- addServlet(context, Servlets.CLUSTER_STATE);
- addServlet(context, Servlets.CLUSTER_STATE_NODE_DETAIL); // this must not precede add of CLUSTER_STATE
- addServlet(context, Servlets.CLUSTER_STATE_CC_DETAIL); // this must not precede add of CLUSTER_STATE
- addServlet(context, Servlets.DIAGNOSTICS);
-
+ addLet(jsonAPIServer, Lets.QUERY_STATUS);
+ addLet(jsonAPIServer, Lets.QUERY_RESULT);
+ addLet(jsonAPIServer, Lets.QUERY_SERVICE);
+ addLet(jsonAPIServer, Lets.CONNECTOR);
+ addLet(jsonAPIServer, Lets.SHUTDOWN);
+ addLet(jsonAPIServer, Lets.VERSION);
+ addLet(jsonAPIServer, Lets.CLUSTER_STATE);
+ addLet(jsonAPIServer, Lets.CLUSTER_STATE_NODE_DETAIL); // this must not precede add of CLUSTER_STATE
+ addLet(jsonAPIServer, Lets.CLUSTER_STATE_CC_DETAIL); // this must not precede add of CLUSTER_STATE
+ addLet(jsonAPIServer, Lets.DIAGNOSTICS);
return jsonAPIServer;
}
- protected Server setupQueryWebServer(ExternalProperties externalProperties) throws Exception {
+ protected void addLet(HttpServer server, Lets let) {
+ server.addLet(createServLet(server, let, let.getPath()));
+ }
- Server queryWebServer = new Server(externalProperties.getQueryWebInterfacePort());
-
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
-
+ protected HttpServer setupQueryWebServer(ExternalProperties externalProperties) throws Exception {
+ HttpServer queryWebServer = new HttpServer(webManager.getBosses(), webManager.getWorkers(), externalProperties
+ .getQueryWebInterfacePort());
IHyracksClientConnection hcc = getNewHyracksClientConnection();
- context.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
-
- queryWebServer.setHandler(context);
- context.addServlet(new ServletHolder(new QueryWebInterfaceServlet()), "/*");
+ queryWebServer.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
+ queryWebServer.addLet(new QueryWebInterfaceServlet(queryWebServer.ctx(), new String[] { "/*" }));
return queryWebServer;
}
@@ -259,77 +228,66 @@
context.getServletHandler().addServletMapping(mapping);
}
- protected void addServlet(ServletContextHandler context, Servlets key) {
- addServlet(context, createServlet(key), key.getPath());
+ protected HttpServer setupFeedServer(ExternalProperties externalProperties) throws Exception {
+ HttpServer feedServer = new HttpServer(webManager.getBosses(), webManager.getWorkers(), externalProperties
+ .getFeedServerPort());
+ feedServer.setAttribute(HYRACKS_CONNECTION_ATTR, getNewHyracksClientConnection());
+ feedServer.addLet(new FeedServlet(feedServer.ctx(), new String[] { "/" }));
+ return feedServer;
}
- protected Servlet createServlet(Servlets key) {
+ protected IServlet createServLet(HttpServer server, Lets key, String... paths) {
switch (key) {
case AQL:
- return new FullAPIServlet(ccExtensionManager.getAqlCompilationProvider(),
+ return new FullApiServlet(server.ctx(), paths, ccExtensionManager.getAqlCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case AQL_QUERY:
- return new QueryAPIServlet(ccExtensionManager.getAqlCompilationProvider(),
+ return new QueryApiServlet(server.ctx(), paths, ccExtensionManager.getAqlCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case AQL_UPDATE:
- return new UpdateAPIServlet(ccExtensionManager.getAqlCompilationProvider(),
+ return new UpdateApiServlet(server.ctx(), paths, ccExtensionManager.getAqlCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case AQL_DDL:
- return new DDLAPIServlet(ccExtensionManager.getAqlCompilationProvider(),
+ return new DdlApiServlet(server.ctx(), paths, ccExtensionManager.getAqlCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case SQLPP:
- return new FullAPIServlet(ccExtensionManager.getSqlppCompilationProvider(),
+ return new FullApiServlet(server.ctx(), paths, ccExtensionManager.getSqlppCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case SQLPP_QUERY:
- return new QueryAPIServlet(ccExtensionManager.getSqlppCompilationProvider(),
+ return new QueryApiServlet(server.ctx(), paths, ccExtensionManager.getSqlppCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case SQLPP_UPDATE:
- return new UpdateAPIServlet(ccExtensionManager.getSqlppCompilationProvider(),
+ return new UpdateApiServlet(server.ctx(), paths, ccExtensionManager.getSqlppCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case SQLPP_DDL:
- return new DDLAPIServlet(ccExtensionManager.getSqlppCompilationProvider(),
+ return new DdlApiServlet(server.ctx(), paths, ccExtensionManager.getSqlppCompilationProvider(),
ccExtensionManager.getQueryTranslatorFactory());
case QUERY_STATUS:
- return new QueryStatusAPIServlet();
+ return new QueryStatusApiServlet(server.ctx(), paths);
case QUERY_RESULT:
- return new QueryResultAPIServlet();
+ return new QueryResultApiServlet(server.ctx(), paths);
case QUERY_SERVICE:
- return new QueryServiceServlet(ccExtensionManager.getSqlppCompilationProvider(),
- ccExtensionManager.getQueryTranslatorFactory());
+ return new QueryServiceServlet(server.ctx(), paths, ccExtensionManager
+ .getSqlppCompilationProvider(), ccExtensionManager.getQueryTranslatorFactory());
case CONNECTOR:
- return new ConnectorAPIServlet();
+ return new ConnectorApiServlet(server.ctx(), paths);
case SHUTDOWN:
- return new ShutdownAPIServlet();
+ return new ShutdownApiServlet(server.ctx(), paths);
case VERSION:
- return new VersionAPIServlet();
+ return new VersionApiServlet(server.ctx(), paths);
case CLUSTER_STATE:
- return new ClusterAPIServlet();
+ return new ClusterApiServlet(server.ctx(), paths);
case CLUSTER_STATE_NODE_DETAIL:
- return new ClusterNodeDetailsAPIServlet();
+ return new NodeControllerDetailsApiServlet(server.ctx(), paths);
case CLUSTER_STATE_CC_DETAIL:
- return new ClusterCCDetailsAPIServlet();
+ return new ClusterControllerDetailsApiServlet(server.ctx(), paths);
case DIAGNOSTICS:
- return new DiagnosticsAPIServlet();
+ return new DiagnosticsApiServlet(server.ctx(), paths);
default:
throw new IllegalStateException(String.valueOf(key));
}
}
- protected Server setupFeedServer(ExternalProperties externalProperties) throws Exception {
- Server feedServer = new Server(externalProperties.getFeedServerPort());
-
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
-
- IHyracksClientConnection hcc = getNewHyracksClientConnection();
- context.setAttribute(HYRACKS_CONNECTION_ATTR, hcc);
-
- feedServer.setHandler(context);
- context.addServlet(new ServletHolder(new FeedServlet()), "/");
-
- return feedServer;
- }
-
@Override
public void startupCompleted() throws Exception {
ClusterManagerProvider.getClusterManager().notifyStartupCompleted();
diff --git a/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/WebManager.java b/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/WebManager.java
new file mode 100644
index 0000000..070a530
--- /dev/null
+++ b/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/WebManager.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.asterix.hyracks.bootstrap;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hyracks.http.server.HttpServer;
+
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+
+public class WebManager {
+ private final List<HttpServer> servers;
+ private final EventLoopGroup bosses;
+ private final EventLoopGroup workers;
+
+ public WebManager() {
+ servers = new ArrayList<>();
+ bosses = new NioEventLoopGroup(1);
+ workers = new NioEventLoopGroup();
+ }
+
+ public List<HttpServer> getServers() {
+ return servers;
+ }
+
+ public EventLoopGroup getBosses() {
+ return bosses;
+ }
+
+ public EventLoopGroup getWorkers() {
+ return workers;
+ }
+
+ public void start() throws Exception {
+ for (HttpServer server : servers) {
+ server.start();
+ }
+ }
+
+ public void stop() throws Exception {
+ for (HttpServer server : servers) {
+ server.stop();
+ }
+ workers.shutdownGracefully().sync();
+ bosses.shutdownGracefully().sync();
+ }
+
+ public void add(HttpServer server) {
+ servers.add(server);
+ }
+}
diff --git a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorAPIServletTest.java b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorApiLetTest.java
similarity index 84%
rename from asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorAPIServletTest.java
rename to asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorApiLetTest.java
index 41785e5..b1fdab5 100644
--- a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorAPIServletTest.java
+++ b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/ConnectorApiLetTest.java
@@ -19,25 +19,16 @@
package org.apache.asterix.api.http.servlet;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import junit.extensions.PA;
+import org.apache.asterix.api.http.server.ConnectorApiServlet;
import org.apache.asterix.metadata.MetadataManager;
import org.apache.asterix.metadata.MetadataTransactionContext;
import org.apache.asterix.metadata.declared.MetadataProvider;
@@ -52,10 +43,20 @@
import org.apache.hyracks.api.comm.NetworkAddress;
import org.apache.hyracks.api.io.FileSplit;
import org.apache.hyracks.api.io.ManagedFileSplit;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
import org.junit.Assert;
import org.junit.Test;
-public class ConnectorAPIServletTest {
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.HttpMethod;
+import junit.extensions.PA;
+
+public class ConnectorApiLetTest {
@Test
public void testGet() throws Exception {
@@ -63,27 +64,27 @@
SqlppExecutionTest.setUp();
// Configures a test connector api servlet.
- ConnectorAPIServlet servlet = spy(new ConnectorAPIServlet());
- ServletConfig mockServletConfig = mock(ServletConfig.class);
- servlet.init(mockServletConfig);
+ ConnectorApiServlet let = new ConnectorApiServlet(new ConcurrentHashMap<>(), new String[] { "/" });
Map<String, NodeControllerInfo> nodeMap = new HashMap<>();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter outputWriter = new PrintWriter(outputStream);
// Creates mocks.
- ServletContext mockContext = mock(ServletContext.class);
IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
NodeControllerInfo mockInfo1 = mock(NodeControllerInfo.class);
NodeControllerInfo mockInfo2 = mock(NodeControllerInfo.class);
- HttpServletRequest mockRequest = mock(HttpServletRequest.class);
- HttpServletResponse mockResponse = mock(HttpServletResponse.class);
+ IServletRequest mockRequest = mock(IServletRequest.class);
+ IServletResponse mockResponse = mock(IServletResponse.class);
+ FullHttpRequest mockHttpRequest = mock(FullHttpRequest.class);
+ // Put stuff in let map
+ let.ctx().put(ServletConstants.HYRACKS_CONNECTION_ATTR, mockHcc);
// Sets up mock returns.
- when(servlet.getServletContext()).thenReturn(mockContext);
+ when(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
+ when(mockHttpRequest.method()).thenReturn(HttpMethod.GET);
when(mockRequest.getParameter("dataverseName")).thenReturn("Metadata");
when(mockRequest.getParameter("datasetName")).thenReturn("Dataset");
- when(mockResponse.getWriter()).thenReturn(outputWriter);
- when(mockContext.getAttribute(anyString())).thenReturn(mockHcc);
+ when(mockResponse.writer()).thenReturn(outputWriter);
when(mockHcc.getNodeControllerInfos()).thenReturn(nodeMap);
when(mockInfo1.getNetworkAddress()).thenReturn(new NetworkAddress("127.0.0.1", 3099));
when(mockInfo2.getNetworkAddress()).thenReturn(new NetworkAddress("127.0.0.2", 3099));
@@ -91,7 +92,7 @@
// Calls ConnectorAPIServlet.formResponseObject.
nodeMap.put("asterix_nc1", mockInfo1);
nodeMap.put("asterix_nc2", mockInfo2);
- servlet.doGet(mockRequest, mockResponse);
+ let.handle(mockRequest, mockResponse);
// Constructs the actual response.
ObjectMapper om = new ObjectMapper();
@@ -103,7 +104,7 @@
String primaryKey = actualResponse.get("keys").asText();
Assert.assertEquals("DataverseName,DatasetName", primaryKey);
ARecordType recordType = (ARecordType) JSONDeserializerForTypes
- .convertFromJSON((ObjectNode) actualResponse.get("type"));
+ .convertFromJSON(actualResponse.get("type"));
Assert.assertEquals(getMetadataRecordType("Metadata", "Dataset"), recordType);
// Checks the correctness of results.
@@ -117,7 +118,7 @@
@Test
public void testFormResponseObject() throws Exception {
- ConnectorAPIServlet servlet = new ConnectorAPIServlet();
+ ConnectorApiServlet let = new ConnectorApiServlet(new ConcurrentHashMap<>(), new String[] { "/" });
ObjectMapper om = new ObjectMapper();
ObjectNode actualResponse = om.createObjectNode();
FileSplit[] splits = new FileSplit[2];
@@ -139,7 +140,7 @@
// Calls ConnectorAPIServlet.formResponseObject.
nodeMap.put("asterix_nc1", mockInfo1);
nodeMap.put("asterix_nc2", mockInfo2);
- PA.invokeMethod(servlet, "formResponseObject(" + ObjectNode.class.getName() + ", " + FileSplit.class.getName()
+ PA.invokeMethod(let, "formResponseObject(" + ObjectNode.class.getName() + ", " + FileSplit.class.getName()
+ "[], " + ARecordType.class.getName() + ", " + String.class.getName() + ", boolean, " + Map.class
.getName() + ")", actualResponse, splits, recordType, primaryKey, true, nodeMap);
// Constructs expected response.
diff --git a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceServletTest.java b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceLetTest.java
similarity index 95%
rename from asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceServletTest.java
rename to asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceLetTest.java
index f4889a0..7b7c0d2 100644
--- a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceServletTest.java
+++ b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/QueryServiceLetTest.java
@@ -19,10 +19,11 @@
package org.apache.asterix.api.http.servlet;
+import org.apache.asterix.api.http.server.QueryServiceServlet;
import org.junit.Assert;
import org.junit.Test;
-public class QueryServiceServletTest {
+public class QueryServiceLetTest {
@Test
public void testTimeUnitFormatNanos() throws Exception {
diff --git a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionAPIServletTest.java b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionApiLetTest.java
similarity index 80%
rename from asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionAPIServletTest.java
rename to asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionApiLetTest.java
index da0ec0c..936b717 100644
--- a/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionAPIServletTest.java
+++ b/asterixdb/asterix-app/src/test/java/org/apache/asterix/api/http/servlet/VersionApiLetTest.java
@@ -22,31 +22,31 @@
import static org.apache.asterix.api.http.servlet.ServletConstants.ASTERIX_BUILD_PROP_ATTR;
import static org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.asterix.api.http.server.VersionApiServlet;
import org.apache.asterix.common.config.BuildProperties;
import org.apache.asterix.runtime.util.AppContextInfo;
import org.apache.asterix.test.runtime.SqlppExecutionTest;
import org.apache.hyracks.api.client.IHyracksClientConnection;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.apache.hyracks.http.server.IServletRequest;
+import org.apache.hyracks.http.server.IServletResponse;
import org.junit.Assert;
import org.junit.Test;
-public class VersionAPIServletTest {
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.HttpMethod;
+
+public class VersionApiLetTest {
@Test
public void testGet() throws Exception {
@@ -54,26 +54,26 @@
SqlppExecutionTest.setUp();
// Configures a test version api servlet.
- VersionAPIServlet servlet = spy(new VersionAPIServlet());
- ServletConfig mockServletConfig = mock(ServletConfig.class);
- servlet.init(mockServletConfig);
- Map<String, String> propMap = new HashMap<String, String>();
+ VersionApiServlet servlet = new VersionApiServlet(new ConcurrentHashMap<>(), new String[] { "/" });
+ Map<String, String> propMap = new HashMap<>();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter outputWriter = new PrintWriter(outputStream);
// Creates mocks.
- ServletContext mockContext = mock(ServletContext.class);
AppContextInfo mockCtx = mock(AppContextInfo.class);
- HttpServletRequest mockRequest = mock(HttpServletRequest.class);
+ IServletRequest mockRequest = mock(IServletRequest.class);
IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
- HttpServletResponse mockResponse = mock(HttpServletResponse.class);
+ IServletResponse mockResponse = mock(IServletResponse.class);
BuildProperties mockProperties = mock(BuildProperties.class);
+ FullHttpRequest mockHttpRequest = mock(FullHttpRequest.class);
+ // Put stuff in let map
+ servlet.ctx().put(HYRACKS_CONNECTION_ATTR, mockHcc);
+ servlet.ctx().put(ASTERIX_BUILD_PROP_ATTR, mockCtx);
// Sets up mock returns.
- when(servlet.getServletContext()).thenReturn(mockContext);
- when(mockResponse.getWriter()).thenReturn(outputWriter);
- when(mockContext.getAttribute(HYRACKS_CONNECTION_ATTR)).thenReturn(mockHcc);
- when(mockContext.getAttribute(ASTERIX_BUILD_PROP_ATTR)).thenReturn(mockCtx);
+ when(mockResponse.writer()).thenReturn(outputWriter);
+ when(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
+ when(mockHttpRequest.method()).thenReturn(HttpMethod.GET);
when(mockCtx.getBuildProperties()).thenReturn(mockProperties);
when(mockProperties.getAllProps()).thenReturn(propMap);
@@ -100,7 +100,7 @@
propMap.put("git.commit.user.name", "Obelix");
// Calls VersionAPIServlet.formResponseObject.
- servlet.doGet(mockRequest, mockResponse);
+ servlet.handle(mockRequest, mockResponse);
// Constructs the actual response.
diff --git a/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/ServletUtil.java b/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/LetUtil.java
similarity index 93%
rename from asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/ServletUtil.java
rename to asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/LetUtil.java
index f0b124d..2fe9380 100644
--- a/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/ServletUtil.java
+++ b/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/LetUtil.java
@@ -18,9 +18,9 @@
*/
package org.apache.asterix.common.utils;
-public class ServletUtil {
+public class LetUtil {
- public enum Servlets {
+ public enum Lets {
AQL("/aql"),
AQL_QUERY("/query"),
AQL_UPDATE("/update"),
@@ -42,7 +42,7 @@
private final String path;
- Servlets(String path) {
+ Lets(String path) {
this.path = path;
}
@@ -52,7 +52,7 @@
}
- private ServletUtil() {
+ private LetUtil() {
throw new AssertionError("No objects of this class should be created.");
}
}
diff --git a/asterixdb/asterix-common/src/test/java/org/apache/asterix/test/aql/TestExecutor.java b/asterixdb/asterix-common/src/test/java/org/apache/asterix/test/aql/TestExecutor.java
index 80e8d09..ff30df3 100644
--- a/asterixdb/asterix-common/src/test/java/org/apache/asterix/test/aql/TestExecutor.java
+++ b/asterixdb/asterix-common/src/test/java/org/apache/asterix/test/aql/TestExecutor.java
@@ -48,7 +48,7 @@
import java.util.regex.Pattern;
import org.apache.asterix.common.config.GlobalConfig;
-import org.apache.asterix.common.utils.ServletUtil.Servlets;
+import org.apache.asterix.common.utils.LetUtil.Lets;
import org.apache.asterix.test.base.ComparisonException;
import org.apache.asterix.test.server.ITestServer;
import org.apache.asterix.test.server.TestServerProvider;
@@ -603,7 +603,7 @@
}
private InputStream getHandleResult(String handle, OutputFormat fmt) throws Exception {
- final String url = getEndpoint(Servlets.QUERY_RESULT);
+ final String url = getEndpoint(Lets.QUERY_RESULT);
// Create a method instance.
HttpUriRequest request = RequestBuilder.get(url).addParameter("handle", handle)
@@ -744,9 +744,9 @@
switch (ctx.getType()) {
case "ddl":
if (ctx.getFile().getName().endsWith("aql")) {
- executeDDL(statement, getEndpoint(Servlets.AQL_DDL));
+ executeDDL(statement, getEndpoint(Lets.AQL_DDL));
} else {
- InputStream resultStream = executeQueryService(statement, getEndpoint(Servlets.QUERY_SERVICE));
+ InputStream resultStream = executeQueryService(statement, getEndpoint(Lets.QUERY_SERVICE));
ResultExtractor.extract(resultStream);
}
break;
@@ -756,9 +756,9 @@
statement = statement.replaceAll("nc1://", "127.0.0.1://../../../../../../asterix-app/");
}
if (ctx.getFile().getName().endsWith("aql")) {
- executeUpdate(statement, getEndpoint(Servlets.AQL_UPDATE));
+ executeUpdate(statement, getEndpoint(Lets.AQL_UPDATE));
} else {
- InputStream resultStream = executeQueryService(statement, getEndpoint(Servlets.QUERY_SERVICE));
+ InputStream resultStream = executeQueryService(statement, getEndpoint(Lets.QUERY_SERVICE));
ResultExtractor.extract(resultStream);
}
break;
@@ -812,16 +812,16 @@
OutputFormat fmt = OutputFormat.forCompilationUnit(cUnit);
if (ctx.getFile().getName().endsWith("aql")) {
if (ctx.getType().equalsIgnoreCase("query")) {
- resultStream = executeQuery(statement, fmt, getEndpoint(Servlets.AQL_QUERY),
+ resultStream = executeQuery(statement, fmt, getEndpoint(Lets.AQL_QUERY),
cUnit.getParameter());
} else if (ctx.getType().equalsIgnoreCase("async")) {
- resultStream = executeAnyAQLAsync(statement, false, fmt, getEndpoint(Servlets.AQL));
+ resultStream = executeAnyAQLAsync(statement, false, fmt, getEndpoint(Lets.AQL));
} else if (ctx.getType().equalsIgnoreCase("asyncdefer")) {
- resultStream = executeAnyAQLAsync(statement, true, fmt, getEndpoint(Servlets.AQL));
+ resultStream = executeAnyAQLAsync(statement, true, fmt, getEndpoint(Lets.AQL));
}
} else {
final String reqType = ctx.getType();
- final String url = getEndpoint(Servlets.QUERY_SERVICE);
+ final String url = getEndpoint(Lets.QUERY_SERVICE);
final List<CompilationUnit.Parameter> params = cUnit.getParameter();
if (reqType.equalsIgnoreCase("query")) {
resultStream = executeQueryService(statement, fmt, url, params, true);
@@ -854,13 +854,13 @@
break;
case "txnqbc": // qbc represents query before crash
resultStream = executeQuery(statement, OutputFormat.forCompilationUnit(cUnit),
- getEndpoint(Servlets.AQL_QUERY), cUnit.getParameter());
+ getEndpoint(Lets.AQL_QUERY), cUnit.getParameter());
qbcFile = getTestCaseQueryBeforeCrashFile(actualPath, testCaseCtx, cUnit);
writeOutputToFile(qbcFile, resultStream);
break;
case "txnqar": // qar represents query after recovery
resultStream = executeQuery(statement, OutputFormat.forCompilationUnit(cUnit),
- getEndpoint(Servlets.AQL_QUERY), cUnit.getParameter());
+ getEndpoint(Lets.AQL_QUERY), cUnit.getParameter());
File qarFile = new File(actualPath + File.separator
+ testCaseCtx.getTestCase().getFilePath().replace(File.separator, "_") + "_" + cUnit.getName()
+ "_qar.adm");
@@ -870,7 +870,7 @@
break;
case "txneu": // eu represents erroneous update
try {
- executeUpdate(statement, getEndpoint(Servlets.AQL_UPDATE));
+ executeUpdate(statement, getEndpoint(Lets.AQL_UPDATE));
} catch (Exception e) {
// An exception is expected.
failed = true;
@@ -898,7 +898,7 @@
break;
case "errddl": // a ddlquery that expects error
try {
- executeDDL(statement, getEndpoint(Servlets.AQL_DDL));
+ executeDDL(statement, getEndpoint(Lets.AQL_DDL));
} catch (Exception e) {
// expected error happens
failed = true;
@@ -1136,11 +1136,11 @@
+ cUnit.getName() + "_qbc.adm");
}
- protected String getPath(Servlets servlet) {
+ protected String getPath(Lets servlet) {
return servlet.getPath();
}
- protected String getEndpoint(Servlets servlet) {
+ protected String getEndpoint(Lets servlet) {
return "http://" + host + ":" + port + getPath(servlet).replaceAll("/\\*$", "");
}
@@ -1152,7 +1152,7 @@
try {
ArrayList<String> toBeDropped = new ArrayList<>();
InputStream resultStream = executeQueryService("select dv.DataverseName from Metadata.`Dataverse` as dv;",
- getEndpoint(Servlets.QUERY_SERVICE));
+ getEndpoint(Lets.QUERY_SERVICE));
String out = IOUtils.toString(resultStream);
ObjectMapper om = new ObjectMapper();
om.setConfig(om.getDeserializationConfig().with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT));
@@ -1181,7 +1181,7 @@
dropStatement.append(dv);
dropStatement.append(";\n");
}
- resultStream = executeQueryService(dropStatement.toString(), getEndpoint(Servlets.QUERY_SERVICE));
+ resultStream = executeQueryService(dropStatement.toString(), getEndpoint(Lets.QUERY_SERVICE));
ResultExtractor.extract(resultStream);
}
} catch (Throwable th) {
diff --git a/asterixdb/asterix-server/src/test/java/org/apache/asterix/server/test/SampleLocalClusterIT.java b/asterixdb/asterix-server/src/test/java/org/apache/asterix/server/test/SampleLocalClusterIT.java
index 83d421f..0991d4f 100644
--- a/asterixdb/asterix-server/src/test/java/org/apache/asterix/server/test/SampleLocalClusterIT.java
+++ b/asterixdb/asterix-server/src/test/java/org/apache/asterix/server/test/SampleLocalClusterIT.java
@@ -27,7 +27,7 @@
import java.net.URL;
import java.util.Collections;
-import org.apache.asterix.common.utils.ServletUtil.Servlets;
+import org.apache.asterix.common.utils.LetUtil.Lets;
import org.apache.asterix.test.aql.TestExecutor;
import org.apache.asterix.test.base.TestMethodTracer;
import org.apache.asterix.test.common.TestHelper;
@@ -89,7 +89,7 @@
public void test1_sanityQuery() throws Exception {
TestExecutor testExecutor = new TestExecutor();
InputStream resultStream = testExecutor.executeQuery("1+1", OutputFormat.ADM,
- "http://127.0.0.1:19002" + Servlets.AQL_QUERY.getPath(), Collections.emptyList());
+ "http://127.0.0.1:19002" + Lets.AQL_QUERY.getPath(), Collections.emptyList());
StringWriter sw = new StringWriter();
IOUtils.copy(resultStream, sw);
Assert.assertEquals("2", sw.toString().trim());
diff --git a/asterixdb/pom.xml b/asterixdb/pom.xml
index ea80127..3133231 100644
--- a/asterixdb/pom.xml
+++ b/asterixdb/pom.xml
@@ -825,6 +825,11 @@
</dependency>
<dependency>
<groupId>org.apache.hyracks</groupId>
+ <artifactId>hyracks-http</artifactId>
+ <version>${hyracks.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hyracks</groupId>
<artifactId>hyracks-util</artifactId>
<version>${hyracks.version}</version>
</dependency>
diff --git a/hyracks-fullstack/hyracks/hyracks-http/pom.xml b/hyracks-fullstack/hyracks/hyracks-http/pom.xml
new file mode 100644
index 0000000..8dc57a2
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/pom.xml
@@ -0,0 +1,34 @@
+<!--
+ ! Licensed to the Apache Software Foundation (ASF) under one
+ ! or more contributor license agreements. See the NOTICE file
+ ! distributed with this work for additional information
+ ! regarding copyright ownership. The ASF licenses this file
+ ! to you under the Apache License, Version 2.0 (the
+ ! "License"); you may not use this file except in compliance
+ ! with the License. You may obtain a copy of the License at
+ !
+ ! http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing,
+ ! software distributed under the License is distributed on an
+ ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ! KIND, either express or implied. See the License for the
+ ! specific language governing permissions and limitations
+ ! under the License.
+ !-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.hyracks</groupId>
+ <artifactId>hyracks</artifactId>
+ <version>0.3.1-SNAPSHOT</version>
+ </parent>
+ <artifactId>hyracks-http</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-all</artifactId>
+ <version>4.1.6.Final</version>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/AbstractServlet.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/AbstractServlet.java
new file mode 100644
index 0000000..22bbc50
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/AbstractServlet.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.concurrent.ConcurrentMap;
+
+public abstract class AbstractServlet implements IServlet {
+ protected final String[] paths;
+ protected final ConcurrentMap<String, Object> ctx;
+ private final int[] trims;
+
+ public AbstractServlet(ConcurrentMap<String, Object> ctx, String[] paths) {
+ this.paths = paths;
+ this.ctx = ctx;
+ trims = new int[paths.length];
+ for (int i = 0; i < paths.length; i++) {
+ String path = paths[i];
+ if (path.endsWith("/*")) {
+ trims[i] = path.indexOf("/*");
+ } else if (path.endsWith("/")) {
+ trims[i] = path.length() - 1;
+ } else {
+ trims[i] = path.length();
+ }
+ }
+ }
+
+ @Override
+ public String[] getPaths() {
+ return paths;
+ }
+
+ @Override
+ public ConcurrentMap<String, Object> ctx() {
+ return ctx;
+ }
+
+ public String path(IServletRequest request) {
+ int trim = -1;
+ if (paths.length > 1) {
+ for (int i = 0; i < paths.length; i++) {
+ String path = paths[i].indexOf('*') >= 0 ? paths[i].substring(0, paths[i].indexOf('*')) : paths[0];
+ if (request.getHttpRequest().uri().indexOf(path) == 0) {
+ trim = trims[i];
+ break;
+ }
+ }
+ } else {
+ trim = trims[0];
+ }
+ return request.getHttpRequest().uri().substring(trim);
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedNettyOutputStream.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedNettyOutputStream.java
new file mode 100644
index 0000000..984122b
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedNettyOutputStream.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.DefaultHttpContent;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+public class ChunkedNettyOutputStream extends OutputStream {
+
+ private final ChannelHandlerContext ctx;
+ private final ChunkedResponse response;
+ private ByteBuf buffer;
+
+ public ChunkedNettyOutputStream(ChannelHandlerContext ctx, int chunkSize,
+ ChunkedResponse response) {
+ this.response = response;
+ this.ctx = ctx;
+ buffer = ctx.alloc().buffer(chunkSize);
+ }
+
+ @Override
+ public synchronized void write(byte[] b, int off, int len) {
+ if ((off < 0) || (off > b.length) || (len < 0) ||
+ ((off + len) > b.length)) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return;
+ }
+
+ if (len > buffer.capacity()) {
+ flush();
+ flush(b, off, len);
+ } else {
+ int space = buffer.writableBytes();
+ if (space >= len) {
+ buffer.writeBytes(b, off, len);
+ } else {
+ buffer.writeBytes(b, off, space);
+ flush();
+ buffer.writeBytes(b, off + space, len - space);
+ }
+ }
+ }
+
+ @Override
+ public synchronized void write(int b) {
+ if (buffer.writableBytes() > 0) {
+ buffer.writeByte(b);
+ } else {
+ flush();
+ buffer.writeByte(b);
+ }
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ flush();
+ buffer.release();
+ super.close();
+ }
+
+ @Override
+ public synchronized void flush() {
+ if (buffer.readableBytes() > 0) {
+ int size = buffer.capacity();
+ if (response.status() == HttpResponseStatus.OK) {
+ response.flush();
+ DefaultHttpContent content = new DefaultHttpContent(buffer);
+ ctx.write(content);
+ } else {
+ response.error(buffer);
+ }
+ buffer = ctx.alloc().buffer(size);
+ }
+ }
+
+ private synchronized void flush(byte[] buf, int offset, int len) {
+ ByteBuf aBuffer = ctx.alloc().buffer(len);
+ aBuffer.writeBytes(buf, offset, len);
+ if (response.status() == HttpResponseStatus.OK) {
+ response.flush();
+ ctx.write(new DefaultHttpContent(aBuffer));
+ } else {
+ response.error(aBuffer);
+ }
+ }
+}
\ No newline at end of file
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedResponse.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedResponse.java
new file mode 100644
index 0000000..19c2664
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/ChunkedResponse.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpResponse;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpUtil;
+import io.netty.handler.codec.http.LastHttpContent;
+
+public class ChunkedResponse implements IServletResponse {
+ private final ChannelHandlerContext ctx;
+ private final ChunkedNettyOutputStream outputStream;
+ private final PrintWriter writer;
+ private HttpResponse response;
+ private boolean headerSent;
+ private ByteBuf error;
+ private ChannelFuture future;
+
+ public ChunkedResponse(ChannelHandlerContext ctx, FullHttpRequest request) {
+ this.ctx = ctx;
+ outputStream = new ChunkedNettyOutputStream(ctx, 4096, this);
+ writer = new PrintWriter(outputStream);
+ response = new DefaultHttpResponse(HTTP_1_1, OK);
+ response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ if (HttpUtil.isKeepAlive(request)) {
+ response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
+ }
+ }
+
+ @Override
+ public IServletResponse setHeader(CharSequence name, Object value) throws IOException {
+ if (headerSent) {
+ throw new IOException("Can't add more headers since the initial response was sent");
+ }
+ response.headers().set(name, value);
+ return this;
+ }
+
+ @Override
+ public ChannelFuture future() {
+ return future;
+ }
+
+ @Override
+ public PrintWriter writer() {
+ return writer;
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (error == null) {
+ writer.close();
+ future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
+ }
+ }
+
+ public HttpResponseStatus status() {
+ return response.status();
+ }
+
+ public void flush() {
+ if (!headerSent && response.status() == HttpResponseStatus.OK) {
+ ctx.writeAndFlush(response);
+ headerSent = true;
+ }
+ }
+
+ public void error(ByteBuf error) {
+ this.error = error;
+ }
+
+ @Override
+ public OutputStream outputStream() {
+ return outputStream;
+ }
+
+ @Override
+ public void setStatus(HttpResponseStatus status) {
+ // update the response
+ // close the stream
+ // write the response
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/FullResponse.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/FullResponse.java
new file mode 100644
index 0000000..245f28a
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/FullResponse.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpUtil;
+import io.netty.handler.codec.http.HttpVersion;
+
+public class FullResponse implements IServletResponse {
+ private final ChannelHandlerContext ctx;
+ private final ByteArrayOutputStream baos;
+ private final PrintWriter writer;
+ private final FullHttpResponse response;
+ private final boolean keepAlive;
+ private ChannelFuture future;
+
+ public FullResponse(ChannelHandlerContext ctx, FullHttpRequest request) {
+ this.ctx = ctx;
+ baos = new ByteArrayOutputStream();
+ writer = new PrintWriter(baos);
+ response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ keepAlive = HttpUtil.isKeepAlive(request);
+ if (keepAlive) {
+ response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ writer.close();
+ FullHttpResponse fullResponse = response.replace(Unpooled.copiedBuffer(baos.toByteArray()));
+ if (keepAlive && response.status() == HttpResponseStatus.OK) {
+ fullResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, fullResponse.content().readableBytes());
+ }
+ future = ctx.writeAndFlush(fullResponse);
+ if (response.status() != HttpResponseStatus.OK) {
+ future.addListener(ChannelFutureListener.CLOSE);
+ }
+ }
+
+ @Override
+ public IServletResponse setHeader(CharSequence name, Object value) throws IOException {
+ response.headers().set(name, value);
+ return this;
+ }
+
+ @Override
+ public PrintWriter writer() {
+ return writer;
+ }
+
+ @Override
+ public ChannelFuture future() throws IOException {
+ return future;
+ }
+
+ @Override
+ public OutputStream outputStream() {
+ return baos;
+ }
+
+ @Override
+ public void setStatus(HttpResponseStatus status) {
+ response.setStatus(status);
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/GetRequest.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/GetRequest.java
new file mode 100644
index 0000000..0b80a78
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/GetRequest.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.List;
+import java.util.Map;
+
+import io.netty.handler.codec.http.FullHttpRequest;
+
+public class GetRequest implements IServletRequest {
+ private final FullHttpRequest request;
+ private final Map<String, List<String>> parameters;
+
+ public GetRequest(FullHttpRequest request, Map<String, List<String>> parameters) {
+ this.request = request;
+ this.parameters = parameters;
+ }
+
+ @Override
+ public FullHttpRequest getHttpRequest() {
+ return request;
+ }
+
+ @Override
+ public String getParameter(CharSequence name) {
+ return IServletRequest.getParameter(parameters, name);
+ }
+
+ @Override
+ public String getHeader(CharSequence name) {
+ return request.headers().get(name);
+ }
+
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServer.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServer.java
new file mode 100644
index 0000000..f7f55bd
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServer.java
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.Channel;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.logging.LogLevel;
+import io.netty.handler.logging.LoggingHandler;
+
+public class HttpServer {
+ // Constants
+ private static final Logger LOGGER = Logger.getLogger(HttpServer.class.getName());
+ private static final int FAILED = -1;
+ private static final int STOPPED = 0;
+ private static final int STARTING = 1;
+ private static final int STARTED = 2;
+ private static final int STOPPING = 3;
+ // Final members
+ private final Object lock = new Object();
+ private final ConcurrentMap<String, Object> ctx;
+ private final List<IServlet> lets;
+ private final EventLoopGroup bossGroup;
+ private final EventLoopGroup workerGroup;
+ private final int port;
+ // Mutable members
+ private volatile int state = STOPPED;
+ private Channel channel;
+ private Throwable cause;
+
+ public HttpServer(EventLoopGroup bossGroup, EventLoopGroup workerGroup,
+ int port) {
+ this.bossGroup = bossGroup;
+ this.workerGroup = workerGroup;
+ this.port = port;
+ ctx = new ConcurrentHashMap<>();
+ lets = new ArrayList<>();
+ }
+
+ public final void start() throws Exception { // NOSONAR
+ synchronized (lock) {
+ try {
+ if (state == STARTED || state == STARTING) {
+ return;
+ }
+ setStarting();
+ doStart();
+ setStarted();
+ } catch (Throwable e) { // NOSONAR
+ LOGGER.log(Level.SEVERE, "Failure starting an Http Server", e);
+ setFailed(e);
+ throw e;
+ }
+ }
+ }
+
+ public final void stop() throws Exception { // NOSONAR
+ synchronized (lock) {
+ try {
+ if (state == STOPPING || state == STOPPED) {
+ return;
+ }
+ setStopping();
+ doStop();
+ setStopped();
+ } catch (Throwable e) { // NOSONAR
+ LOGGER.log(Level.SEVERE, "Failure stopping an Http Server", e);
+ setFailed(e);
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * @return String representation of the State for this server
+ */
+ public String getState() {
+ switch (state) {
+ case FAILED:
+ return "FAILED";
+ case STARTING:
+ return "STARTING";
+ case STARTED:
+ return "STARTED";
+ case STOPPING:
+ return "STOPPING";
+ case STOPPED:
+ return "STOPPED";
+ default:
+ return "UNKNOWN";
+ }
+ }
+
+ private void setStarting() {
+ state = STARTING;
+ }
+
+ private void setStarted() {
+ state = STARTED;
+ }
+
+ private void setStopping() {
+ state = STOPPING;
+ }
+
+ private void setStopped() {
+ state = STOPPED;
+ }
+
+ private void setFailed(Throwable th) {
+ state = FAILED;
+ cause = th;
+ }
+
+ public Throwable getCause() {
+ return cause;
+ }
+
+ public void setAttribute(String name, Object value) {
+ ctx.put(name, value);
+ }
+
+ public Object getAttribute(String name) {
+ return ctx.get(name);
+ }
+
+ public ConcurrentMap<String, Object> ctx() {
+ return ctx;
+ }
+
+ public void addLet(IServlet let) {
+ lets.add(let);
+ }
+
+
+ protected void doStart() throws InterruptedException {
+ /*
+ * This is a hacky way to ensure that ILets with more specific paths are checked first.
+ * For example:
+ * "/path/to/resource/"
+ * is checked before
+ * "/path/to/"
+ * which in turn is checked before
+ * "/path/"
+ * Note that it doesn't work for the case where multiple paths map to a single ILet
+ */
+ Collections.sort(lets, (l1, l2) -> l2.getPaths()[0].length() - l1.getPaths()[0].length());
+ ServerBootstrap b = new ServerBootstrap();
+ b.group(bossGroup, workerGroup)
+ .channel(NioServerSocketChannel.class)
+ .handler(new LoggingHandler(LogLevel.INFO))
+ .childHandler(new HttpServerInitializer(this));
+ channel = b.bind(port).sync().channel();
+ }
+
+
+ protected void doStop() throws InterruptedException {
+ channel.close();
+ channel.closeFuture().sync();
+ }
+
+ public IServlet getServlet(FullHttpRequest request) {
+ String uri = request.uri();
+ int i = uri.indexOf('?');
+ if (i >= 0) {
+ uri = uri.substring(0, i);
+ }
+ for (IServlet let : lets) {
+ for (String path : let.getPaths()) {
+ if (match(path, uri)) {
+ return let;
+ }
+ }
+ }
+ return null;
+ }
+
+ private static boolean match(String pathSpec, String path) {
+ char c = pathSpec.charAt(0);
+ if (c == '/') {
+ if (pathSpec.length() == 1 || pathSpec.equals(path)) {
+ return true;
+ }
+
+ if (isPathWildcardMatch(pathSpec, path)) {
+ return true;
+ }
+ } else if (c == '*') {
+ return path.regionMatches(path.length() - pathSpec.length() + 1,
+ pathSpec, 1, pathSpec.length() - 1);
+ }
+ return false;
+ }
+ private static boolean isPathWildcardMatch(String pathSpec, String path) {
+ int cpl = pathSpec.length() - 2;
+ return (pathSpec.endsWith("/*") && path.regionMatches(0, pathSpec, 0, cpl))
+ && (path.length() == cpl || '/' == path.charAt(cpl));
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerHandler.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerHandler.java
new file mode 100644
index 0000000..c8ed937
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerHandler.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpUtil;
+import io.netty.handler.codec.http.QueryStringDecoder;
+import io.netty.handler.codec.http.multipart.Attribute;
+import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
+import io.netty.handler.codec.http.multipart.InterfaceHttpData;
+import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
+import io.netty.handler.codec.http.multipart.MixedAttribute;
+
+public class HttpServerHandler extends SimpleChannelInboundHandler<Object> {
+
+ private static final Logger LOGGER = Logger.getLogger(HttpServerHandler.class.getName());
+ protected final HttpServer server;
+
+ public HttpServerHandler(HttpServer server) {
+ this.server = server;
+ }
+
+ @Override
+ public void channelReadComplete(ChannelHandlerContext ctx) {
+ ctx.flush();
+ }
+
+ @Override
+ protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
+ try {
+ FullHttpRequest http = (FullHttpRequest) msg;
+ IServlet servlet = server.getServlet(http);
+ if (servlet == null) {
+ DefaultHttpResponse response = new DefaultHttpResponse(http.protocolVersion(),
+ HttpResponseStatus.NOT_FOUND);
+ ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+ } else {
+ if (http.method() != HttpMethod.GET && http.method() != HttpMethod.POST) {
+ DefaultHttpResponse response = new DefaultHttpResponse(http.protocolVersion(),
+ HttpResponseStatus.METHOD_NOT_ALLOWED);
+ ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+ return;
+ }
+ IServletRequest request = http.method() == HttpMethod.GET ? get(http) : post(http);
+ IServletResponse response = new FullResponse(ctx, http);
+ try {
+ servlet.handle(request, response);
+ } catch (Throwable th) { // NOSONAR
+ LOGGER.log(Level.WARNING, "Failure during handling of an IServLetRequest", th);
+ response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
+ } finally {
+ response.close();
+ }
+ ChannelFuture lastContentFuture = response.future();
+ if (!HttpUtil.isKeepAlive(http)) {
+ lastContentFuture.addListener(ChannelFutureListener.CLOSE);
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.log(Level.SEVERE, "Failure handling HTTP Request", e);
+ ctx.close();
+ }
+ }
+
+ public static IServletRequest post(FullHttpRequest request) throws IOException {
+ List<String> names = new ArrayList<>();
+ List<String> values = new ArrayList<>();
+ HttpPostRequestDecoder decoder = null;
+ try {
+ decoder = new HttpPostRequestDecoder(request);
+ } catch (Exception e) {
+ //ignore. this means that the body of the POST request does not have key value pairs
+ LOGGER.log(Level.WARNING, "Failed to decode a post message. Fix the API not to have queries as POST body",
+ e);
+ }
+ if (decoder != null) {
+ try {
+ List<InterfaceHttpData> bodyHttpDatas = decoder.getBodyHttpDatas();
+ for (InterfaceHttpData data : bodyHttpDatas) {
+ if (data.getHttpDataType().equals(HttpDataType.Attribute)) {
+ Attribute attr = (MixedAttribute) data;
+ names.add(data.getName());
+ values.add(attr.getValue());
+ }
+ }
+ } finally {
+ decoder.destroy();
+ }
+ }
+ return new PostRequest(request, new QueryStringDecoder(request.uri()).parameters(), names, values);
+ }
+
+ public static IServletRequest get(FullHttpRequest request) throws IOException {
+ return new GetRequest(request, new QueryStringDecoder(request.uri()).parameters());
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ LOGGER.log(Level.SEVERE, "Failure handling HTTP Request", cause);
+ ctx.close();
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerInitializer.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerInitializer.java
new file mode 100644
index 0000000..3b32ee6
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/HttpServerInitializer.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.codec.http.HttpObjectAggregator;
+import io.netty.handler.codec.http.HttpRequestDecoder;
+import io.netty.handler.codec.http.HttpResponseEncoder;
+
+public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
+
+ private static final int MAX_CHUNK_SIZE = 262144;
+ private static final int MAX_HEADER_SIZE = 262144;
+ private static final int MAX_INITIAL_LINE_LENGTH = 131072;
+ private HttpServer server;
+
+ public HttpServerInitializer(HttpServer server) {
+ this.server = server;
+ }
+
+ @Override
+ public void initChannel(SocketChannel ch) {
+ ChannelPipeline p = ch.pipeline();
+ p.addLast(new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE));
+ p.addLast(new HttpResponseEncoder());
+ p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
+ p.addLast(new HttpServerHandler(server));
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServlet.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServlet.java
new file mode 100644
index 0000000..5691fd9
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServlet.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Represents a component that handles IServLet requests
+ */
+public interface IServlet {
+
+ public class Encoding {
+ public static final String UTF8 = "utf-8";
+
+ private Encoding() {
+ }
+ }
+
+ public class ContentType {
+ public static final String APPLICATION_ADM = "application/x-adm";
+ public static final String APPLICATION_JSON = "application/json";
+ public static final String CSV = "text/csv";
+ public static final String IMG_PNG = "image/png";
+ public static final String TEXT_HTML = "text/html";
+ public static final String TEXT_PLAIN = "text/plain";
+
+ private ContentType() {
+ }
+
+ /**
+ * Get the mime string representation from the extension
+ * @param extension
+ * @return
+ */
+ public static String mime(String extension) {
+ switch (extension) {
+ case ".png":
+ return "image/png";
+ case ".eot":
+ return "application/vnd.ms-fontobject";
+ case ".svg":
+ return "image/svg+xml\t";
+ case ".ttf":
+ return "application/x-font-ttf";
+ case ".woff":
+ case ".woff2":
+ return "application/x-font-woff";
+ case ".html":
+ return "text/html";
+ case ".css":
+ return "text/css";
+ case ".js":
+ return "application/javascript";
+ default:
+ return null;
+ }
+ }
+ }
+
+ /**
+ * @return an array of paths associated with this IServLet
+ */
+ String[] getPaths();
+
+ /**
+ * @return the context associated with this IServlet
+ */
+ ConcurrentMap<String, Object> ctx();
+
+ /**
+ * handle the IServLetRequest writing the response in the passed IServLetResponse
+ * @param request
+ * @param response
+ */
+ void handle(IServletRequest request, IServletResponse response);
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletRequest.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletRequest.java
new file mode 100644
index 0000000..8aebd07
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletRequest.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.List;
+import java.util.Map;
+
+import io.netty.handler.codec.http.FullHttpRequest;
+
+/**
+ * An Http Request instance
+ */
+public interface IServletRequest {
+ /**
+ * @return the full http request
+ */
+ FullHttpRequest getHttpRequest();
+
+ /**
+ * Get a request parameter
+ * @param name
+ * @return the parameter or null if not found
+ */
+ String getParameter(CharSequence name);
+
+ /**
+ * Get a request header
+ * @param name
+ * @return the header or null if not found
+ */
+ String getHeader(CharSequence name);
+
+ static String getParameter(Map<String, List<String>> parameters, CharSequence name) {
+ List<String> parameter = parameters.get(name);
+ if (parameter == null) {
+ return null;
+ } else if (parameter.size() == 1) {
+ return parameter.get(0);
+ } else {
+ StringBuilder aString = new StringBuilder(parameter.get(0));
+ for (int i = 1; i < parameter.size(); i++) {
+ aString.append(",").append(parameter.get(i));
+ }
+ return aString.toString();
+ }
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletResponse.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletResponse.java
new file mode 100644
index 0000000..342e643
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/IServletResponse.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+import io.netty.channel.ChannelFuture;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpResponseStatus;
+
+/**
+ * A response to an instance of IServLetRequest
+ */
+public interface IServletResponse extends Closeable {
+
+ /**
+ * Set a response header
+ * @param name
+ * @param value
+ * @return
+ * @throws Exception
+ */
+ IServletResponse setHeader(CharSequence name, Object value) throws IOException;
+
+ /**
+ * Get the output writer for the response
+ * @return
+ * @throws Exception
+ */
+ PrintWriter writer();
+
+ /**
+ * Send the last http response if any and return the future
+ * @return
+ * @throws Exception
+ */
+ ChannelFuture future() throws IOException;
+
+ /**
+ * Set the status of the http response
+ * @param status
+ */
+ void setStatus(HttpResponseStatus status);
+
+ /**
+ * Get the output stream for the response
+ * @return
+ */
+ OutputStream outputStream();
+
+ public static void setContentType(IServletResponse response, String type, String charset) throws IOException {
+ response.setHeader(HttpHeaderNames.CONTENT_TYPE, type + "; charset=" + charset);
+ }
+
+ public static void setContentType(IServletResponse response, String type) throws IOException {
+ response.setHeader(HttpHeaderNames.CONTENT_TYPE, type);
+ }
+}
diff --git a/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/PostRequest.java b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/PostRequest.java
new file mode 100644
index 0000000..99f338c
--- /dev/null
+++ b/hyracks-fullstack/hyracks/hyracks-http/src/main/java/org/apache/hyracks/http/server/PostRequest.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.hyracks.http.server;
+
+import java.util.List;
+import java.util.Map;
+
+import io.netty.handler.codec.http.FullHttpRequest;
+
+public class PostRequest implements IServletRequest {
+ private final FullHttpRequest request;
+ private final List<String> names;
+ private final List<String> values;
+ private final Map<String, List<String>> parameters;
+
+ public PostRequest(FullHttpRequest request, Map<String, List<String>> parameters, List<String> names,
+ List<String> values) {
+ this.request = request;
+ this.parameters = parameters;
+ this.names = names;
+ this.values = values;
+ }
+
+ @Override
+ public FullHttpRequest getHttpRequest() {
+ return request;
+ }
+
+ @Override
+ public String getParameter(CharSequence name) {
+ for (int i = 0; i < names.size(); i++) {
+ if (name.equals(names.get(i))) {
+ return values.get(i);
+ }
+ }
+ return IServletRequest.getParameter(parameters, name);
+ }
+
+ @Override
+ public String getHeader(CharSequence name) {
+ return request.headers().get(name);
+ }
+}
diff --git a/hyracks-fullstack/hyracks/pom.xml b/hyracks-fullstack/hyracks/pom.xml
index e2d5a95..fc7d8b5 100644
--- a/hyracks-fullstack/hyracks/pom.xml
+++ b/hyracks-fullstack/hyracks/pom.xml
@@ -130,5 +130,6 @@
<module>hyracks-maven-plugins</module>
<module>hyracks-hdfs</module>
<module>hyracks-dist</module>
+ <module>hyracks-http</module>
</modules>
</project>