Search in sources :

Example 1 with IServletRequest

use of org.apache.hyracks.http.api.IServletRequest in project asterixdb by apache.

the class ConnectorApiServletTest method testGet.

@Test
public void testGet() throws Exception {
    // Starts test asterixdb cluster.
    SqlppExecutionTest.setUp();
    // Configures a test connector api servlet.
    ConnectorApiServlet let = new ConnectorApiServlet(new ConcurrentHashMap<>(), new String[] { "/" }, (ICcApplicationContext) ExecutionTestUtil.integrationUtil.cc.getApplicationContext());
    Map<String, NodeControllerInfo> nodeMap = new HashMap<>();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter outputWriter = new PrintWriter(outputStream);
    // Creates mocks.
    IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
    NodeControllerInfo mockInfo1 = mock(NodeControllerInfo.class);
    NodeControllerInfo mockInfo2 = mock(NodeControllerInfo.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(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
    when(mockHttpRequest.method()).thenReturn(HttpMethod.GET);
    when(mockRequest.getParameter("dataverseName")).thenReturn("Metadata");
    when(mockRequest.getParameter("datasetName")).thenReturn("Dataset");
    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));
    // Calls ConnectorAPIServlet.formResponseObject.
    nodeMap.put("asterix_nc1", mockInfo1);
    nodeMap.put("asterix_nc2", mockInfo2);
    let.handle(mockRequest, mockResponse);
    // Constructs the actual response.
    ObjectMapper om = new ObjectMapper();
    ObjectNode actualResponse = (ObjectNode) om.readTree(outputStream.toString());
    // Checks the temp-or-not, primary key, data type of the dataset.
    boolean temp = actualResponse.get("temp").asBoolean();
    Assert.assertFalse(temp);
    String primaryKey = actualResponse.get("keys").asText();
    Assert.assertEquals("DataverseName,DatasetName", primaryKey);
    ARecordType recordType = (ARecordType) JSONDeserializerForTypes.convertFromJSON(actualResponse.get("type"));
    Assert.assertEquals(getMetadataRecordType("Metadata", "Dataset"), recordType);
    // Checks the correctness of results.
    ArrayNode splits = (ArrayNode) actualResponse.get("splits");
    String path = (splits.get(0)).get("path").asText();
    Assert.assertTrue(path.endsWith("Metadata/Dataset_idx_Dataset"));
    // Tears down the asterixdb cluster.
    SqlppExecutionTest.tearDown();
}
Also used : IHyracksClientConnection(org.apache.hyracks.api.client.IHyracksClientConnection) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IServletRequest(org.apache.hyracks.http.api.IServletRequest) NetworkAddress(org.apache.hyracks.api.comm.NetworkAddress) NodeControllerInfo(org.apache.hyracks.api.client.NodeControllerInfo) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ConnectorApiServlet(org.apache.asterix.api.http.server.ConnectorApiServlet) IServletResponse(org.apache.hyracks.http.api.IServletResponse) ARecordType(org.apache.asterix.om.types.ARecordType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PrintWriter(java.io.PrintWriter) Test(org.junit.Test) SqlppExecutionTest(org.apache.asterix.test.runtime.SqlppExecutionTest)

Example 2 with IServletRequest

use of org.apache.hyracks.http.api.IServletRequest in project asterixdb by apache.

the class QueryCancellationServletTest method testDelete.

@Test
public void testDelete() throws Exception {
    // Creates a query cancellation servlet.
    QueryCancellationServlet cancellationServlet = new QueryCancellationServlet(new ConcurrentHashMap<>(), new String[] { "/" });
    // Adds mocked Hyracks client connection into the servlet context.
    IHyracksClientConnection mockHcc = mock(IHyracksClientConnection.class);
    cancellationServlet.ctx().put(ServletConstants.HYRACKS_CONNECTION_ATTR, mockHcc);
    // Adds a query context into the servlet context.
    IStatementExecutorContext queryCtx = new StatementExecutorContext();
    cancellationServlet.ctx().put(ServletConstants.RUNNING_QUERIES_ATTR, queryCtx);
    // Tests the case that query is not in the map.
    IServletRequest mockRequest = mockRequest("1");
    IServletResponse mockResponse = mock(IServletResponse.class);
    cancellationServlet.handle(mockRequest, mockResponse);
    verify(mockResponse, times(1)).setStatus(HttpResponseStatus.NOT_FOUND);
    // Tests the case that query is in the map.
    queryCtx.put("1", new JobId(1));
    cancellationServlet.handle(mockRequest, mockResponse);
    verify(mockResponse, times(1)).setStatus(HttpResponseStatus.OK);
    // Tests the case the client_context_id is not provided.
    mockRequest = mockRequest(null);
    cancellationServlet.handle(mockRequest, mockResponse);
    verify(mockResponse, times(1)).setStatus(HttpResponseStatus.BAD_REQUEST);
    // Tests the case that the job cancellation hit some exception from Hyracks.
    queryCtx.put("2", new JobId(2));
    Mockito.doThrow(new Exception()).when(mockHcc).cancelJob(any());
    mockRequest = mockRequest("2");
    cancellationServlet.handle(mockRequest, mockResponse);
    verify(mockResponse, times(1)).setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
Also used : StatementExecutorContext(org.apache.asterix.api.http.ctx.StatementExecutorContext) IStatementExecutorContext(org.apache.asterix.translator.IStatementExecutorContext) IHyracksClientConnection(org.apache.hyracks.api.client.IHyracksClientConnection) QueryCancellationServlet(org.apache.asterix.api.http.server.QueryCancellationServlet) IStatementExecutorContext(org.apache.asterix.translator.IStatementExecutorContext) IServletResponse(org.apache.hyracks.http.api.IServletResponse) JobId(org.apache.hyracks.api.job.JobId) IServletRequest(org.apache.hyracks.http.api.IServletRequest) Test(org.junit.Test)

Example 3 with IServletRequest

use of org.apache.hyracks.http.api.IServletRequest in project asterixdb by apache.

the class HttpServerHandler method submit.

private void submit(ChannelHandlerContext ctx, IServlet servlet, FullHttpRequest request) throws IOException {
    IServletRequest servletRequest;
    try {
        servletRequest = HttpUtil.toServletRequest(request);
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.WARNING, "Failure Decoding Request", e);
        respond(ctx, request.protocolVersion(), HttpResponseStatus.BAD_REQUEST);
        return;
    }
    handler = new HttpRequestHandler(ctx, servlet, servletRequest, chunkSize);
    submit();
}
Also used : IServletRequest(org.apache.hyracks.http.api.IServletRequest)

Example 4 with IServletRequest

use of org.apache.hyracks.http.api.IServletRequest in project asterixdb by apache.

the class RestApiServlet method initResponse.

/**
     * 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 SessionOutput initResponse(IServletRequest request, IServletResponse response) throws IOException {
    HttpUtil.setContentType(response, HttpUtil.ContentType.TEXT_PLAIN, HttpUtil.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 (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 (format == OutputFormat.CLEAN_JSON && ("true".equals(request.getParameter("lossless")) || accept.contains("lossless=true"))) {
        format = OutputFormat.LOSSLESS_JSON;
    }
    SessionOutput.ResultAppender appendHandle = (app, handle) -> app.append("{ \"").append("handle").append("\":" + " \"").append(handle).append("\" }");
    SessionConfig sessionConfig = new SessionConfig(format);
    // 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 = format == OutputFormat.CLEAN_JSON || format == OutputFormat.LOSSLESS_JSON;
    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:
            HttpUtil.setContentType(response, "application/x-adm");
            break;
        case CLEAN_JSON:
        // No need to reflect "clean-ness" in output type; fall through
        case LOSSLESS_JSON:
            HttpUtil.setContentType(response, "application/json");
            break;
        case CSV:
            // Check for header parameter or in Accept:.
            if ("present".equals(request.getParameter("header")) || accept.contains("header=present")) {
                HttpUtil.setContentType(response, "text/csv; header=present");
                sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, true);
            } else {
                HttpUtil.setContentType(response, "text/csv; header=absent");
            }
            break;
        default:
            throw new IOException("Unknown format " + format);
    }
    return new SessionOutput(sessionConfig, response.writer(), null, null, appendHandle, null);
}
Also used : IStorageComponentProvider(org.apache.asterix.common.context.IStorageComponentProvider) ResultDelivery(org.apache.asterix.translator.IStatementExecutor.ResultDelivery) GlobalConfig(org.apache.asterix.common.config.GlobalConfig) AsterixException(org.apache.asterix.common.exceptions.AsterixException) OutputFormat(org.apache.asterix.translator.SessionConfig.OutputFormat) ICcApplicationContext(org.apache.asterix.common.dataflow.ICcApplicationContext) QueryTranslator(org.apache.asterix.app.translator.QueryTranslator) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ConcurrentMap(java.util.concurrent.ConcurrentMap) Level(java.util.logging.Level) HyracksDataset(org.apache.hyracks.client.dataset.HyracksDataset) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) IServletResponse(org.apache.hyracks.http.api.IServletResponse) MetadataManager(org.apache.asterix.metadata.MetadataManager) IStatementExecutor(org.apache.asterix.translator.IStatementExecutor) ILangCompilationProvider(org.apache.asterix.compiler.provider.ILangCompilationProvider) SessionConfig(org.apache.asterix.translator.SessionConfig) IParser(org.apache.asterix.lang.common.base.IParser) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) HYRACKS_CONNECTION_ATTR(org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_CONNECTION_ATTR) Logger(java.util.logging.Logger) Statement(org.apache.asterix.lang.common.base.Statement) IStatementExecutorFactory(org.apache.asterix.translator.IStatementExecutorFactory) AbstractServlet(org.apache.hyracks.http.server.AbstractServlet) List(java.util.List) HttpUtil(org.apache.hyracks.http.server.utils.HttpUtil) HYRACKS_DATASET_ATTR(org.apache.asterix.api.http.servlet.ServletConstants.HYRACKS_DATASET_ATTR) SessionOutput(org.apache.asterix.translator.SessionOutput) IHyracksClientConnection(org.apache.hyracks.api.client.IHyracksClientConnection) ResultReader(org.apache.asterix.app.result.ResultReader) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) IServletRequest(org.apache.hyracks.http.api.IServletRequest) IParserFactory(org.apache.asterix.lang.common.base.IParserFactory) SessionOutput(org.apache.asterix.translator.SessionOutput) OutputFormat(org.apache.asterix.translator.SessionConfig.OutputFormat) SessionConfig(org.apache.asterix.translator.SessionConfig) IOException(java.io.IOException)

Example 5 with IServletRequest

use of org.apache.hyracks.http.api.IServletRequest in project asterixdb by apache.

the class QueryCancellationServletTest method mockRequest.

private IServletRequest mockRequest(String clientContextId) {
    IServletRequest mockRequest = mock(IServletRequest.class);
    FullHttpRequest mockHttpRequest = mock(FullHttpRequest.class);
    when(mockRequest.getHttpRequest()).thenReturn(mockHttpRequest);
    when(mockHttpRequest.method()).thenReturn(HttpMethod.DELETE);
    if (clientContextId != null) {
        when(mockRequest.getParameter("client_context_id")).thenReturn(clientContextId);
    }
    return mockRequest;
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) IServletRequest(org.apache.hyracks.http.api.IServletRequest)

Aggregations

IServletRequest (org.apache.hyracks.http.api.IServletRequest)6 IHyracksClientConnection (org.apache.hyracks.api.client.IHyracksClientConnection)4 IServletResponse (org.apache.hyracks.http.api.IServletResponse)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)3 Test (org.junit.Test)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 PrintWriter (java.io.PrintWriter)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 SqlppExecutionTest (org.apache.asterix.test.runtime.SqlppExecutionTest)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 HttpMethod (io.netty.handler.codec.http.HttpMethod)1 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)1 IOException (java.io.IOException)1 List (java.util.List)1 Map (java.util.Map)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1