private RDFRectangle toRectangle(StatementPattern pattern, BindingSet bindings) {
    Value sVal = pattern.getSubjectVar().getValue();
    Value pVal = pattern.getPredicateVar().getValue();
    Value oVal = pattern.getObjectVar().getValue();

    RDFURIRange subjectRange;
    List<String> list = new ArrayList<String>();
    if (sVal == null) {
      if (bindings.hasBinding(pattern.getSubjectVar().getName()))
        list.add(bindings.getValue(pattern.getSubjectVar().getName()).stringValue());
    } else list.add(sVal.stringValue());

    if (!list.isEmpty()) subjectRange = new RDFURIRange(list);
    else subjectRange = new RDFURIRange();

    ExplicitSetRange<URI> predicateRange;
    Set<URI> set = new HashSet<URI>();
    if (pVal == null) {
      if (bindings.hasBinding(pattern.getPredicateVar().getName()))
        set.add((URI) bindings.getValue(pattern.getPredicateVar().getName()));
    } else set.add((URI) pVal);

    if (!set.isEmpty()) predicateRange = new ExplicitSetRange<URI>(set);
    else predicateRange = new ExplicitSetRange<>();

    RDFValueRange objectRange = new RDFValueRange();
    if (oVal == null) {
      if (bindings.hasBinding(pattern.getObjectVar().getName()))
        objectRange = fillObjectRange(bindings.getValue(pattern.getObjectVar().getName()));
    } else objectRange = fillObjectRange(oVal);

    return new RDFRectangle(subjectRange, predicateRange, objectRange);
  }
 @Override
 protected double getCardinality(StatementPattern sp) {
   logger.info("get cardinality");
   try {
     Value subj = getConstantValue(sp.getSubjectVar());
     if (!(subj instanceof Resource)) {
       // can happen when a previous optimizer has inlined a
       // comparison operator.
       // this can cause, for example, the subject variable to be
       // equated to a literal value.
       // See SES-970
       subj = null;
     }
     Value pred = getConstantValue(sp.getPredicateVar());
     if (!(pred instanceof URI)) {
       // can happen when a previous optimizer has inlined a
       // comparison operator. See SES-970
       pred = null;
     }
     Value obj = getConstantValue(sp.getObjectVar());
     Value context = getConstantValue(sp.getContextVar());
     if (!(context instanceof Resource)) {
       // can happen when a previous optimizer has inlined a
       // comparison operator. See SES-970
       context = null;
     }
     //				System.out.println("begin to do kvStore.cardinalitty");
     return kvStore.cardinality((Resource) subj, (URI) pred, obj, (Resource) context);
   } catch (Exception e) {
     logger.error(
         "Failed to estimate statement pattern cardinality, falling back to generic implementation",
         e);
     return super.getCardinality(sp);
   }
 }
  /**
   * Gets the set of variables that are relevant for the constructor. This method accumulates all
   * subject, predicate and object variables from the supplied statement patterns, but ignores any
   * context variables.
   */
  private Set<Var> getConstructVars(Collection<StatementPattern> statementPatterns) {
    Set<Var> vars = new LinkedHashSet<Var>(statementPatterns.size() * 2);

    for (StatementPattern sp : statementPatterns) {
      vars.add(sp.getSubjectVar());
      vars.add(sp.getPredicateVar());
      vars.add(sp.getObjectVar());
    }

    return vars;
  }
 @Override
 public void meet(StatementPattern node) throws RepositoryException {
   Resource subj = (Resource) node.getSubjectVar().getValue();
   IRI pred = (IRI) node.getPredicateVar().getValue();
   Value obj = node.getObjectVar().getValue();
   Resource[] ctx = getContexts(node.getContextVar());
   for (RepositoryConnection member : members) {
     if (member.hasStatement(subj, pred, obj, true, ctx)) {
       return;
     }
   }
   node.replaceWith(new EmptySet());
 }
  /**
   * Provides a string representation of an SP which contains info about whether each component
   * (subj, pred, obj) is constant and its data and data type if it is constant.
   *
   * @param sp - The statement pattern to convert. (not null)
   * @return A String representation of the statement pattern that may be used to do triple
   *     matching.
   */
  public static String toStatementPatternString(final StatementPattern sp) {
    checkNotNull(sp);

    final Var subjVar = sp.getSubjectVar();
    String subj = subjVar.getName();
    if (subjVar.isConstant()) {
      subj = subj + TYPE_DELIM + URI_TYPE;
    }

    final Var predVar = sp.getPredicateVar();
    String pred = predVar.getName();
    if (predVar.isConstant()) {
      pred = pred + TYPE_DELIM + URI_TYPE;
    }

    final Var objVar = sp.getObjectVar();
    String obj = objVar.getName();
    if (objVar.isConstant()) {
      final RyaType rt = RdfToRyaConversions.convertValue(objVar.getValue());
      obj = obj + TYPE_DELIM + rt.getDataType().stringValue();
    }

    return subj + DELIM + pred + DELIM + obj;
  }
  @Override
  protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();

    URI pred = (URI) predVar.getValue();
    String predNamespace = pred.getNamespace();

    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null
        && !RDF.NAMESPACE.equals(predNamespace)
        && !SESAME.NAMESPACE.equals(predNamespace)
        && !RDFS.NAMESPACE.equals(predNamespace)
        && !EXPANDED.equals(cntxtVar)) {

      URI transPropUri = (URI) predVar.getValue();
      if (inferenceEngine.isTransitiveProperty(transPropUri)) {
        node.replaceWith(
            new TransitivePropertySP(
                sp.getSubjectVar(), sp.getPredicateVar(), sp.getObjectVar(), sp.getContextVar()));
      }
    }
  }
  private TupleExpr buildConstructor(
      TupleExpr bodyExpr,
      TupleExpr constructExpr,
      boolean explicitConstructor,
      boolean distinct,
      boolean reduced) {
    TupleExpr result = bodyExpr;

    // Retrieve all StatementPattern's from the construct expression
    List<StatementPattern> statementPatterns = StatementPatternCollector.process(constructExpr);

    Set<Var> constructVars = getConstructVars(statementPatterns);

    // Note: duplicate elimination is a two-step process. The first step
    // removes duplicates from the set of constructor variables. After this
    // step, any bnodes that need to be generated are added to each solution
    // and these solutions are projected to subject-predicate-object
    // bindings.
    // Finally, the spo-bindings are again filtered for duplicates.
    if (distinct || reduced) {
      // Create projection that removes all bindings that are not used in
      // the
      // constructor
      ProjectionElemList projElemList = new ProjectionElemList();

      for (Var var : constructVars) {
        // Ignore anonymous and constant vars, these will be handled
        // after
        // the distinct
        if (!var.isAnonymous() && !var.hasValue()) {
          projElemList.addElement(new ProjectionElem(var.getName()));
        }
      }

      result = new Projection(result, projElemList);

      // Filter the duplicates from these projected bindings
      if (distinct) {
        result = new Distinct(result);
      } else {
        result = new Reduced(result);
      }
    }

    // Create BNodeGenerator's for all anonymous variables
    Map<Var, ExtensionElem> extElemMap = new HashMap<Var, ExtensionElem>();

    for (Var var : constructVars) {
      if (var.isAnonymous() && !extElemMap.containsKey(var)) {
        ValueExpr valueExpr = null;

        if (var.hasValue()) {
          valueExpr = new ValueConstant(var.getValue());
        } else if (explicitConstructor) {
          // only generate bnodes in case of an explicit constructor
          valueExpr = new BNodeGenerator();
        }

        if (valueExpr != null) {
          extElemMap.put(var, new ExtensionElem(valueExpr, var.getName()));
        }
      }
    }

    if (!extElemMap.isEmpty()) {
      result = new Extension(result, extElemMap.values());
    }

    // Create a Projection for each StatementPattern in the constructor
    List<ProjectionElemList> projections = new ArrayList<ProjectionElemList>();

    for (StatementPattern sp : statementPatterns) {
      ProjectionElemList projElemList = new ProjectionElemList();

      projElemList.addElement(new ProjectionElem(sp.getSubjectVar().getName(), "subject"));
      projElemList.addElement(new ProjectionElem(sp.getPredicateVar().getName(), "predicate"));
      projElemList.addElement(new ProjectionElem(sp.getObjectVar().getName(), "object"));

      projections.add(projElemList);
    }

    if (projections.size() == 1) {
      result = new Projection(result, projections.get(0));

      // Note: no need to apply the second duplicate elimination step if
      // there's just one projection
    } else if (projections.size() > 1) {
      result = new MultiProjection(result, projections);

      if (distinct) {
        // Add another distinct to filter duplicate statements
        result = new Distinct(result);
      } else if (reduced) {
        result = new Reduced(result);
      }
    } else {
      // Empty constructor
      result = new EmptySet();
    }

    return result;
  }