/**
   * 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()));
  }
 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";
 }
  /**
   * 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;
  }
 /**
  * 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();
 }
  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;
  }
    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());
      }
    }
Exemple #7
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;
    }
  }
 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());
 }
  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);
    }
  }
  /** 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;
    }
  }