예제 #1
0
 /** Evaluate in a general context */
 public Item evaluateItem(XPathContext xpathContext) throws XPathException {
   XPathContext originalCallerContext = xpathContext;
   for (;
       originalCallerContext.getCaller() != null;
       originalCallerContext = originalCallerContext.getCaller()) ;
   return originalCallerContext.getContextItem();
 }
  /**
   * Process this instruction
   *
   * @param context the dynamic context of the transformation
   * @return a TailCall to be executed by the caller, always null for this instruction
   */
  public TailCall processLeavingTail(XPathContext context) throws XPathException {
    Controller controller = context.getController();
    SequenceReceiver out = context.getReceiver();
    int opt = options;
    int ann = annotation;

    // we may need to change the namespace prefix if the one we chose is
    // already in use with a different namespace URI: this is done behind the scenes
    // by the Outputter

    CharSequence value = expandChildren(context);
    if (schemaType != null) {
      // test whether the value actually conforms to the given type
      XPathException err =
          schemaType.validateContent(
              value,
              DummyNamespaceResolver.getInstance(),
              context.getConfiguration().getNameChecker());
      if (err != null) {
        ValidationException verr =
            new ValidationException(
                "Attribute value "
                    + Err.wrap(value, Err.VALUE)
                    + " does not the match the required type "
                    + schemaType.getDescription()
                    + ". "
                    + err.getMessage());
        verr.setErrorCode("XTTE1540");
        verr.setLocator(this);
        throw verr;
      }
    } else if (validationAction == Validation.STRICT || validationAction == Validation.LAX) {
      try {
        ann = controller.getConfiguration().validateAttribute(nameCode, value, validationAction);
      } catch (ValidationException e) {
        DynamicError err = DynamicError.makeDynamicError(e);
        String errorCode = e.getErrorCodeLocalPart();
        if (errorCode == null) {
          errorCode = (validationAction == Validation.STRICT ? "XTTE1510" : "XTTE1515");
        }
        err.setErrorCode(errorCode);
        err.setXPathContext(context);
        err.setLocator(this);
        err.setIsTypeError(true);
        throw err;
      }
    }
    try {
      out.attribute(nameCode, ann, value, locationId, opt);
    } catch (XPathException err) {
      throw dynamicError(this, err, context);
    }

    return null;
  }
예제 #3
0
 /**
  * Build the grouping table forming groups of items with equal keys. This form of grouping allows
  * a member of the population to be present in zero or more groups, one for each value of the
  * grouping key.
  */
 private void buildIndexedGroups() throws XPathException {
   HashMap index = new HashMap(40);
   XPathContext c2 = keyContext.newMinorContext();
   c2.setCurrentIterator(population);
   while (true) {
     Item item = population.next();
     if (item == null) {
       break;
     }
     processItem(index, item, c2);
   }
 }
  /**
   * Evaluate the matches() function to give a Boolean value.
   *
   * @param c The dynamic evaluation context
   * @return the result as a BooleanValue, or null to indicate the empty sequence
   * @throws XPathException on an error
   */
  public Item evaluateItem(XPathContext c) throws XPathException {
    AtomicValue sv0 = (AtomicValue) argument[0].evaluateItem(c);
    if (sv0 == null) {
      sv0 = StringValue.EMPTY_STRING;
    }
    ;

    RegularExpression re = regexp;

    if (re == null) {
      AtomicValue pat = (AtomicValue) argument[1].evaluateItem(c);
      if (pat == null) return null;

      CharSequence flags;
      if (argument.length == 2) {
        flags = "";
      } else {
        AtomicValue sv2 = (AtomicValue) argument[2].evaluateItem(c);
        if (sv2 == null) return null;
        flags = sv2.getStringValueCS();
      }

      try {
        final Platform platform = c.getConfiguration().getPlatform();
        re = platform.compileRegularExpression(pat.getStringValueCS(), true, flags);
      } catch (XPathException err) {
        DynamicError de = new DynamicError(err);
        de.setErrorCode("FORX0002");
        de.setXPathContext(c);
        throw de;
      }
    }
    return BooleanValue.get(re.containsMatch(sv0.getStringValueCS()));
  }
예제 #5
0
 public static String getType(Expression expr, XPathContext context) throws XPathException {
   ValueRepresentation vr = ExpressionTool.lazyEvaluate(expr, context, 1);
   ItemType it = Value.asValue(vr).getItemType(context.getConfiguration().getTypeHierarchy());
   if (it instanceof SchemaType) {
     return "xs:" + ((SchemaType) it).getName();
   }
   return "xs:any";
 }
예제 #6
0
 /**
  * Normalize the date and time to be in timezone Z.
  *
  * @param cc used to supply the implicit timezone, used when the value has no explicit timezone
  * @return in general, a new DateTimeValue in timezone Z, representing the same instant in time.
  *     Returns the original DateTimeValue if this is already in timezone Z.
  * @throws NoDynamicContextException if the implicit timezone is needed and is not available
  */
 public DateTimeValue normalize(XPathContext cc) throws NoDynamicContextException {
   if (hasTimezone()) {
     return (DateTimeValue) adjustTimezone(0);
   } else {
     DateTimeValue dt = (DateTimeValue) copyAsSubType(null);
     dt.setTimezoneInMinutes(cc.getImplicitTimezone());
     return (DateTimeValue) dt.adjustTimezone(0);
   }
 }
    public void process(XPathContext context) throws XPathException {
      String effMessage = message.evaluateAsString(context);
      int effOrientation = 0;
      if (orientation != null) {
        String s = orientation.evaluateAsString(context);
        try {
          effOrientation = Integer.parseInt(s);
          effOrientation = BarcodeDimension.normalizeOrientation(effOrientation);
        } catch (NumberFormatException nfe) {
          throw new ValidationException(nfe);
        } catch (IllegalArgumentException iae) {
          throw new ValidationException(iae);
        }
      }

      try {
        SequenceReceiver out = context.getReceiver();

        // Acquire BarcodeGenerator
        final BarcodeGenerator gen = BarcodeUtil.getInstance().createBarcodeGenerator(cfg);

        // Setup Canvas
        final SVGCanvasProvider svg;
        if (cfg.getAttributeAsBoolean("useNamespace", true)) {
          svg = new SVGCanvasProvider(cfg.getAttribute("prefix", "svg"), effOrientation);
        } else {
          svg = new SVGCanvasProvider(false, effOrientation);
        }
        // Generate barcode
        gen.generateBarcode(svg, effMessage);

        DocumentWrapper wrapper =
            new DocumentWrapper(
                svg.getDOM(), SVGCanvasProvider.SVG_NAMESPACE, context.getConfiguration());
        out.append(wrapper, this.getLocationId(), 1);

      } catch (ConfigurationException ce) {
        throw new DynamicError("(Barcode4J) " + ce.getMessage());
      } catch (BarcodeException be) {
        throw new DynamicError("(Barcode4J) " + be.getMessage());
      }
    }
  public Item evaluateItem(XPathContext context) throws XPathException {
    Orphan o = (Orphan) super.evaluateItem(context);
    if (schemaType != null) {
      XPathException err =
          schemaType.validateContent(
              o.getStringValueCS(),
              DummyNamespaceResolver.getInstance(),
              context.getConfiguration().getNameChecker());
      if (err != null) {
        throw new ValidationException(
            "Attribute value "
                + Err.wrap(o.getStringValueCS(), Err.VALUE)
                + " does not the match the required type "
                + schemaType.getDescription()
                + ". "
                + err.getMessage());
      }
      o.setTypeAnnotation(schemaType.getFingerprint());
      if (schemaType.isNamespaceSensitive()) {
        throw new DynamicError(
            "Cannot validate a parentless attribute whose content is namespace-sensitive");
      }
    } else if (validationAction == Validation.STRICT || validationAction == Validation.LAX) {
      try {
        int ann =
            context
                .getController()
                .getConfiguration()
                .validateAttribute(nameCode, o.getStringValueCS(), validationAction);
        o.setTypeAnnotation(ann);
      } catch (ValidationException e) {
        DynamicError err = DynamicError.makeDynamicError(e);
        err.setErrorCode(e.getErrorCodeLocalPart());
        err.setXPathContext(context);
        err.setLocator(this);
        err.setIsTypeError(true);
        throw err;
      }
    }

    return o;
  }
예제 #9
0
 /**
  * Get the dateTime value representing the nominal date/time of this transformation run. Two calls
  * within the same query or transformation will always return the same answer.
  *
  * @param context the XPath dynamic context. May be null, in which case the current date and time
  *     are taken directly from the system clock
  * @return the current xs:dateTime
  */
 public static DateTimeValue getCurrentDateTime(XPathContext context) {
   Controller c;
   if (context == null || (c = context.getController()) == null) {
     // non-XSLT/XQuery environment
     // We also take this path when evaluating compile-time expressions that require an implicit
     // timezone.
     return new DateTimeValue(new GregorianCalendar(), true);
   } else {
     return c.getCurrentDateTime();
   }
 }
예제 #10
0
 /**
  * Deliver the next output tuple. Before returning, this method must set all the variables
  * corresponding to the output tuple in the local stack frame associated with the context object
  *
  * @param context the dynamic evaluation context
  * @return true if another tuple has been generated; false if the tuple stream is exhausted. If
  *     the method returns false, the values of the local variables corresponding to this tuple
  *     stream are undefined.
  */
 @Override
 public boolean nextTuple(XPathContext context) throws XPathException {
   while (true) {
     Item next;
     if (currentIteration == null) {
       if (!base.nextTuple(context)) {
         return false;
       }
       currentIteration = forClause.getSequence().iterate(context);
       next = currentIteration.next();
       if (next == null) {
         context.setLocalVariable(
             forClause.getRangeVariable().getLocalSlotNumber(), EmptySequence.getInstance());
         if (forClause.getPositionVariable() != null) {
           context.setLocalVariable(
               forClause.getPositionVariable().getLocalSlotNumber(), Int64Value.ZERO);
         }
         currentIteration = null;
         return true;
       }
     } else {
       next = currentIteration.next();
     }
     if (next != null) {
       context.setLocalVariable(forClause.getRangeVariable().getLocalSlotNumber(), next);
       if (forClause.getPositionVariable() != null) {
         context.setLocalVariable(
             forClause.getPositionVariable().getLocalSlotNumber(),
             new Int64Value(currentIteration.position()));
       }
       return true;
     } else {
       currentIteration = null;
     }
   }
 }
예제 #11
0
  /** Supporting routine to load one external file given a URI (href) and a baseURI */
  public CharSequence readFile(String href, String baseURI, String encoding, XPathContext context)
      throws XPathException {

    final Configuration config = context.getConfiguration();
    NameChecker checker = config.getNameChecker();

    // Use the URI machinery to validate and resolve the URIs

    URI absoluteURI = getAbsoluteURI(href, baseURI);

    Reader reader;
    try {
      reader =
          context
              .getController()
              .getUnparsedTextURIResolver()
              .resolve(absoluteURI, encoding, config);
    } catch (XPathException err) {
      err.maybeSetErrorCode("XTDE1170");
      err.maybeSetLocation(this);
      throw err;
    }
    try {
      return readFile(checker, reader);
    } catch (java.io.UnsupportedEncodingException encErr) {
      XPathException e = new XPathException("Unknown encoding " + Err.wrap(encoding), encErr);
      e.setErrorCode("XTDE1190");
      throw e;
    } catch (java.io.IOException ioErr) {
      //            System.err.println("ProxyHost: " + System.getProperty("http.proxyHost"));
      //            System.err.println("ProxyPort: " + System.getProperty("http.proxyPort"));
      XPathException e = handleIOError(absoluteURI, ioErr);
      e.setLocator(this);
      throw e;
    }
  }
예제 #12
0
 /**
  * Create a GroupByIterator
  *
  * @param population iterator over the population to be grouped
  * @param keyExpression the expression used to calculate the grouping key
  * @param keyContext dynamic context for calculating the grouping key
  * @param collator Collation to be used for comparing grouping keys
  * @throws XPathException
  */
 public GroupByIterator(
     SequenceIterator population,
     Expression keyExpression,
     XPathContext keyContext,
     StringCollator collator)
     throws XPathException {
   this.population = population;
   this.keyExpression = keyExpression;
   this.keyContext = keyContext;
   this.collator = collator;
   int type =
       keyExpression
           .getItemType(keyContext.getConfiguration().getTypeHierarchy())
           .getPrimitiveType();
   this.comparer = AtomicSortComparer.makeSortComparer(collator, type, keyContext);
   buildIndexedGroups();
 }
  /** Allocate a Comparator to perform the comparisons described by this sort key component */
  public Comparator makeComparator(XPathContext context) throws XPathException {

    String orderX = order.evaluateAsString(context);

    final Configuration config = context.getConfiguration();
    final TypeHierarchy th = config.getTypeHierarchy();

    Comparator comp;
    if (collation != null) {
      comp = collation;
    } else if (collationName != null) {
      String cname = collationName.evaluateAsString(context);
      URI collationURI;
      try {
        collationURI = new URI(cname);
        if (!collationURI.isAbsolute()) {
          if (baseURI == null) {
            throw new DynamicError("Collation URI is relative, and base URI is unknown");
          } else {
            URI base = new URI(baseURI);
            collationURI = base.resolve(collationURI);
          }
        }
      } catch (URISyntaxException err) {
        throw new DynamicError("Collation name " + cname + " is not a valid URI: " + err);
      }
      try {
        comp = context.getCollation(collationURI.toString());
      } catch (XPathException e) {
        if ("FOCH0002".equals(e.getErrorCodeLocalPart())) {
          e.setErrorCode("XTDE1035");
        }
        throw e;
      }
    } else {
      String caseOrderX = caseOrder.evaluateAsString(context);
      String languageX = language.evaluateAsString(context);
      Properties props = new Properties();
      if (!languageX.equals("")) {
        props.setProperty("lang", languageX);
      }
      if (!caseOrderX.equals("#default")) {
        props.setProperty("case-order", caseOrderX);
      }
      comp = config.getPlatform().makeCollation(config, props);
    }

    if (dataTypeExpression == null) {
      int type = sortKey.getItemType(th).getAtomizedItemType().getPrimitiveType();
      comp = AtomicSortComparer.makeSortComparer(comp, type, context);
      if (!emptyLeast) {
        comp = new EmptyGreatestComparer((AtomicComparer) comp);
      }
    } else {
      String dataType = dataTypeExpression.evaluateAsString(context);
      if (dataType.equals("text")) {
        comp = new TextComparer(comp);
      } else if (dataType.equals("number")) {
        comp = NumericComparer.getInstance();
      } else {
        DynamicError err = new DynamicError("data-type on xsl:sort must be 'text' or 'number'");
        err.setErrorCode("XTDE0030");
        throw err;
      }
    }

    if (stable != null) {
      StringValue stableVal = (StringValue) stable.evaluateItem(context);
      String s = stableVal.getStringValue().trim();
      if (s.equals("yes") || s.equals("no")) {
        // no action
      } else {
        DynamicError err = new DynamicError("Value of 'stable' on xsl:sort must be 'yes' or 'no'");
        err.setErrorCode("XTDE0030");
        throw err;
      }
    }

    if (orderX.equals("ascending")) {
      return comp;
    } else if (orderX.equals("descending")) {
      return new DescendingComparer(comp);
    } else {
      DynamicError err1 = new DynamicError("order must be 'ascending' or 'descending'");
      err1.setErrorCode("XTDE0030");
      throw err1;
    }
  }
예제 #14
0
  public SequenceIterator iterate(XPathContext context) throws XPathException {
    Controller controller = context.getController();
    ObjectValue ov = (ObjectValue) controller.getParameter("{" + Test.TE_NS + "}core");
    TECore core = (TECore) ov.getObject();

    Expression[] argExpressions = getArguments();
    String xml = "<params>\n";
    List<QName> params = fe.getParams();
    for (int i = 0; i < params.size(); i++) {
      QName param = params.get(i);
      xml += "<param";
      xml += " local-name=\"" + param.getLocalPart() + "\"";
      xml += " namespace-uri=\"" + param.getNamespaceURI() + "\"";
      xml += " prefix=\"" + param.getPrefix() + "\"";
      ValueRepresentation vr = ExpressionTool.eagerEvaluate(argExpressions[i], context);
      // ValueRepresentation vr =
      // ExpressionTool.lazyEvaluate(argExpressions[i], context, 1);
      Value v = Value.asValue(vr);
      try {
        Node n = (Node) v.convertToJava(Node.class, context);
        int type = n.getNodeType();
        if (type == Node.ATTRIBUTE_NODE) {
          xml += ">\n";
          Attr attr = (Attr) n;
          xml +=
              "<value " + attr.getNodeName() + "=\"" + attr.getValue().replace("&", "&amp;") + "\"";
          if (attr.getPrefix() != null) {
            xml += " xmlns:" + attr.getPrefix() + "=\"" + attr.getNamespaceURI() + "\"";
          }
          xml += "/>\n";
          // } else if (type == Node.ELEMENT_NODE || type ==
          // Node.DOCUMENT_NODE) {
          // xml += ">\n";
          // xml += "<value>";
          // xml += DomUtils.serializeNode(n);
          // xml += "</value>\n";
        } else if (type == Node.ELEMENT_NODE) {
          xml += " type=\"node()\">\n";
          xml += "<value>";
          xml += DomUtils.serializeNode(n);
          xml += "</value>\n";
        } else if (type == Node.DOCUMENT_NODE) {
          xml += " type=\"document-node()\">\n";
          xml += "<value>";
          xml += DomUtils.serializeNode(n);
          xml += "</value>\n";
        } else {
          ItemType it = v.getItemType(context.getConfiguration().getTypeHierarchy());
          xml += " type=\"" + getTypeName(it) + "\">\n";
          xml += "<value>" + n.getNodeValue() + "</value>\n";
        }
      } catch (Exception e) {
        ItemType it = v.getItemType(context.getConfiguration().getTypeHierarchy());
        xml += " type=\"" + getTypeName(it) + "\">\n";
        xml += "<value>" + v.getStringValue() + "</value>\n";
      }
      xml += "</param>\n";
    }
    xml += "</params>";
    // System.out.println(xml);
    Source src = new StreamSource(new CharArrayReader(xml.toCharArray()));
    // XdmValue result = null;
    NodeInfo result = null;
    try {
      // result = core.executeTemplate(fe, Globals.builder.build(src),
      // context);
      NodeInfo paramsNode = core.getEngine().getBuilder().build(src).getUnderlyingNode();
      result = core.executeXSLFunction(context, fe, paramsNode);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    if (result == null) {
      return EmptyIterator.getInstance();
    } else {
      // Value v = Value.asValue(result);
      // return v.iterate();
      return result.iterateAxis(Axis.CHILD);
    }
  }
    public void process(XPathContext context) throws XPathException {
      // Prepare the SQL statement (only do this once)

      Controller controller = context.getController();
      Item conn = arguments[CONNECTION].evaluateItem(context);
      if (!(conn instanceof ObjectValue
          && ((ObjectValue) conn).getObject() instanceof Connection)) {
        DynamicError de =
            new DynamicError("Value of connection expression is not a JDBC Connection");
        de.setXPathContext(context);
        throw de;
      }
      Connection connection = (Connection) ((ObjectValue) conn).getObject();

      String dbCol = arguments[COLUMN].evaluateAsString(context);
      String dbTab = arguments[TABLE].evaluateAsString(context);
      String dbWhere = arguments[WHERE].evaluateAsString(context);

      NamePool pool = controller.getNamePool();
      int rowCode = pool.allocate("", "", rowTag);
      int colCode = pool.allocate("", "", colTag);

      PreparedStatement ps = null;
      ResultSet rs = null;
      DynamicError de = null;

      try {
        StringBuffer statement = new StringBuffer();
        statement.append("SELECT " + dbCol + " FROM " + dbTab);
        if (dbWhere != "") {
          statement.append(" WHERE " + dbWhere);
        }
        // System.err.println("-> SQL: " + statement.toString());

        // -- Prepare the SQL statement
        ps = connection.prepareStatement(statement.toString());
        controller.setUserData(this, "sql:statement", ps);

        // -- Execute Statement
        rs = ps.executeQuery();

        // -- Print out Result
        Receiver out = context.getReceiver();
        String result = "";
        int icol = rs.getMetaData().getColumnCount();
        while (rs.next()) { // next row
          // System.out.print("<- SQL : "+ rowStart);
          out.startElement(rowCode, StandardNames.XDT_UNTYPED, locationId, 0);
          for (int col = 1; col <= icol; col++) { // next column
            // Read result from RS only once, because
            // of JDBC-Specifications
            result = rs.getString(col);
            out.startElement(colCode, StandardNames.XDT_UNTYPED, locationId, 0);
            if (result != null) {
              out.characters(result, locationId, options);
            }
            out.endElement();
          }
          // System.out.println(rowEnd);
          out.endElement();
        }
        // rs.close();

        if (!connection.getAutoCommit()) {
          connection.commit();
        }

      } catch (SQLException ex) {
        de = new DynamicError("(SQL) " + ex.getMessage());
        de.setXPathContext(context);
        throw de;
      } finally {
        boolean wasDEThrown = (de != null);
        if (rs != null) {
          try {
            rs.close();
          } catch (SQLException ex) {
            de = new DynamicError("(SQL) " + ex.getMessage());
            de.setXPathContext(context);
          }
        }
        if (ps != null) {
          try {
            ps.close();
          } catch (SQLException ex) {
            de = new DynamicError("(SQL) " + ex.getMessage());
            de.setXPathContext(context);
          }
        }
        if (!wasDEThrown && de != null) {
          throw de; // test so we don't lose the real exception
        }
      }
    }
  /** Enumerate the results of the expression */
  public SequenceIterator iterate(XPathContext context) throws XPathException {

    Controller controller = context.getController();

    Item arg2;
    try {
      arg2 = argument[2].evaluateItem(context);
    } catch (XPathException e) {
      if ("XPDY0002".equals(e.getErrorCodeLocalPart())) {
        dynamicError(
            "Cannot call the key() function when there is no context item", "XTDE1270", context);
        return null;
      } else if ("XPDY0050".equals(e.getErrorCodeLocalPart())) {
        dynamicError(
            "In the key() function,"
                + " the node supplied in the third argument (or the context node if absent)"
                + " must be in a tree whose root is a document node",
            "XTDE1270",
            context);
        return null;
      } else if ("XPTY0020".equals(e.getErrorCodeLocalPart())) {
        dynamicError(
            "Cannot call the key() function when the context item is an atomic value",
            "XTDE1270",
            context);
        return null;
      }
      throw e;
    }

    NodeInfo origin = (NodeInfo) arg2;
    NodeInfo root = origin.getRoot();
    if (root.getNodeKind() != Type.DOCUMENT) {
      dynamicError(
          "In the key() function,"
              + " the node supplied in the third argument (or the context node if absent)"
              + " must be in a tree whose root is a document node",
          "XTDE1270",
          context);
      return null;
    }
    DocumentInfo doc = (DocumentInfo) root;

    int fprint = keyFingerprint;
    if (fprint == -1) {
      String givenkeyname = argument[0].evaluateItem(context).getStringValue();
      try {
        fprint =
            controller
                    .getNamePool()
                    .allocateLexicalQName(
                        givenkeyname,
                        false,
                        nsContext,
                        controller.getConfiguration().getNameChecker())
                & NamePool.FP_MASK;
      } catch (XPathException err) {
        dynamicError("Invalid key name: " + err.getMessage(), "XTDE1260", context);
      }
      if (fprint == -1) {
        dynamicError("Key '" + givenkeyname + "' has not been defined", "XTDE1260", context);
        return null;
      }
    }

    //        if (internal) {
    //            System.err.println("Using key " + fprint + " on doc " + doc);
    //        }

    // If the second argument is a singleton, we evaluate the function
    // directly; otherwise we recurse to evaluate it once for each Item
    // in the sequence.

    Expression expression = argument[1];
    SequenceIterator allResults;
    if (Cardinality.allowsMany(expression.getCardinality())) {
      final XPathContext keyContext = context;
      final DocumentInfo document = doc;
      final KeyManager keyManager = controller.getKeyManager();
      MappingFunction map =
          new MappingFunction() {
            // Map a value to the sequence of nodes having that value as a key value
            public Object map(Item item) throws XPathException {
              return keyManager.selectByKey(
                  keyFingerprint, document, (AtomicValue) item, keyContext);
            }
          };

      SequenceIterator keys = argument[1].iterate(context);
      SequenceIterator allValues = new MappingIterator(keys, map);
      allResults = new DocumentOrderIterator(allValues, LocalOrderComparer.getInstance());
    } else {
      try {
        AtomicValue keyValue = (AtomicValue) argument[1].evaluateItem(context);
        if (keyValue == null) {
          return EmptyIterator.getInstance();
        }
        KeyManager keyManager = controller.getKeyManager();
        allResults = keyManager.selectByKey(fprint, doc, keyValue, context);
      } catch (XPathException e) {
        if (e.getLocator() == null) {
          e.setLocator(this);
        }
        throw e;
      }
    }
    if (origin == doc) {
      return allResults;
    }
    SubtreeFilter filter = new SubtreeFilter();
    filter.origin = origin;
    return new ItemMappingIterator(allResults, filter);
  }
예제 #17
0
 /*@NotNull*/
 public SequenceIterator getAnother() throws XPathException {
   XPathContext c2 = keyContext.newMinorContext();
   return new GroupByIterator(population.getAnother(), keyExpression, c2, collator);
 }
예제 #18
0
  private void runAdjacent() throws SaxonApiException {
    TreeWriter treeWriter = null;
    String last = null;
    boolean open = false;

    int count = 0;
    while (source.moreDocuments()) {
      count++;
      source.read();
    }
    source.resetReader();

    DocumentSequenceIterator xsi = new DocumentSequenceIterator(); // See below
    xsi.setLast(count);

    int pos = 0;
    while (source.moreDocuments()) {
      XdmNode node = source.read();
      pos++;

      Item item = null;

      try {
        XPathCompiler xcomp = runtime.getProcessor().newXPathCompiler();
        xcomp.setBaseURI(step.getNode().getBaseURI());

        for (String prefix : groupAdjacent.getNamespaceBindings().keySet()) {
          xcomp.declareNamespace(prefix, groupAdjacent.getNamespaceBindings().get(prefix));
        }

        XPathExecutable xexec = xcomp.compile(groupAdjacent.getString());

        // From Michael Kay: http://markmail.org/message/vkb2vaq2miylgndu
        //
        // Underneath the s9api XPathExecutable is a net.sf.saxon.sxpath.XPathExpression.

        XPathExpression xexpr = xexec.getUnderlyingExpression();

        // Call createDynamicContext() on this to get an XPathDynamicContext object;

        XPathDynamicContext xdc = xexpr.createDynamicContext(node.getUnderlyingNode());

        // call getXPathContextObject() on that to get the underlying XPathContext.

        XPathContext xc = xdc.getXPathContextObject();

        // Then call XPathContext.setCurrentIterator()
        // to supply a SequenceIterator whose current() and position() methods return
        // the context item and position respectively. If there's any risk that the
        // expression will call the last() method, then it's simplest to make your
        // iterator's getProperties() return LAST_POSITION_FINDER, and implement the
        // LastPositionFinder interface, in which case last() will be implemented by
        // calling the iterator's getLastPosition() method. (Otherwise last() is
        // implemented by calling getAnother() to clone the iterator and calling next()
        // on the clone until the end of the sequence is reached).

        xsi.setPosition(pos);
        xsi.setItem(node.getUnderlyingNode());
        xc.setCurrentIterator(xsi);

        // Then evaluate the expression by calling iterate() on the
        // net.sf.saxon.sxpath.XPathExpression object.

        SequenceIterator results = xexpr.iterate(xdc);
        item = results.next();

        if (item == null) {
          throw new XProcException(
              step.getNode(), "The group-adjacent expression returned nothing.");
        }

        if (results.next() != null) {
          throw new XProcException(
              step.getNode(), "Didn't expect group-adjacent to return a sequence!");
        }
      } catch (XPathException xe) {
        throw new XProcException(xe);
      }

      //
      //  Good luck!
      //

      // FIXME: Compute effective boolean value in a more robust way
      String cur = item.getStringValue();

      if (last != null) {
        if (last.equals(cur)) {
          treeWriter.addSubtree(node);
        } else {
          if (open) {
            open = false;
            treeWriter.addEndElement();
            treeWriter.endDocument();
            result.write(treeWriter.getResult());
          }
        }
      }

      if (last == null || !last.equals(cur)) {
        last = cur;
        open = true;
        treeWriter = new TreeWriter(runtime);
        treeWriter.startDocument(step.getNode().getBaseURI());
        treeWriter.addStartElement(wrapper);
        treeWriter.startContent();
        treeWriter.addSubtree(node);
      }
    }

    if (open) {
      open = false;
      treeWriter.addEndElement();
      treeWriter.endDocument();
      result.write(treeWriter.getResult());
    }
  }
 public SequenceIterator<?> resolve(final String href, final String base, final XPathContext ctxt)
     throws XPathException {
   final Iterable<Source> sources = resolveInternal(href, base, ctxt);
   return new SeqIterator(sources, ctxt.getConfiguration());
 }