public void setUp() throws Exception {
    pm = new SimplePrefixManager();
    OBDADataFactory pfac = OBDADataFactoryImpl.getInstance();
    OBDADataFactory tfac = OBDADataFactoryImpl.getInstance();
    query = tfac.getDatalogProgram();

    LinkedList<Term> innerterms = new LinkedList<Term>();
    innerterms.add(tfac.getVariable("id"));

    //		IRIFactory fact = new IRIFactory();

    List<Term> terms = new LinkedList<Term>();
    terms.add(
        tfac.getFunction(
            pfac.getPredicate("http://obda.org/onto.owl#person-individual", 1), innerterms));

    Function body =
        tfac.getFunction(pfac.getClassPredicate("http://obda.org/onto.owl#Person"), terms);

    terms = new LinkedList<Term>();
    terms.add(tfac.getVariable("id"));
    Function head = tfac.getFunction(pfac.getPredicate("http://obda.org/predicates#q", 1), terms);

    rule1 = tfac.getCQIE(head, Collections.singletonList(body));
    query.appendRule(rule1);
  }
  // @Test
  public void testNoBody() throws RecognitionException {

    datalog = parser.parse(CQ_STRINGS[6]);

    EXPECTED_RULE_SIZE = 1;
    List<CQIE> rules = datalog.getRules();
    assertTrue("Mismatch rule size!", rules.size() == EXPECTED_RULE_SIZE);

    // Rule #1
    // -- The Head
    Function head = rules.get(0).getHead();
    assertNotNull("Head is null!", head);

    uri = head.getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://www.abc.org/1999/02/22-abc-syntax-ns#p");

    EXPECTED_HEAD_TERM_SIZE = 1;
    terms = head.getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_HEAD_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");

    // -- The Body
    EXPECTED_BODY_SIZE = 1;
    List<Function> body = rules.get(0).getBody();
    assertTrue("Body is not empty!", body.size() == 0);
  }
  // @Test
  public void testNoHead() throws RecognitionException {

    datalog = parser.parse(CQ_STRINGS[5]);

    EXPECTED_RULE_SIZE = 1;
    List<CQIE> rules = datalog.getRules();
    assertTrue("Mismatch rule size!", rules.size() == EXPECTED_RULE_SIZE);

    // Rule #1
    // -- The Head
    Function head = rules.get(0).getHead();
    assertNull("Head is not null!", head);

    // -- The Body
    EXPECTED_BODY_SIZE = 1;
    List<Function> body = rules.get(0).getBody();
    assertNotNull("Body is null!", body);
    assertTrue("Mismatch body size!", body.size() == EXPECTED_BODY_SIZE);

    // ---- Body atom #1
    uri = ((Function) body.get(0)).getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://example.org/stuff/1.0/q");

    EXPECTED_BODY_TERM_SIZE = 1;
    terms = ((Function) body.get(0)).getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_BODY_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");
  }
  // @Test
  public void testBasicInputDatalogSyntax() throws RecognitionException {

    datalog = parser.parse(CQ_STRINGS[0]);

    EXPECTED_RULE_SIZE = 1;
    List<CQIE> rules = datalog.getRules();
    assertTrue("Mismatch rule size!", rules.size() == EXPECTED_RULE_SIZE);

    // Rule #1
    // -- The Head
    Function head = rules.get(0).getHead();
    assertNotNull("Head is null!", head);

    uri = head.getFunctionSymbol().getName().toString();
    assertEquals("Mismatch predicate name!", uri, "http://www.abc.org/1999/02/22-abc-syntax-ns#p");

    EXPECTED_HEAD_TERM_SIZE = 2;
    terms = head.getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_HEAD_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");

    term = terms.get(1);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "y");

    // -- The Body
    EXPECTED_BODY_SIZE = 2;
    List<Function> body = rules.get(0).getBody();
    assertNotNull("Body is null!", body);
    assertTrue("Mismatch body size!", body.size() == EXPECTED_BODY_SIZE);

    // ---- Body atom #1
    uri = ((Function) body.get(0)).getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://example.org/stuff/1.0/q");

    EXPECTED_BODY_TERM_SIZE = 1;
    terms = ((Function) body.get(0)).getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_BODY_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");

    // ---- Body atom #2
    uri = ((Function) body.get(1)).getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://base.org/stuff/1.0/r");

    EXPECTED_BODY_TERM_SIZE = 1;
    terms = ((Function) body.get(1)).getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_BODY_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "y");
  }
  /**
   * Checking that the atoms that use the default namespace are renderered in short form and those
   * who don't have it are renderered with the full uri
   */
  public void testNamespace1() {
    pm.addPrefix(PrefixManager.DEFAULT_PREFIX, "http://obda.org/onto.owl#");
    String name =
        pm.getShortForm(query.getRules().get(0).getHead().getFunctionSymbol().toString(), true);
    assertTrue(name, name.equals("http://obda.org/predicates#q"));

    name =
        pm.getShortForm(
            ((Function) query.getRules().get(0).getBody().get(0)).getFunctionSymbol().toString(),
            true);
    assertTrue(name, name.equals("&:;Person"));

    Function atom0 = (Function) query.getRules().get(0).getBody().get(0);
    name =
        pm.getShortForm(
            ((FunctionalTermImpl) atom0.getTerms().get(0)).getFunctionSymbol().toString(), true);
    assertTrue(name, name.equals("&:;person-individual"));

    pm.addPrefix(PrefixManager.DEFAULT_PREFIX, "http://obda.org/predicates#");
    name = pm.getShortForm(query.getRules().get(0).getHead().getFunctionSymbol().toString(), true);
    assertTrue(name, name.equals("&:;q"));

    name =
        pm.getShortForm(
            ((Function) query.getRules().get(0).getBody().get(0)).getFunctionSymbol().toString(),
            true);
    assertTrue(name, name.equals("http://obda.org/onto.owl#Person"));

    atom0 = (Function) query.getRules().get(0).getBody().get(0);
    name =
        pm.getShortForm(
            ((FunctionalTermImpl) atom0.getTerms().get(0)).getFunctionSymbol().toString(), true);
    assertTrue(name, name.equals("http://obda.org/onto.owl#person-individual"));
  }
  public DatalogProgram constructDatalogProgram() {
    DatalogProgram datalog = dfac.getDatalogProgram();
    LinkedList<String> errorMessage = new LinkedList<String>();
    for (OBDAMappingAxiom axiom : mappingList) {
      try {
        // Obtain the target and source query from each mapping axiom in
        // the model.
        CQIE targetQuery = (CQIE) axiom.getTargetQuery();

        // Get the parsed sql, since it is already parsed by the mapping
        // parser
        // consider also MetaMappingExpander
        // VisitedQuery queryParsed = ...;

        OBDASQLQuery sourceQuery = (OBDASQLQuery) axiom.getSourceQuery();

        // Construct the SQL query tree from the source query
        VisitedQuery queryParsed = translator.constructParser(sourceQuery.toString());

        // Create a lookup table for variable swapping
        LookupTable lookupTable = createLookupTable(queryParsed);

        // We can get easily the table from the SQL
        ArrayList<RelationJSQL> tableList = queryParsed.getTableSet();

        // Construct the body from the source query
        ArrayList<Function> atoms = new ArrayList<Function>();
        for (RelationJSQL table : tableList) {
          // Construct the URI from the table name
          String tableName = table.getGivenName();
          String predicateName = tableName;

          // Construct the predicate using the table name
          int arity = dbMetaData.getDefinition(tableName).countAttribute();
          Predicate predicate = dfac.getPredicate(predicateName, arity);

          // Swap the column name with a new variable from the lookup
          // table
          List<Term> terms = new ArrayList<Term>();
          for (int i = 1; i <= arity; i++) {
            String columnName =
                dbMetaData.getFullQualifiedAttributeName(tableName, table.getAlias(), i);
            String termName = lookupTable.lookup(columnName);
            if (termName == null) {
              throw new RuntimeException(
                  "Column '" + columnName + "'was not found in the lookup table: ");
            }
            Term term = dfac.getVariable(termName);
            terms.add(term);
          }
          // Create an atom for a particular table
          Function atom = dfac.getFunction(predicate, terms);
          atoms.add(atom);
        }

        // For the join conditions WE STILL NEED TO CONSIDER NOT EQUI
        // JOIN
        ArrayList<Expression> joinConditions = queryParsed.getJoinCondition();
        for (Expression predicate : joinConditions) {

          Function atom = getFunction(predicate, lookupTable);
          atoms.add(atom);
        }

        // For the selection "where" clause conditions
        SelectionJSQL selection = queryParsed.getSelection();
        if (selection != null) {

          // Stack for filter function
          Stack<Function> filterFunctionStack = new Stack<Function>();

          Expression conditions = selection.getRawConditions();
          Function filterFunction = getFunction(conditions, lookupTable);
          filterFunctionStack.push(filterFunction);

          // The filter function stack must have 1 element left
          if (filterFunctionStack.size() == 1) {
            Function filterFunct = filterFunctionStack.pop();
            Function atom =
                dfac.getFunction(filterFunct.getFunctionSymbol(), filterFunct.getTerms());
            atoms.add(atom);
          } else {
            throwInvalidFilterExpressionException(filterFunctionStack);
          }
        }

        // Construct the head from the target query.
        List<Function> atomList = targetQuery.getBody();
        // for (Function atom : atomList) {
        Iterator<Function> atomListIter = atomList.iterator();

        while (atomListIter.hasNext()) {
          Function atom = atomListIter.next();
          List<Term> terms = atom.getTerms();
          List<Term> newterms = new LinkedList<Term>();
          for (Term term : terms) {
            newterms.add(updateTerm(term, lookupTable));
          }
          Function newhead = dfac.getFunction(atom.getPredicate(), newterms);
          CQIE rule = dfac.getCQIE(newhead, atoms);
          datalog.appendRule(rule);
        }

      } catch (Exception e) {
        errorMessage.add(
            "Error in mapping with id: "
                + axiom.getId()
                + " \n Description: "
                + e.getMessage()
                + " \nMapping: ["
                + axiom.toString()
                + "]");
      }
    }

    if (errorMessage.size() > 0) {
      StringBuilder errors = new StringBuilder();
      for (String error : errorMessage) {
        errors.append(error + "\n");
      }
      final String msg =
          "There was an error analyzing the following mappings. Please correct the issue(s) to continue.\n"
              + errors.toString();
      RuntimeException r = new RuntimeException(msg);
      throw r;
    }
    return datalog;
  }
  // @Test
  public void testFullNameWithUri() throws RecognitionException {

    datalog = parser.parse(CQ_STRINGS[10]);

    EXPECTED_RULE_SIZE = 1;
    List<CQIE> rules = datalog.getRules();
    assertTrue("Mismatch rule size!", rules.size() == EXPECTED_RULE_SIZE);

    // Rule #1
    // -- The Head
    Function head = rules.get(0).getHead();
    assertNotNull("Head is null!", head);

    uri = head.getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://www.abc.org/1999/02/22-abc-syntax-ns#p");

    EXPECTED_HEAD_TERM_SIZE = 2;
    terms = head.getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_HEAD_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");

    term = terms.get(1);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "y");

    // -- The Body
    EXPECTED_BODY_SIZE = 2;
    List<Function> body = rules.get(0).getBody();
    assertNotNull("Body is null!", body);
    assertTrue("Mismatch body size!", body.size() == EXPECTED_BODY_SIZE);

    // ---- Body atom #1
    uri = ((Function) body.get(0)).getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://example.org/stuff/1.0/q");

    EXPECTED_BODY_TERM_SIZE = 1;
    terms = ((Function) body.get(0)).getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_BODY_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) term).getName(), "x");

    // ---- Body atom #2
    uri = ((Function) body.get(1)).getFunctionSymbol().getName();
    assertEquals("Mismatch predicate name!", uri, "http://base.org/stuff/1.0/r");

    EXPECTED_BODY_TERM_SIZE = 2;
    terms = ((Function) body.get(1)).getTerms();
    assertEquals("Mismatch term size!", terms.size(), EXPECTED_BODY_TERM_SIZE);

    term = terms.get(0);
    assertTrue("Mismatch term type!", term instanceof FunctionalTermImpl);
    assertEquals(
        "Mismatch variable name!",
        ((FunctionalTermImpl) term).getFunctionSymbol().toString(),
        "http://example.org/stuff/1.0/s");

    // ------ Object term
    List<Term> objVarTerms = ((FunctionalTermImpl) term).getTerms();
    assertEquals("Mismatch term size!", objVarTerms.size(), 2);

    Term objVarTerm = objVarTerms.get(0);
    assertTrue("Mismatch term type!", objVarTerm instanceof Variable);
    assertEquals("Mismatch variable name!", ((Variable) objVarTerm).getName(), "y");

    objVarTerm = objVarTerms.get(1);
    assertTrue("Mismatch term type!", objVarTerm instanceof ValueConstantImpl);
    assertEquals("Mismatch variable name!", ((ValueConstantImpl) objVarTerm).getValue(), "Student");
    // ------ Object term ends.

    term = terms.get(1);
    assertTrue("Mismatch term type!", term instanceof URIConstantImpl);
    assertEquals(
        "Mismatch variable name!",
        ((URIConstantImpl) term).getURI().toString(),
        "http://example.org/stuff/1.1/FUB");
  }