@Test
  public void testSetVars() {
    Var v = Var.alloc("v");
    Triple t = new Triple(NodeFactory.createURI("one"), NodeFactory.createURI("two"), v);
    handler.addConstruct(t);
    Template template = query.getConstructTemplate();
    assertNotNull(template);
    List<Triple> lst = template.getTriples();
    assertEquals(1, lst.size());
    assertEquals(t, lst.get(0));

    Map<Var, Node> values = new HashMap<Var, Node>();
    values.put(v, NodeFactory.createURI("three"));
    handler.setVars(values);

    template = query.getConstructTemplate();
    assertNotNull(template);
    lst = template.getTriples();
    assertEquals(1, lst.size());
    t =
        new Triple(
            NodeFactory.createURI("one"),
            NodeFactory.createURI("two"),
            NodeFactory.createURI("three"));
    assertEquals(t, lst.get(0));
  }
  /**
   * Tests whether a query gives the same results when run both with and without a given optimizer
   *
   * @param queryStr Query
   * @param ds Dataset
   * @param opt Optimizer
   * @param expected Expected number of results
   */
  public static void test(String queryStr, Dataset ds, Symbol opt, int expected) {
    Query q = QueryFactory.create(queryStr);

    if (!q.isSelectType()) Assert.fail("Only SELECT queries are testable with this method");

    Op op = Algebra.compile(q);
    // Track current state
    boolean isEnabled = ARQ.isTrue(opt);
    boolean isDisabled = ARQ.isFalse(opt);

    try {
      // Run first without optimization
      ARQ.set(opt, false);
      ResultSetRewindable rs;
      try (QueryExecution qe = QueryExecutionFactory.create(q, ds)) {
        rs = ResultSetFactory.makeRewindable(qe.execSelect());
        if (expected != rs.size()) {
          System.err.println("Non-optimized results not as expected");
          TextOutput output = new TextOutput((SerializationContext) null);
          output.format(System.out, rs);
          rs.reset();
        }
        Assert.assertEquals(expected, rs.size());
      }

      // Run with optimization
      ARQ.set(opt, true);
      ResultSetRewindable rsOpt;
      try (QueryExecution qeOpt = QueryExecutionFactory.create(q, ds)) {
        rsOpt = ResultSetFactory.makeRewindable(qeOpt.execSelect());
        if (expected != rsOpt.size()) {
          System.err.println("Optimized results not as expected");
          TextOutput output = new TextOutput((SerializationContext) null);
          output.format(System.out, rsOpt);
          rsOpt.reset();
        }
        Assert.assertEquals(expected, rsOpt.size());
      }
      Assert.assertTrue(ResultSetCompare.isomorphic(rs, rsOpt));
    } finally {
      // Restore previous state
      if (isEnabled) {
        ARQ.set(opt, true);
      } else if (isDisabled) {
        ARQ.set(opt, false);
      } else {
        ARQ.unset(opt);
      }
    }
  }
Example #3
0
  protected void execute(String queryString, HttpAction action) {
    String queryStringLog = ServletOps.formatForLog(queryString);
    if (action.verbose) action.log.info(format("[%d] Query = \n%s", action.id, queryString));
    else action.log.info(format("[%d] Query = %s", action.id, queryStringLog));

    Query query = null;
    try {
      // NB syntax is ARQ (a superset of SPARQL)
      query = QueryFactory.create(queryString, QueryParseBase, Syntax.syntaxARQ);
      queryStringLog = formatForLog(query);
      validateQuery(action, query);
    } catch (ActionErrorException ex) {
      throw ex;
    } catch (QueryParseException ex) {
      ServletOps.errorBadRequest(
          "Parse error: \n" + queryString + "\n\r" + messageForQueryException(ex));
    }
    // Should not happen.
    catch (QueryException ex) {
      ServletOps.errorBadRequest("Error: \n" + queryString + "\n\r" + ex.getMessage());
    }

    // Assumes finished whole thing by end of sendResult.
    try {
      action.beginRead();
      Dataset dataset = decideDataset(action, query, queryStringLog);
      try (QueryExecution qExec = createQueryExecution(query, dataset); ) {
        SPARQLResult result = executeQuery(action, qExec, query, queryStringLog);
        // Deals with exceptions itself.
        sendResults(action, result, query.getPrologue());
      }
    } catch (QueryParseException ex) {
      // Late stage static error (e.g. bad fixed Lucene query string).
      ServletOps.errorBadRequest(
          "Query parse error: \n" + queryString + "\n\r" + messageForQueryException(ex));
    } catch (QueryCancelledException ex) {
      // Additional counter information.
      incCounter(action.getEndpoint().getCounters(), QueryTimeouts);
      throw ex;
    } finally {
      action.endRead();
    }
  }
Example #4
0
  /**
   * Perform the {@link QueryExecution} once.
   *
   * @param action
   * @param queryExecution
   * @param query
   * @param queryStringLog Informational string created from the initial query.
   * @return
   */
  protected SPARQLResult executeQuery(
      HttpAction action, QueryExecution queryExecution, Query query, String queryStringLog) {
    setAnyTimeouts(queryExecution, action);

    if (query.isSelectType()) {
      ResultSet rs = queryExecution.execSelect();

      // Force some query execution now.
      // If the timeout-first-row goes off, the output stream has not
      // been started so the HTTP error code is sent.

      rs.hasNext();

      // If we wanted perfect query time cancellation, we could consume
      // the result now to see if the timeout-end-of-query goes off.
      // rs = ResultSetFactory.copyResults(rs) ;

      // action.log.info(format("[%d] exec/select", action.id)) ;
      return new SPARQLResult(rs);
    }

    if (query.isConstructType()) {
      Dataset dataset = queryExecution.execConstructDataset();
      // action.log.info(format("[%d] exec/construct", action.id));
      return new SPARQLResult(dataset);
    }

    if (query.isDescribeType()) {
      Model model = queryExecution.execDescribe();
      // action.log.info(format("[%d] exec/describe", action.id)) ;
      return new SPARQLResult(model);
    }

    if (query.isAskType()) {
      boolean b = queryExecution.execAsk();
      // action.log.info(format("[%d] exec/ask", action.id)) ;
      return new SPARQLResult(b);
    }

    ServletOps.errorBadRequest("Unknown query type - " + queryStringLog);
    return null;
  }
Example #5
0
  public void analyze(final String queryName, final String queryString) throws IOException {
    final List<Object> row = new ArrayList<>();
    row.add(queryName);

    logger.info(
        "----------------------------------------------------------------------------------------------------");
    logger.info(queryName);
    logger.info(
        "----------------------------------------------------------------------------------------------------");

    final Query q = QueryFactory.create(queryString);
    final List<Var> parameterVariables = q.getProjectVars();

    final MetricVisitor metricVisitor = new MetricVisitor();
    ElementWalker.walk(q.getQueryPattern(), metricVisitor);

    row.add(metricVisitor.getVariables().size());
    logger.info(String.format("All variables: %d", metricVisitor.getVariables().size()));
    row.add(parameterVariables.size());
    logger.info(String.format("Parameter variables: %d", parameterVariables.size()));

    row.add(metricVisitor.getTriples());
    logger.info(String.format("Number of triples: %d", metricVisitor.getTriples()));
    row.add(metricVisitor.getTypeConstraints());
    logger.info(
        String.format("Number of type constraints: %d", metricVisitor.getTypeConstraints()));
    row.add(metricVisitor.getAttributeConstraints());
    logger.info(
        String.format(
            "Number of attribute constraints: %d", metricVisitor.getAttributeConstraints()));
    row.add(metricVisitor.getEdgeConstraints());
    logger.info(
        String.format("Number of edge constraints: %d", metricVisitor.getEdgeConstraints()));
    row.add(metricVisitor.getFilterConditions());
    logger.info(
        String.format("Number of filter conditions: %d", metricVisitor.getFilterConditions()));
    row.add(metricVisitor.getOptionalConditions());
    logger.info(
        String.format("Number of optional conditions: %d", metricVisitor.getOptionalConditions()));

    results.add(row);
  }
  @Override
  public QueryExecutionAndType createQueryExecutionAndType(String queryString) {

    QueryExecutionFactory qef = requireService();

    QueryExecutionAndType result;
    QueryExecution qe;
    if (qef instanceof QueryExecutionFactoryEx) {
      QueryEx queryEx = QueryFactoryEx.create(queryString);
      QueryExecutionFactoryEx tmp = (QueryExecutionFactoryEx) qef;

      qe = tmp.createQueryExecution(queryEx);
      result = new QueryExecutionAndType(qe, queryEx.getQuery().getQueryType());
    } else {

      Query query = QueryFactory.create(queryString);
      qe = qef.createQueryExecution(query);
      result = new QueryExecutionAndType(qe, query.getQueryType());
    }
    // QueryExecutionFactoryExImpl

    return result;
  }
 @Test
 public void testAddConstruct() {
   Triple t =
       new Triple(
           NodeFactory.createURI("one"),
           NodeFactory.createURI("two"),
           NodeFactory.createURI("three"));
   handler.addConstruct(t);
   Template template = query.getConstructTemplate();
   assertNotNull(template);
   List<Triple> lst = template.getTriples();
   assertEquals(1, lst.size());
   assertEquals(t, lst.get(0));
 }
Example #8
0
 private String formatForLog(Query query) {
   IndentedLineBuffer out = new IndentedLineBuffer();
   out.setFlatMode(true);
   query.serialize(out);
   return out.asString();
 }
Example #9
0
 public static Expr parse(String s, PrefixMapping pmap) {
   Query query = QueryFactory.make();
   query.setPrefixMapping(pmap);
   return parse(query, s, true);
 }