/**
   * Type-check the expression
   *
   * @return the checked expression
   */
  public Expression typeCheck(ExpressionVisitor visitor, ItemType contextItemType)
      throws XPathException {
    operand = visitor.typeCheck(operand, contextItemType);
    if (operand instanceof Literal) {
      Literal lit =
          Literal.makeLiteral(
              (AtomicValue) evaluateItem(visitor.getStaticContext().makeEarlyEvaluationContext()));
      ExpressionTool.copyLocationInfo(this, lit);
      return lit;
    }

    // See if we can get the answer by static analysis.

    if (Cardinality.subsumes(targetCardinality, operand.getCardinality())) {
      final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
      int relation = th.relationship(operand.getItemType(th), targetType);
      if (relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY) {
        Literal lit = Literal.makeLiteral(BooleanValue.TRUE);
        ExpressionTool.copyLocationInfo(this, lit);
        return lit;
      } else if (relation == TypeHierarchy.DISJOINT) {
        // if the item types are disjoint, the result might still be true if both sequences are
        // empty
        if (!Cardinality.allowsZero(targetCardinality)
            || !Cardinality.allowsZero(operand.getCardinality())) {
          Literal lit = Literal.makeLiteral(BooleanValue.FALSE);
          ExpressionTool.copyLocationInfo(this, lit);
          return lit;
        }
      }
    }
    return this;
  }
 protected boolean isTemplateLine(Line line) {
   ProcessedRichString string = line.getRichString();
   if (string.getLines().size() == 1) {
     return false;
   }
   boolean firstOrLast = string.getLines().get(0) == line;
   if (!firstOrLast) {
     if (string.getLines().get(string.getLines().size() - 1) == line) {
       if (!(line.getParts().get(line.getParts().size() - 1) instanceof LineBreak))
         firstOrLast = true;
     }
   }
   boolean onlyLiterals = true;
   for (LinePart part : line.getParts()) {
     if (part instanceof PrintedExpression) return false;
     if (part instanceof Literal) {
       Literal literal = (Literal) part;
       if (literal instanceof LineBreak) {
         if (firstOrLast) return onlyLiterals;
         return !onlyLiterals;
       }
       if (!(new TextLine(
               literal.getLiteral().getValue(), literal.getOffset(), literal.getLength(), 0)
           .containsOnlyWhitespace())) return false;
     } else if (firstOrLast) {
       return false;
     } else {
       onlyLiterals = false;
     }
   }
   if (firstOrLast) return onlyLiterals;
   return !onlyLiterals;
 }
 private static MultiMap<Variable, Variable> surelyDifferent(DefaultRule rule) {
   Clause body = rule.antecedent();
   Clause head = rule.consequent();
   final MultiMap<Variable, Variable> different = new MultiMap<Variable, Variable>();
   for (Literal literal :
       Sugar.union(
           body.getLiteralsByPredicate(SpecialBinaryPredicates.NEQ),
           body.getLiteralsByPredicate(SpecialBinaryPredicates.GT),
           body.getLiteralsByPredicate(SpecialBinaryPredicates.LT),
           body.getLiteralsByPredicate(SpecialVarargPredicates.ALLDIFF),
           head.getLiteralsByPredicate(SpecialBinaryPredicates.NEQ),
           head.getLiteralsByPredicate(SpecialBinaryPredicates.GT),
           head.getLiteralsByPredicate(SpecialBinaryPredicates.LT),
           head.getLiteralsByPredicate(SpecialVarargPredicates.ALLDIFF))) {
     for (Term a : literal.terms()) {
       if (a instanceof Variable) {
         Variable v1 = (Variable) a;
         for (Term b : literal.terms()) {
           if (b instanceof Variable) {
             Variable v2 = (Variable) b;
             if (v1 != v2) {
               different.put(v1, v2);
             }
           }
         }
       }
     }
   }
   return different;
 }
 public static Set<DefaultRule> selectNonisomorphicDefaultRules(
     Iterable<DefaultRule> defaultRules) {
   List<Clause> candidates = new ArrayList<Clause>();
   for (DefaultRule rule : defaultRules) {
     DefaultRule preprocessed = preprocess(rule);
     candidates.add(
         new Clause(
             Sugar.<Literal>iterable(
                 preprocessed.antecedent().literals(), preprocessed.consequent().literals())));
   }
   Matching m = new Matching();
   Set<DefaultRule> retVal = new HashSet<DefaultRule>();
   for (Clause c : m.nonisomorphic(candidates)) {
     List<Literal> head = new ArrayList<Literal>();
     List<Literal> body = new ArrayList<Literal>();
     for (Literal l : c.literals()) {
       Literal newLiteral =
           new Literal(
               l.predicate().substring(l.predicate().indexOf(":") + 1), l.isNegated(), l.arity());
       for (int i = 0; i < l.arity(); i++) {
         newLiteral.set(l.get(i), i);
       }
       if (l.predicate().startsWith("antecedent:")
           || l.predicate().startsWith(SymmetricPredicates.PREFIX + "antecedent:")) {
         body.add(newLiteral);
       } else {
         head.add(newLiteral);
       }
     }
     retVal.add(new DefaultRule(new Clause(body), new Clause(head)));
   }
   return retVal;
 }
  /**
   * Query SPARQL endpoint with a SELECT query
   *
   * @param qExec QueryExecution encapsulating the query
   * @return model retrieved by querying the endpoint
   */
  private Model getSelectModel(QueryExecution qExec) {
    Model model = ModelFactory.createDefaultModel();
    Graph graph = model.getGraph();
    ResultSet results = qExec.execSelect();

    while (results.hasNext()) {
      QuerySolution sol = results.next();
      String subject;
      String predicate;
      RDFNode object;

      try {
        subject = sol.getResource("s").toString();
        predicate = sol.getResource("p").toString();
        object = sol.get("o");
      } catch (NoSuchElementException e) {
        logger.error("SELECT query does not return a (?s ?p ?o) Triple");
        continue;
      }

      Node objNode;
      if (object.isLiteral()) {
        Literal obj = object.asLiteral();
        objNode = NodeFactory.createLiteral(obj.getString(), obj.getDatatype());
      } else {
        objNode = NodeFactory.createLiteral(object.toString());
      }

      graph.add(
          new Triple(NodeFactory.createURI(subject), NodeFactory.createURI(predicate), objNode));
    }

    return model;
  }
Exemple #6
0
  public static boolean visit(
      In obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder)
      throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); // $NON-NLS-1$

    Expression lhs = obj.getLeftExpression();

    Column mdIDElement = ((ColumnReference) lhs).getMetadataObject();

    List<Expression> rhsList = obj.getRightExpressions();
    boolean createdQuery = false;
    for (Expression expr : rhsList) {

      if (expr instanceof Literal) {
        Literal literal = (Literal) expr;

        // add these as OR queries
        createEqualsQuery(
            mdIDElement,
            escapeReservedChars(literal.getValue()),
            false,
            false,
            junction,
            queryBuilder);
        createdQuery = true;
      } else {
        String msg =
            ObjectPlugin.Util.getString(
                "LuceneSearch.Unsupported_expression", //$NON-NLS-1$
                new Object[] {expr, "IN"}); // $NON-NLS-1$
        throw new TranslatorException(msg);
      }
    }
    return createdQuery;
  }
  @Override
  public Expression<K> applyInternal(And<K> input) {

    for (Expression<K> expr : input.expressions) {
      if (expr instanceof Literal) {
        Literal l = (Literal) expr;

        if (l.getValue()) {
          return copyWithoutTrue(input);
        } else {
          return Literal.getFalse();
        }
      }

      //  succeed immediately if require something or its opposite
      if (expr instanceof Not) {
        Expression<K> notChild = ((Not<K>) expr).getE();
        for (Expression<K> child : input.expressions) {
          if (child.equals(notChild)) {
            return Literal.getFalse();
          }
        }
      }
    }

    return input;
  }
 /** Return a list of all tests of the given type, according to the current filters */
 public List<Resource> findTestsOfType(Resource testType) {
   ArrayList<Resource> result = new ArrayList<>();
   StmtIterator si = testDefinitions.listStatements(null, RDF.type, testType);
   while (si.hasNext()) {
     Resource test = si.nextStatement().getSubject();
     boolean accept = true;
     // Check test status
     Literal status = (Literal) test.getProperty(RDFTest.status).getObject();
     if (approvedOnly) {
       accept = status.getString().equals(STATUS_FLAGS[0]);
     } else {
       accept = false;
       for (String STATUS_FLAG : STATUS_FLAGS) {
         if (status.getString().equals(STATUS_FLAG)) {
           accept = true;
           break;
         }
       }
     }
     // Check for blocked tests
     for (String BLOCKED_TEST : BLOCKED_TESTS) {
       if (BLOCKED_TEST.equals(test.toString())) {
         accept = false;
       }
     }
     // End of filter tests
     if (accept) {
       result.add(test);
     }
   }
   return result;
 }
 public static Literal allDiffLiteral(Clause c) {
   Literal l = new Literal(SpecialVarargPredicates.ALLDIFF, c.variables().size());
   int i = 0;
   for (Variable v : c.variables()) {
     l.set(v, i++);
   }
   return l;
 }
Exemple #10
0
 @Override
 public SecuredLiteral getLiteral(final int index)
     throws ReadDeniedException, AuthenticationRequiredException {
   checkRead();
   final Literal literal = holder.getBaseItem().getLiteral(index);
   checkRead(new Triple(holder.getBaseItem().asNode(), RDF.li(index).asNode(), literal.asNode()));
   return SecuredLiteralImpl.getInstance(getModel(), literal);
 }
Exemple #11
0
 @Override
 public String getLanguage(final int index)
     throws ReadDeniedException, AuthenticationRequiredException {
   checkRead();
   final Literal literal = holder.getBaseItem().getLiteral(index);
   checkRead(new Triple(holder.getBaseItem().asNode(), RDF.li(index).asNode(), literal.asNode()));
   return literal.getLanguage();
 }
 public boolean applicable(Example example) {
   for (Literal literal : literalMap.values()) {
     if (!literal.applicable(example)) {
       return false;
     }
   }
   return true;
 }
Exemple #13
0
 @Test
 public void testChooseLiteral() {
   Clause c = cpqr;
   while (!(c.isEmpty())) {
     Literal l = c.chooseLiteral();
     assertTrue(c.contains(l));
     c = c.reduce(l.getNegation());
   }
 }
Exemple #14
0
 @Override
 public int compareTo(Term t) {
   if (t == null) return -1;
   if (t.isLiteral()) {
     Literal tl = (Literal) t;
     if (!negated() && tl.negated()) return -1;
     else if (negated() && !tl.negated()) return 1;
   }
   return super.compareTo(t);
 }
 /**
  * Gets the right hand expression as a valid value to be assigned to the left hand side. Usually
  * returns the original rhs. However, if the lhs is of a primitive type, and the rhs is an
  * explicit null, returns a primitive value instead.
  */
 private Expression rhsAsValue() {
   if (SqlTypeUtil.isJavaPrimitive(lhsType) && (rhsType.getSqlTypeName() == SqlTypeName.NULL)) {
     if (lhsType.getSqlTypeName() == SqlTypeName.BOOLEAN) {
       return Literal.constantFalse();
     } else {
       return Literal.constantZero();
     }
   }
   return rhsExp;
 }
 public double predict(Example example) throws OperatorException {
   Iterator it = this.myLiterals.iterator();
   while (it.hasNext()) {
     Literal nextLiteral = (Literal) it.next();
     if (nextLiteral.testExample(example) == false) {
       return this.flipLabel(this.predictedLabel);
     }
   }
   return this.predictedLabel;
 }
Exemple #17
0
  @Override
  public int compare(Literal l1, Literal l2) {
    if (l1 == l2) return 0;

    int c = l1.name.compareTo(l2.name);
    if (c != 0) return c;

    if (l1.isNegation != l2.isNegation)
      return l1.isNegation ? Integer.MAX_VALUE : Integer.MIN_VALUE;

    // same name, negation sign
    // check mode and temporal
    c = l1.mode.compareTo(l2.mode);
    if (c != 0) return c;

    if (isCheckTemporal) {
      c =
          null == temporalComparator
              ? DEFAULT_TEMPORAL_COMPARTOR.compare(l1.temporal, l2.temporal)
              : temporalComparator.compare(l1.temporal, l2.temporal);

      //	System.out.println("literalComparator.checkTemporal:("+l1+","+l2+")="+c);
      if (c != 0) return c;
      // if (null == l1.temporal) {
      // if (null != l2.temporal) {
      // Temporal t2=l2.temporal;
      // if (Long.MIN_VALUE == t2.startTime) return Long.MAX_VALUE==t2.endTime?0 :Integer.MAX_VALUE;
      // return Integer.MIN_VALUE;
      // }
      // } else {
      // Temporal t1=l1.temporal;
      // if (null == l2.temporal) {
      // if (Long.MIN_VALUE == t1.startTime) return Long.MAX_VALUE==t1.endTime?0: Integer.MIN_VALUE;
      // return Integer.MAX_VALUE;
      // } else {
      // Temporal t2 = l2.temporal;
      // c = null == temporalComparator ? t1.compareTo(t2) : temporalComparator.compare(t1, t2);
      // if (c != 0) return c;
      // }
      // }
    }

    c = l1.predicates.length - l2.predicates.length;
    if (c != 0) return c;
    for (int i = 0; i < l1.predicates.length; i++) {
      if (!l1.isPredicateGrounded(i) && !l2.isPredicateGrounded(i)) {
      } else if (l1.isPredicateGrounded(i) && l2.isPredicateGrounded(i)) {
        c = l1.predicates[i].compareTo(l2.predicates[i]);
        if (c != 0) return c;
      } else {
        return l1.isPredicateGrounded(i) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
      }
    }
    return 0;
  }
Exemple #18
0
  /**
   * Test if this Body is included in a rule. It is the literals of this Body are contained in the
   * body of the other rule, or if their negation is included in the head of the other rule.
   */
  public boolean isIncludedIn(Rule otherRule) {

    Iterator iter = this.enumerateLiterals();
    while (iter.hasNext()) {
      Literal current = (Literal) iter.next();
      if (!otherRule.bodyContains(current) && !otherRule.headContains(current.getNegation())) {
        return false;
      }
    }
    return true;
  }
 @Override
 public Boolean caseRichStringLiteral(RichStringLiteral object) {
   String value = object.getValue();
   List<TextLine> lines = TextLines.splitString(value);
   if (lines.isEmpty()) {
     Literal literal = factory.createLiteral();
     literal.setLength(0);
     literal.setOffset(0);
     literal.setLiteral(object);
     addToCurrentLine(literal);
   } else {
     for (TextLine textLine : lines) {
       Literal literal = factory.createLiteral();
       literal.setLength(textLine.length());
       literal.setOffset(textLine.getRelativeOffset());
       literal.setLiteral(object);
       addToCurrentLine(literal);
       if (textLine.hasTrailingLineBreak()) {
         LineBreak lineBreak = factory.createLineBreak();
         lineBreak.setLength(textLine.getDelimiterLength());
         lineBreak.setOffset(textLine.getRelativeOffset() + textLine.length());
         lineBreak.setLiteral(object);
         addToCurrentLine(lineBreak);
         currentLine = null;
       }
     }
   }
   return Boolean.TRUE;
 }
 @Override
 public boolean equals(Object object) {
   if (object == null) {
     return false;
   }
   if (getClass() != object.getClass()) {
     return false;
   }
   Hypothesis otherHypothesis = (Hypothesis) object;
   for (Literal literal : getLiterals()) {
     if (!literal.equals(otherHypothesis.getLiteral(literal.getAttribute()))) {
       return false;
     }
   }
   return true;
 }
 /**
  * A wrapper around <code>pushInternal(Literal)</code> that checks the argument for references to
  * variables besides the one this solver is meant to process.
  *
  * @param literal the additional literal to check and then push onto the stack
  * @throws IllegalArgumentException if any variable besides the one this solver is designated for
  *     is referenced in the argument
  */
 public final void push(Literal literal) {
   if (literal.getVariable() != variable) {
     throw new IllegalArgumentException(
         "Single-variable solver for " + variable + " cannot process the literal " + literal);
   }
   pushInternal(literal);
 }
  private Literal getOptionalObjectLiteral(
      Model model, Resource subject, URI predicate, String lang) {
    Set<Value> objects = GraphUtil.getObjects(model, subject, predicate);

    Literal result = null;

    for (Value nextValue : objects) {
      if (nextValue instanceof Literal) {
        final Literal literal = (Literal) nextValue;
        if (result == null || (lang != null && lang.equals(literal.getLanguage()))) {
          result = literal;
        }
      }
    }
    return result;
  }
  @Test
  public void testUpdateWithEmptyObjectArray() throws Exception {
    UpdateAnalyzedStatement.NestedAnalyzedStatement analysis =
        analyze("update users set friends=? where other_id=0", new Object[] {new Map[0], 0})
            .nestedStatements()
            .get(0);

    Literal friendsLiteral =
        (Literal)
            analysis
                .assignments()
                .get(new Reference(USER_TABLE_INFO.getReferenceInfo(new ColumnIdent("friends"))));
    assertThat(friendsLiteral.valueType().id(), is(ArrayType.ID));
    assertEquals(DataTypes.OBJECT, ((ArrayType) friendsLiteral.valueType()).innerType());
    assertThat(((Object[]) friendsLiteral.value()).length, is(0));
  }
 @Nullable
 private Function rewriteAndValidateFields(Function function, Context context) {
   if (function.arguments().size() == 2) {
     Symbol left = function.arguments().get(0);
     Symbol right = function.arguments().get(1);
     if (left.symbolType() == SymbolType.REFERENCE && right.symbolType().isValueSymbol()) {
       Reference ref = (Reference) left;
       if (ref.info().ident().columnIdent().equals(DocSysColumns.ID)) {
         function.setArgument(
             0,
             new Reference(DocSysColumns.forTable(ref.ident().tableIdent(), DocSysColumns.UID)));
         function.setArgument(
             1,
             Literal.newLiteral(
                 Uid.createUid(
                     Constants.DEFAULT_MAPPING_TYPE, ValueSymbolVisitor.STRING.process(right))));
       } else {
         String unsupportedMessage =
             context.unsupportedMessage(ref.info().ident().columnIdent().name());
         if (unsupportedMessage != null) {
           throw new UnsupportedFeatureException(unsupportedMessage);
         }
       }
     }
   }
   return function;
 }
 private TermsFilter termsFilter(String columnName, Literal arrayLiteral) {
   TermsFilter termsFilter;
   Object values = arrayLiteral.value();
   if (values instanceof Collection) {
     termsFilter =
         new TermsFilter(
             columnName,
             getBytesRefs((Collection) values, TermBuilder.forType(arrayLiteral.valueType())));
   } else {
     termsFilter =
         new TermsFilter(
             columnName,
             getBytesRefs((Object[]) values, TermBuilder.forType(arrayLiteral.valueType())));
   }
   return termsFilter;
 }
 @Override
 protected Query applyArrayReference(
     Reference arrayReference, Literal literal, Context context) throws IOException {
   QueryBuilderHelper builder =
       QueryBuilderHelper.forType(((CollectionType) arrayReference.valueType()).innerType());
   return builder.eq(arrayReference.ident().columnIdent().fqn(), literal.value());
 }
      @Override
      public Query apply(Function input, Context context) throws IOException {
        Tuple<Reference, Literal> tuple = prepare(input);
        if (tuple == null) {
          return null;
        }
        String field = tuple.v1().info().ident().columnIdent().fqn();
        Literal literal = tuple.v2();
        CollectionType dataType = ((CollectionType) literal.valueType());

        Set values = (Set) literal.value();
        DataType innerType = dataType.innerType();
        BytesRef[] terms = getBytesRefs(values, TermBuilder.forType(innerType));
        TermsFilter termsFilter = new TermsFilter(field, terms);
        return new FilteredQuery(Queries.newMatchAllQuery(), termsFilter);
      }
    /**
     * Generates code to round an expression according to the Farrago convention. The Farrago
     * convention is to round away from zero. Rounding is performed with the following algorithm.
     *
     * <pre>
     * in = rhs;
     * if (value < 0) {
     *     in = -in;
     *     out = Math.round(in);
     *     out = -out;
     * } else {
     *     out = Math.round(in);
     * }
     * </pre>
     *
     * <p>PRECONDITION: rhsExp must be an unwrapped (not null) Java primitive
     *
     * <p>TODO: account for overflow in both unary minus and round.
     */
    private Expression roundAway() {
      // Get the primitive part of right hand side
      RelDataType inType = translator.getTypeFactory().createTypeWithNullability(rhsType, false);

      // TODO: is there any preference between stack and instance var?
      OJClass inClass = getClass(inType);
      Variable inTemp = translator.getRelImplementor().newVariable();
      translator.addStatement(declareStackVar(inClass, inTemp, rhsExp));

      OJClass outClass = getLhsClass();
      Variable outTemp = translator.getRelImplementor().newVariable();
      translator.addStatement(declareStackVar(outClass, outTemp, null));

      boolean isLong =
          translator.getFarragoTypeFactory().getClassForPrimitive(lhsType) == long.class;

      addStatement(
          new IfStatement(
              new BinaryExpression(inTemp, BinaryExpression.LESS, Literal.constantZero()),
              new StatementList(
                  assign(inTemp, minus(inClass, inTemp)),
                  assign(outTemp, round(lhsClass, inTemp, isLong)),
                  assign(outTemp, minus(outClass, outTemp))),
              new StatementList(assign(outTemp, round(lhsClass, inTemp, isLong)))));
      return outTemp;
    }
 protected void addToCurrentLine(LinePart part) {
   if (currentLine == null) {
     currentLine = factory.createLine();
     if (!(part instanceof Literal) && !result.getLines().isEmpty()) {
       Line prevLine = result.getLines().get(result.getLines().size() - 1);
       LineBreak lineBreak = (LineBreak) prevLine.getParts().get(prevLine.getParts().size() - 1);
       Literal literal = factory.createLiteral();
       literal.setLength(0);
       literal.setOffset(lineBreak.getLiteral().getValue().length());
       literal.setLiteral(lineBreak.getLiteral());
       currentLine.getParts().add(literal);
     }
     result.getLines().add(currentLine);
   }
   if (part != null) currentLine.getParts().add(part);
 }
    /**
     * Implements a cast from any Java primitive to a nullable Java primitive as a simple
     * assignment. i.e.
     *
     * <pre>
     * [NullablePrimitiveType] lhs;
     * lhs.[nullIndicator] = ...;
     * if (! lhs.[nullIndicator]) {
     *     // check overflow ...
     *     // round ...
     *     lhs.[value] = ...;
     * }
     * </pre>
     */
    private Expression castPrimitiveToNullablePrimitive() {
      ensureLhs();
      boolean nullableSource = rhsType.isNullable();
      Expression rhsIsNull;
      if (nullableSource) {
        rhsIsNull = getNullIndicator(rhsExp);
        rhsExp = getValue(rhsType, rhsExp);
      } else {
        rhsIsNull = Literal.constantFalse();
      }

      addStatement(assign(getNullIndicator(lhsExp), rhsIsNull));
      StatementList setValueBlock = new StatementList();
      StatementList oldList = borrowStmtList(setValueBlock);
      try {
        checkOverflow();
        roundAsNeeded();
        addStatement(assign(getValue(lhsType, lhsExp), new CastExpression(getLhsClass(), rhsExp)));
      } finally {
        returnStmtList(oldList);
      }
      if (nullableSource) {
        addStatement(new IfStatement(not(getNullIndicator(lhsExp)), setValueBlock));
      } else {
        addStatementList(setValueBlock);
      }
      return lhsExp;
    }