Exemple #1
0
 public static Object getValue(
     Class<?> type, Item colItem, Configuration config, CommandContext context)
     throws XPathException, ValidationException, TransformationException {
   Object value = colItem;
   if (value instanceof AtomicValue) {
     value = getValue((AtomicValue) colItem, context);
   } else if (value instanceof Item) {
     Item i = (Item) value;
     if (XMLSystemFunctions.isNull(i)) {
       return null;
     }
     BuiltInAtomicType bat = typeMapping.get(type);
     if (bat != null) {
       AtomicValue av = new StringValue(i.getStringValueCS());
       ConversionResult cr = Converter.convert(av, bat, config.getConversionRules());
       value = cr.asAtomic();
       value = getValue((AtomicValue) value, context);
       if (value instanceof Item) {
         value = ((Item) value).getStringValue();
       }
     } else {
       value = i.getStringValue();
     }
   }
   return FunctionDescriptor.importValue(value, type);
 }
Exemple #2
0
  /**
   * Show a query producing a sequence as its result and returning the sequence to the Java
   * application in the form of an iterator. For each item in the result, its string value is
   * output.
   */
  public static void exampleToSequence() throws XPathException {
    final Configuration config = new Configuration();
    final StaticQueryContext sqc = config.newStaticQueryContext();
    final XQueryExpression exp = sqc.compileQuery("for $i in 1 to 10 return ($i * $i)");

    final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
    final SequenceIterator iter = exp.iterator(dynamicContext);
    while (true) {
      Item item = iter.next();
      if (item == null) {
        break;
      }
      System.out.println(item.getStringValue());
    }
  }
Exemple #3
0
  public void validate(Declaration decl) throws XPathException {

    // 2.0 spec has reverted to the 1.0 rule that xsl:text may not have child elements
    AxisIterator kids = iterateAxis(Axis.CHILD);
    value = StringValue.EMPTY_STRING;
    while (true) {
      Item child = kids.next();
      if (child == null) {
        break;
      } else if (child instanceof StyleElement) {
        ((StyleElement) child).compileError("xsl:text must not contain child elements", "XTSE0010");
        return;
      } else {
        value = StringValue.makeStringValue(child.getStringValueCS());
        // continue;
      }
    }
    super.validate(decl);
  }
Exemple #4
0
  public void validate() throws TransformerConfigurationException {
    checkWithinTemplate();

    // 2.0 spec has reverted to the 1.0 rule that xsl:text may not have child elements
    AxisIterator kids = iterateAxis(Axis.CHILD);
    while (true) {
      Item child = kids.next();
      if (child == null) {
        value = StringValue.EMPTY_STRING;
        break;
      } else if (child instanceof StyleElement) {
        compileError("xsl:text must not contain child elements", "XT0010");
        return;
      } else {
        value = new StringValue(child.getStringValueCS());
        break;
      }
    }
    super.validate();
  }
  /**
   * Convert an XPath value to an object in this object model. If the supplied value can be
   * converted to an object in this model, of the specified class, then the conversion should be
   * done and the resulting object returned. If the value cannot be converted, the method should
   * return null. Note that the supplied class might be a List, in which case the method should
   * inspect the contents of the Value to see whether they belong to this object model.
   *
   * @throws XPathException if the target class is explicitly associated with this object model, but
   *     the supplied value cannot be converted to the appropriate class
   */
  public Object convertXPathValueToObject(Value value, Class target, XPathContext context)
      throws XPathException {
    // We accept the object if (a) the target class is Node, Node[], or NodeList,
    // or (b) the supplied object is a node, or sequence of nodes, that wrap DOM nodes,
    // provided that the target class is Object or a collection class
    boolean requireDOM =
        (Node.class.isAssignableFrom(target)
            || (target == NodeList.class)
            || (target.isArray() && Node.class.isAssignableFrom(target.getComponentType())));

    // Note: we allow the declared type of the method argument to be a subclass of Node. If the
    // actual
    // node supplied is the wrong kind of node, this will result in a Java exception.

    boolean allowDOM =
        (target == Object.class
            || target.isAssignableFrom(ArrayList.class)
            || target.isAssignableFrom(HashSet.class)
            || (target.isArray() && target.getComponentType() == Object.class));
    if (!(requireDOM || allowDOM)) {
      return null;
    }
    List nodes = new ArrayList(20);

    SequenceIterator iter = value.iterate(context);
    while (true) {
      Item item = iter.next();
      if (item == null) {
        break;
      }
      if (item instanceof VirtualNode) {
        Object o = ((VirtualNode) item).getUnderlyingNode();
        if (o instanceof Node) {
          nodes.add(o);
        } else {
          if (requireDOM) {
            DynamicError err =
                new DynamicError(
                    "Extension function required class "
                        + target.getName()
                        + "; supplied value of class "
                        + item.getClass().getName()
                        + " could not be converted");
            throw err;
          }
          ;
        }
      } else if (requireDOM) {
        if (item instanceof NodeInfo) {
          nodes.add(NodeOverNodeInfo.wrap((NodeInfo) item));
        } else {
          DynamicError err =
              new DynamicError(
                  "Extension function required class "
                      + target.getName()
                      + "; supplied value of class "
                      + item.getClass().getName()
                      + " could not be converted");
          throw err;
        }
      } else {
        return null; // DOM Nodes are not actually required; let someone else try the conversion
      }
    }

    if (nodes.size() == 0 && !requireDOM) {
      return null; // empty sequence supplied - try a different mapping
    }
    if (Node.class.isAssignableFrom(target)) {
      if (nodes.size() != 1) {
        DynamicError err =
            new DynamicError(
                "Extension function requires a single DOM Node"
                    + "; supplied value contains "
                    + nodes.size()
                    + " nodes");
        throw err;
      }
      return nodes.get(0);
      // could fail if the node is of the wrong kind
    } else if (target == NodeList.class) {
      return new DOMNodeList(nodes);
    } else if (target.isArray() && target.getComponentType() == Node.class) {
      Node[] array = new Node[nodes.size()];
      nodes.toArray(array);
      return array;
    } else if (target.isAssignableFrom(ArrayList.class)) {
      return nodes;
    } else if (target.isAssignableFrom(HashSet.class)) {
      return new HashSet(nodes);
    } else {
      // after all this work, give up
      return null;
    }
  }
  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());
    }
  }