net.sf.saxon.om.NodeInfo Java Examples

The following examples show how to use net.sf.saxon.om.NodeInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public List<?> translate(Object result, NamespaceContext nsContext){
    List nodeList = (List)result;
    int i = 0;
    for(Object item: nodeList){
        if(item instanceof List)
            nodeList.set(i, translate(item, nsContext));
        else{
            NodeInfo node = (NodeInfo)item;
            int type = node.getNodeKind();
            String value = "";
            if(type!=NodeType.DOCUMENT && type!=NodeType.ELEMENT)
                value = node.getStringValue();
            String localName = node.getLocalPart();
            String namespaceURI = node.getURI();
            String qualifiedName = node.getDisplayName();
            String location = SaxonNavigator.INSTANCE.getXPath(node, nsContext);
            NodeItem nodeItem = new NodeItem(type, location, value, localName, namespaceURI, qualifiedName);
            nodeItem.xml = node;
            nodeList.set(i, nodeItem);
        }
        i++;
    }
    return nodeList;
}
 
Example #2
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 6 votes vote down vote up
@Override
public List<Object> evaluate(TestCase testCase, String file) throws Exception{
    XPathFactoryImpl xpf = new XPathFactoryImpl();
    XPathEvaluator xpe = (XPathEvaluator)xpf.newXPath();
    xpe.getConfiguration().setVersionWarning(false);
    ((StandardErrorListener)xpe.getConfiguration().getErrorListener()).setRecoveryPolicy(Configuration.RECOVER_SILENTLY);
    xpe.getStaticContext().setBackwardsCompatibilityMode(true);
    xpe.setXPathVariableResolver(testCase.variableResolver);
    xpe.setXPathFunctionResolver(testCase.functionResolver);
    xpe.setNamespaceContext(testCase.nsContext);
    NodeInfo doc = xpe.getConfiguration().buildDocument(new SAXSource(new InputSource(file)));

    List<Object> results = new ArrayList<Object>(testCase.xpaths.size());
    for(XPathInfo xpathInfo: testCase.xpaths){
        if(xpathInfo.forEach==null)
            results.add(xpe.evaluate(xpathInfo.xpath, doc, xpathInfo.resultType));
        else{
            List<Object> list = new ArrayList<Object>();
            List nodeList = (List)xpe.evaluate(xpathInfo.forEach, doc, XPathConstants.NODESET);
            for(Object context: nodeList)
                list.add(xpe.evaluate(xpathInfo.xpath, context, xpathInfo.resultType));
            results.add(list);
        }
    }
    return results;
}
 
Example #3
Source File: TECore.java    From teamengine with Apache License 2.0 5 votes vote down vote up
public NodeInfo executeXSLFunction(XPathContext context, FunctionEntry fe,
        NodeInfo params) throws Exception {
  String oldFnPath = fnPath;
  CRC32 crc = new CRC32();
  crc.update((fe.getPrefix() + fe.getId()).getBytes());
  fnPath += Long.toHexString(crc.getValue()) + "/";
  XdmNode n = executeTemplate(fe, S9APIUtils.makeNode(params), context);
  fnPath = oldFnPath;
  if (n == null) {
    return null;
  }
  return n.getUnderlyingNode();
}
 
Example #4
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
public String convert(NodeInfo source){
    switch(source.getNodeKind()){
        case NodeType.ATTRIBUTE:
        case NodeType.NAMESPACE:
            return delegate.convert(source);
    }
    return super.convert(source);
}
 
Example #5
Source File: TECore.java    From teamengine with Apache License 2.0 5 votes vote down vote up
public XdmNode executeTemplate(TemplateEntry template, XdmNode params,
        XPathContext context) throws Exception {
  if (stop) {
    throw new Exception("Execution was stopped by the user.");
  }
  XsltExecutable executable = engine.loadExecutable(template,
          opts.getSourcesName());
  XsltTransformer xt = executable.load();
  XdmDestination dest = new XdmDestination();
  xt.setDestination(dest);
  if (template.usesContext() && context != null) {
    xt.setSource((NodeInfo) context.getContextItem());
  } else {
    xt.setSource(new StreamSource(new StringReader("<nil/>")));
  }
      xt.setParameter(TECORE_QNAME, new ObjValue(this));
  if (params != null) {
          xt.setParameter(TEPARAMS_QNAME, params);
  }
  // test may set global verdict, e.g. by calling ctl:fail
  if (LOGR.isLoggable( FINE)) {
    LOGR.log( FINE,
            "Executing TemplateEntry {0}" + template.getQName());
  }
  xt.transform();
  XdmNode ret = dest.getXdmNode();
      if (ret != null && LOGR.isLoggable( FINE)) {
          LOGR.log( FINE, "Output:\n" + ret.toString());
      }
  return ret;
}
 
Example #6
Source File: XmlValueHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected String toString(Object value) {
	String stringValue;
	if (value instanceof NodeInfo) {
		stringValue = ((NodeInfo) value).getStringValue();
	} else {
		stringValue = value.toString();
	}
	
	return stringValue;
}
 
Example #7
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
public String convert(NodeInfo source){
    switch(source.getNodeKind()){
        case Node.DOCUMENT_NODE:
            return "";
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE:
            return "text()";
        case Node.COMMENT_NODE:
            return "comment()";
        case Node.PROCESSING_INSTRUCTION_NODE:
            return "processing-instruction('"+source.getDisplayName() +"')";
        case Node.ELEMENT_NODE:
            String prefix = nsContext.getPrefix(source.getURI());
            String name = source.getLocalPart();
            return StringUtil.isEmpty(prefix) ? name : prefix+':'+name;
        case Node.ATTRIBUTE_NODE:
            if(Namespaces.URI_XMLNS.equals(source.getURI()))
                return "namespace::"+source.getLocalPart();
            prefix = nsContext.getPrefix(source.getURI());
            name = source.getLocalPart();
            return '@'+ (StringUtil.isEmpty(prefix) ? name : prefix+':'+name);
        case NodeType.NAMESPACE:
            return "namespace::"+source.getLocalPart();
        default:
            return null;
    }
}
 
Example #8
Source File: MonitorServlet.java    From teamengine with Apache License 2.0 4 votes vote down vote up
static public String createMonitor(XPathContext context, String url,
        String localName, String namespaceURI, NodeInfo params,
        String callId, TECore core) throws Exception {
    return createMonitor(context, url, localName, namespaceURI, params,
            null, "", callId, core);
}
 
Example #9
Source File: S9APIUtils.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public static XdmNode makeNode(NodeInfo node) {
    return new XdmNode(node);
}
 
Example #10
Source File: TECore.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public void repeatTest(XPathContext context, String localName,
        String NamespaceURI, NodeInfo params, String callId, int count,
        int pause) throws Exception {
  String key = "{" + NamespaceURI + "}" + localName;
  TestEntry test = index.getTest(key);

  if (logger != null) {
    logger.println("<testcall path=\"" + testPath + "/" + callId
            + "\"/>");
    logger.flush();
  }
  if (opts.getMode() == Test.RESUME_MODE) {
    Document doc = LogUtils.readLog(opts.getLogDir(), testPath + "/"
            + callId);
    int result = LogUtils.getResultFromLog(doc);
    if (result >= 0) {
      out.println(indent + "Test " + test.getName() + " "
              + getResultDescription(result));
              if (result == WARNING) {
        warning();
              } else if (result != PASS) {
        inheritedFailure();
      }
      return;
    }
  }
  int oldResult = verdict;
  String oldTestPath = testPath;
  testPath += "/" + callId;

  for (int i = 0; i < count; i++) {
    executeTest(test, S9APIUtils.makeNode(params), context);
    testPath = oldTestPath;
          if (verdict == FAIL && oldResult != FAIL) {
      // If the child result was FAIL and parent hasn't directly
      // failed,
      // set parent result to INHERITED_FAILURE
              verdict = INHERITED_FAILURE;

      return;
          } else if (verdict == CONTINUE) {
      // System.out.println("Pausing for..."+pause);
      if (pause > 0 && i < count - 1) {

        try {

          Thread.sleep(pause);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    } else if (verdict <= oldResult) {
      // Restore parent result if the child results aren't worse
      verdict = oldResult;
      return;

    }
  }
      verdict = FAIL;
      if (oldResult != FAIL) {
    // If the child result was FAIL and parent hasn't directly failed,
    // set parent result to INHERITED_FAILURE
          verdict = INHERITED_FAILURE;
  }

}
 
Example #11
Source File: TECore.java    From teamengine with Apache License 2.0 4 votes vote down vote up
/**
 * Runs a subtest as directed by a &lt;ctl:call-test&gt; instruction.
 *
   * @param context
   *            The context in which the subtest is executed.
   * @param localName
   *            The [local name] of the subtest.
   * @param namespaceURI
   *            The [namespace name] of the subtest.
   * @param params
   *            A NodeInfo object containing test parameters.
   * @param callId
   *            A node identifier used to build a file path reference for the
   *            test results.
   * @throws Exception
   *             If an error occcurs while executing the test.
 */
public synchronized void callTest(XPathContext context, String localName,
        String namespaceURI, NodeInfo params, String callId)
        throws Exception {
  String key = "{" + namespaceURI + "}" + localName;
  TestEntry test = index.getTest(key);
  if (logger != null) {
    logger.println("<testcall path=\"" + testPath + "/" + callId
            + "\"/>");
    logger.flush();
  }
  if (opts.getMode() == Test.RESUME_MODE) {
    Document doc = LogUtils.readLog(opts.getLogDir(), testPath + "/"
            + callId);
    int result = LogUtils.getResultFromLog(doc);
    // TODO revise the following
    if (result >= 0) {
      out.println(indent + "Test " + test.getName() + " "
              + getResultDescription(result));
              if (result == WARNING) {
        warning();
              } else if (result == CONTINUE) {
        throw new IllegalStateException(
                "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
              } else if (result != PASS) {
        inheritedFailure();
      }
      return;
    }
  }

  String oldTestPath = testPath;
  testPath += "/" + callId;
  try{
      this.verdict = executeTest(test, S9APIUtils.makeNode(params), context);
  } catch(Exception e){
  	
  } finally {
  	testPath = oldTestPath;
  }
      if (this.verdict == CONTINUE) {
    throw new IllegalStateException(
            "Error: 'continue' is not allowed when a test is called using 'call-test' instruction");
  }
  updateParentTestResult(test);
  testStack.pop();
}
 
Example #12
Source File: XPathElement.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Sets value from context node to data record. 
 * 
 * @param record
 * @param contextNode
 * @return
 * @throws TransformerException
 */
public DataRecord getValue(DataRecord record, NodeInfo contextNode) throws TransformerException {
	// get field index
	if (record == null) return null;
	if (contextNode == null) return record;
	if (cloverFieldNumber == NO_FIELD && record != null) {
		Integer i = (Integer)record.getMetadata().getFieldNamesMap().get(cloverField);
		if (i == null) 
			throw new TransformerException("Clover field name '" + cloverField + "' not found in metadata");
		cloverFieldNumber = i.intValue();
	}
	
	// get previous value
	if (previousContextNode == contextNode) {
		if (record != null) {
			if (defaultValue) {
				record.getField(cloverFieldNumber).setToDefaultValue();
			} else if (previousValue != null)	{
				assignValue(record.getField(cloverFieldNumber), previousValue);
			}
		}
		return record;
	}
	
	// get value (from xpath)
	if (xpathExpression != null) {
		nodeList = xpathExpression.evaluate(contextNode);
		previousContextNode = contextNode;

		switch(nodeList.size()) {
		case 0:
			defaultValue = true;
			record.getField(cloverFieldNumber).setToDefaultValue();
			break;
		case 1: 
			defaultValue = false;
			value = nodeList.get(0);
			if (value instanceof NodeInfo) {
				previousValue = trim ? ((NodeInfo)value).getStringValue().trim() : ((NodeInfo)value).getStringValue();
			} else {
				previousValue = trim ? value.toString().trim() : value.toString();
			}
			assignValue(record.getField(cloverFieldNumber), previousValue);
			break;
		default:
			throw new TransformerException("XPath for clover field'" + cloverField + "' contains two or more values!");
		}
	} else {
		childIterator = contextNode.iterateAxis(Axis.CHILD);
		previousValue = null;
		while ((item = (TinyNodeImpl)childIterator.next()) != null) {
			if (item.getDisplayName().equals(childNodeName)) {
				previousValue = trim ? item.getStringValue().trim() : item.getStringValue();
				break;
			}
		}
		if (previousValue == null) {
			defaultValue = true;
			record.getField(cloverFieldNumber).setToDefaultValue();
		} else {
			defaultValue = false;
			assignValue(record.getField(cloverFieldNumber), previousValue);
		}
	}
	return record;
}
 
Example #13
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
@Override
public Sequence<NodeInfo> copy(){
    return new NodeInfoSequence(nodeInfo, axis);
}
 
Example #14
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
@Override
protected NodeInfo findNext(){
    return (NodeInfo)iterator.next();
}
 
Example #15
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
NodeInfoSequence(NodeInfo nodeInfo, byte axis){
    this.nodeInfo = nodeInfo;
    this.axis = axis;
    iterator = nodeInfo.iterateAxis(axis);
}
 
Example #16
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
public String getXPath(NodeInfo node, NamespaceContext nsContext){
    if(node.getNodeKind()==NodeType.DOCUMENT)
        return "/";
    else
        return getPath(node, new XPathConvertor(nsContext), "/");
}
 
Example #17
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
@Override
public Sequence<? extends NodeInfo> children(NodeInfo node){
    return new NodeInfoSequence(node, AxisInfo.CHILD);
}
 
Example #18
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
@Override
public NodeInfo parent(NodeInfo node){
    return node.getParent();
}
 
Example #19
Source File: SaxonEngine.java    From jlibs with Apache License 2.0 4 votes vote down vote up
public static boolean isNamespaceDeclaration(NodeInfo attr){
    return Namespaces.URI_XMLNS.equals(attr.getURI()) || attr instanceof NamespaceNode;
}