javax.xml.xpath.XPathConstants Java Examples

The following examples show how to use javax.xml.xpath.XPathConstants. 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: UniverseClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private String getValue(String response, String xPathString) throws ParserConfigurationException,
    IOException, SAXException, XPathExpressionException {
  try (InputStream xmlStream = new ByteArrayInputStream(response.getBytes())) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xmlStream);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(xPathString);
    Node tokenNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
    if (tokenNode != null) {
      return tokenNode.getTextContent();
    }
  }
  return null;
}
 
Example #2
Source File: Framework.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public Framework(final String name, final File bsFile) {
    super(name, null);
    try {
        final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile();
        path = pathf.getParentFile().getParentFile().getCanonicalPath();
    } catch (IOException x) {
        throw new RuntimeException(x);
    }
    binaries = findBinaries(path, name);

    pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase();
    try {
        rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE);
    } catch (final XPathExpressionException e) { throw new RuntimeException(e); }
    protocols = new ArrayList<Protocol>();
    categories = new ArrayList<Category>();
}
 
Example #3
Source File: MainClassCastExceptionError.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public static void main (final String [] args) throws Exception
{
  final Document aDoc = DocumentBuilderFactory.newInstance ()
                                              .newDocumentBuilder ()
                                              .getDOMImplementation ()
                                              .createDocument (null, null, null);
  final Node eRoot = aDoc.appendChild (aDoc.createElement ("root"));
  eRoot.appendChild (aDoc.createElement ("para")).appendChild (aDoc.createTextNode ("100"));
  eRoot.appendChild (aDoc.createElement ("para")).appendChild (aDoc.createTextNode ("200"));
  System.out.println (XMLWriter.getNodeAsString (aDoc));

  final XPathExpression aExpr = XPathFactory.newInstance (XPathFactory.DEFAULT_OBJECT_MODEL_URI,
                                                          "net.sf.saxon.xpath.XPathFactoryImpl",
                                                          ClassLoaderHelper.getSystemClassLoader ())
                                            .newXPath ()
                                            .compile ("distinct-values(//para)");
  final Object aResult = aExpr.evaluate (aDoc, XPathConstants.NODESET);
  System.out.println (aResult);
}
 
Example #4
Source File: RssParser.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private boolean isApplicableToVersion(Node item, String version, String build) throws XPathExpressionException {
  boolean hasRestriction = false;
  NodeList categories = (NodeList) getXPath("atom:category").evaluate(item, XPathConstants.NODESET);
  for (int i = 0; i < categories.getLength(); i++) {
    Element elCategory = (Element) categories.item(i);
    String category = elCategory.getAttribute("term");
    if (!Strings.isNullOrEmpty(category)) {
      if (category.startsWith("__version")) {
        hasRestriction = true;
        if (compareCategory(category, "version", version)) {
          return true;
        }
      }
      if (category.startsWith("__build")) {
        hasRestriction = true;
        if (compareCategory(category, "build", build)) {
          return true;
        }
      }
    }
  }
  return !hasRestriction;
}
 
Example #5
Source File: OXPath.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Evaluates a given XPATH and returns the result as a single node.
 * 
 * @param expression the XPATH expression.
 * @param context the DOM context.
 * @return the result as a single node.
 * @throws XPathExpressionException in case of XPATH failure.
 */
public Node one(final String expression, final Object context) throws XPathExpressionException {
	Element doc = (Element) (context instanceof Document ? ((Document)context).getDocumentElement() : context);
	String [] members = expression.split("/");
	List<Node> current = null;
	String firstExp = members[0];
	final XPathExpression exp = xpath(firstExp);
	NodeList topLevel = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
	if (members.length == 1) {
		current = new ArrayList<Node>();
		for (int i = 0; i < topLevel.getLength(); i++) {
			current.add(topLevel.item(i));
		}
	} else {
		for (int i = 1; i < members.length; i++) {
			current = (i==1) ? select(topLevel, members[i]) : select(current, members[i]);
		}
	}
	
	return (current != null && current.size() > 0) ? current.get(0) : null;
}
 
Example #6
Source File: CompositeTypeTest.java    From simple-binary-encoding with Apache License 2.0 6 votes vote down vote up
private static Map<String, Type> parseTestXmlWithMap(final String xPathExpr, final String xml)
    throws ParserConfigurationException, XPathExpressionException, IOException, SAXException
{
    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
        new ByteArrayInputStream(xml.getBytes()));
    final XPath xPath = XPathFactory.newInstance().newXPath();
    final NodeList list = (NodeList)xPath.compile(xPathExpr).evaluate(document, XPathConstants.NODESET);
    final Map<String, Type> map = new HashMap<>();

    final ParserOptions options = ParserOptions.builder().stopOnError(true).suppressOutput(true).build();
    document.setUserData(XmlSchemaParser.ERROR_HANDLER_KEY, new ErrorHandler(options), null);

    for (int i = 0, size = list.getLength(); i < size; i++)
    {
        final Type t = new CompositeType(list.item(i));
        map.put(t.name(), t);
    }

    return map;
}
 
Example #7
Source File: XmlUtil.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Evaluates the given xpath against the given document and produces string
 * which satisfy the xpath expression.
 *
 * @param document the document to search against the given xpath
 * @param xpath the xpath expression
 * @return a string which satisfy the xpath expression against the given
 * document.
 * @throws XmlUtilException if an error occurred
 */
public static String evaluateString(Document document, String xpath) throws XmlUtilException {
    if (document == null || xpath == null) {
        throw new XmlUtilException("Unable to evaluate null document or xpath");
    }

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpathObject = xpathFactory.newXPath();
    xpathObject.setNamespaceContext(new UniversalNamespaceCache(document));

    String result = null;
    try {
        XPathExpression expr = xpathObject.compile(xpath);
        result = (String) expr.evaluate(document, XPathConstants.STRING);
    } catch (XPathExpressionException xpee) {
        throw new XmlUtilException(xpee);
    }

    if (result == null) {
        throw new XmlUtilException("Evaluation caused a null result");
    }

    return result;
}
 
Example #8
Source File: Sprite.java    From DeskChan with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected static Insets getMarginFromFile(Document document){
    Insets standard = new Insets(30, 30, 30, 30);
    if (document == null)
        return standard;

    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile("//margin");

        NamedNodeMap marginTags = ((NodeList) expression.evaluate(document, XPathConstants.NODESET)).item(0).getAttributes();
        return new Insets(
                Double.parseDouble(marginTags.getNamedItem("top").getTextContent()),
                Double.parseDouble(marginTags.getNamedItem("right").getTextContent()),
                Double.parseDouble(marginTags.getNamedItem("bottom").getTextContent()),
                Double.parseDouble(marginTags.getNamedItem("left").getTextContent())
        );
    } catch (Exception e) {
        return standard;
    }
}
 
Example #9
Source File: XMLUtil.java    From webdsl with Apache License 2.0 6 votes vote down vote up
public static List<Node> getNodesByXPath( Node n, String xpath, short nodeType){
	XPath xPath = XPathFactory.newInstance().newXPath();
	NodeList nodeList;
	java.util.ArrayList<Node> nodes = new java.util.ArrayList<Node>();
	try {
		nodeList = (NodeList)xPath.evaluate(xpath,
		        n, XPathConstants.NODESET);			
		for (int i=0; i<nodeList.getLength(); i++){
            Node node = nodeList.item(i);
            if (nodeType == ANYNODE || node.getNodeType()==nodeType) nodes.add(node);
        }
	} catch (XPathExpressionException e) {
		Logger.error(e);
	}
	return nodes;        
}
 
Example #10
Source File: XPathFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * @return the nodes correspond to specified xpath.
 * @param root context in which to find the node.
 * @param xpath location path for the attribute or element.
 */
public List<Node> findNodes(Document root, String xpathExpression) {
    if (root == null || root.getDocumentElement() == null) {
        return Collections.emptyList();
    }
    
    init(root, xpathExpression);
    if (! isReadyForEvaluation()) {
        return new ArrayList<Node>();
    }
    
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(getNamespaceContext());
    NodeList result = null;
    try {
        result = (NodeList) xpath.evaluate(getFixedUpXpath(), root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e.getCause().getLocalizedMessage());
    }
    assert(result != null);
    List<Node> ret = new ArrayList<Node>();
    for (int i=0; i<result.getLength(); i++) {
        ret.add((Node) result.item(i));
    }
    return ret;
}
 
Example #11
Source File: XPathQualifierResolver.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void handleCompoundMap(Node baseNode, List<Map<String, String>> maps, ResolverConfig config, XPath xPath) throws XPathExpressionException {
	Map<String, String> map = new HashMap<String, String>();
	for (String attributeName : config.getExpressionMap().keySet()) {
		String xPathExpression = config.getExpressionMap().get(attributeName);
		NodeList attributes = (NodeList)xPath.evaluate(xPathExpression, baseNode, XPathConstants.NODESET);
		if (attributes.getLength() > 1) {
			throw new RiceRuntimeException("Found more than more XPath result for an attribute in a compound attribute set for attribute: " + attributeName + " with expression " + xPathExpression);
		} else if (attributes.getLength() != 0) {
			String attributeValue = ((Element)attributes.item(0)).getTextContent();
			if (LOG.isDebugEnabled()) {
				LOG.debug("Adding values to compound Map<String, String>: " + attributeName + "::" + attributeValue);
			}
			map.put(attributeName, attributeValue);
		}
	}
	maps.add(map);
}
 
Example #12
Source File: Internalizer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private NodeList evaluateXPathMultiNode(Node bindings, Node target, String expression, NamespaceContext namespaceContext) {
    NodeList nlst;
    try {
        xpath.setNamespaceContext(namespaceContext);
        nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        reportError((Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATION_ERROR(e.getMessage()), e);
        return null; // abort processing this <jaxb:bindings>
    }

    if (nlst.getLength() == 0) {
        reportError((Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NO_TARGET(expression));
        return null; // abort
    }

    return nlst;
}
 
Example #13
Source File: Deployment.java    From lambadaframework with MIT License 6 votes vote down vote up
/**
 * Get latest version number using maven-metadata.xml file
 * <p>
 * This information is used to determine which version deploy when a specific version is not given as a parameter
 *
 * @return String
 */
protected String getLatestVersion() {
    try {

        String bucketKey = "releases" + seperator + this.project.getGroupId().replace(".", seperator)
                + seperator
                + this.project.getArtifactId()
                + seperator;

        String metadataFileName = bucketKey + "maven-metadata.xml";

        if (log != null)
            log.info("Getting the latest project info from s3://" + getBucketName() + metadataFileName);


        Document doc = loadXMLFromString(S3.getFile(getBucketName(), metadataFileName));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/metadata/versioning/latest");
        return ((Node) expr.evaluate(doc, XPathConstants.NODE)).getTextContent();
    } catch (Exception e) {
        throw new RuntimeException("Error at get maven metadata. Did you deploy the compiled project to S3 Bucket?", e);
    }
}
 
Example #14
Source File: XmlUtils.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * Search by XPath in XML
 * @param xml XML
 * @param xpath xpath
 * @return Search result
 */
public static Optional<String> getXmlByXpath(String xml, String xpath)
{
    return XPATH_FACTORY.apply(xPathFactory -> {
        try
        {
            InputSource source = createInputSource(xml);
            NodeList nodeList = (NodeList) xPathFactory.newXPath().evaluate(xpath, source, XPathConstants.NODESET);
            Node singleNode = nodeList.item(0);
            Properties outputProperties = new Properties();
            outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
            return transform(new DOMSource(singleNode), outputProperties);
        }
        catch (XPathExpressionException e)
        {
            throw new IllegalStateException(e.getMessage(), e);
        }
    });
}
 
Example #15
Source File: ModuleManager.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads module settings from a module element. The settings include
 * autostarting, priority, name read from attributes of the element
 * and useService elements defined inside the module element.
 * 
 * @param e The module element.
 * @param source The source identifier for the module, could be the file name
 *                where the module comes from or something else.
 * @return Parsed module settings.
 * @throws ClassNotFoundException 
 */
public static ModuleSettings parseXMLModuleSettings(Element e,String source) throws ClassNotFoundException {
    if(xpath==null) xpath=XPathFactory.newInstance().newXPath();
    
    ModuleSettings settings=new ModuleSettings();
    
    String autostartS=e.getAttribute("autostart");
    if(autostartS!=null && autostartS.equalsIgnoreCase("false")) settings.autoStart=false;
    else settings.autoStart=true;
    
    String priorityS=e.getAttribute("priority");
    if(priorityS!=null && priorityS.length()>0) settings.servicePriority=Integer.parseInt(priorityS);
    
    String name=e.getAttribute("name");
    if(name!=null && name.length()>0) settings.name=name;
    
    settings.source=source;
    
    try{
        NodeList nl=(NodeList)xpath.evaluate("useService",e,XPathConstants.NODESET);
        for(int j=0;j<nl.getLength();j++){
            Element e2=(Element)nl.item(j);
            String service=e2.getAttribute("service");
            String value=e2.getAttribute("value");
            
            Class serviceClass=Class.forName(service);
            if(!Module.class.isAssignableFrom(serviceClass)){
                throw new ClassCastException("The specified service is not a module");
            }
            settings.serviceNames.put((Class<? extends Module>)serviceClass,value);
        }
    }catch(XPathExpressionException xpee){
        throw new RuntimeException(xpee); // hardcoded xpath expressions so this shouldn't really happen
    }        

    return settings;
}
 
Example #16
Source File: XmlSchemaParser.java    From simple-binary-encoding with Apache License 2.0 5 votes vote down vote up
/**
 * Take an {@link InputSource} and parse it generating map of template ID to Message objects, types, and schema.
 *
 * @param is      source from which schema is read. Ideally it will have the systemId property set to resolve
 *                relative references.
 * @param options to be applied during parsing.
 * @return {@link MessageSchema} encoding for the schema.
 * @throws Exception on parsing error.
 */
public static MessageSchema parse(final InputSource is, final ParserOptions options) throws Exception
{
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    if (options.xIncludeAware())
    {
        factory.setNamespaceAware(true);
        factory.setXIncludeAware(true);
        factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
    }

    final Document document = factory.newDocumentBuilder().parse(is);
    final XPath xPath = XPathFactory.newInstance().newXPath();

    final ErrorHandler errorHandler = new ErrorHandler(options);
    document.setUserData(ERROR_HANDLER_KEY, errorHandler, null);

    final Map<String, Type> typeByNameMap = findTypes(document, xPath);
    errorHandler.checkIfShouldExit();

    final Map<Long, Message> messageByIdMap = findMessages(document, xPath, typeByNameMap);
    errorHandler.checkIfShouldExit();

    final Node schemaNode = (Node)xPath.compile(MESSAGE_SCHEMA_XPATH_EXPR).evaluate(document, XPathConstants.NODE);
    final MessageSchema messageSchema = new MessageSchema(schemaNode, typeByNameMap, messageByIdMap);
    errorHandler.checkIfShouldExit();

    return messageSchema;
}
 
Example #17
Source File: CienaWaveserverAiDeviceDescription.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<PortDescription> discoverPortDetails() {
    log.info("Adding ports for Waveserver Ai device");
    List<PortDescription> ports = new ArrayList<>();

    Device device = getDevice(handler().data().deviceId());
    NetconfSession session = getNetconfSession();

    try {
        XPath xp = XPathFactory.newInstance().newXPath();
        Node nodeListItem;

        Node node = TEMPLATE_MANAGER.doRequest(session, "discoverPortDetails");
        NodeList nodeList = (NodeList) xp.evaluate("waveserver-ports/ports", node, XPathConstants.NODESET);
        int count = nodeList.getLength();
        for (int i = 0; i < count; ++i) {
            nodeListItem = nodeList.item(i);
            DefaultAnnotations annotationPort = DefaultAnnotations.builder()
                    .set(AnnotationKeys.PORT_NAME, xp.evaluate("port-id/text()", nodeListItem))
                    .set(AnnotationKeys.PROTOCOL, xp.evaluate("id/type/text()", nodeListItem))
                    .build();
            String port = xp.evaluate("port-id/text()", nodeListItem);
            ports.add(DefaultPortDescription.builder()
                      .withPortNumber(PortNumber.portNumber(
                              portIdConvert(port), port))
                      .isEnabled(portStateConvert(
                              xp.evaluate("state/operational-state/text()", nodeListItem)))
                      .portSpeed(portSpeedToLong(xp.evaluate("id/speed/text()", nodeListItem)))
                      .type(Port.Type.PACKET)
                      .annotations(annotationPort)
                      .build());
        }
    } catch (NetconfException | XPathExpressionException e) {
        log.error("Unable to retrieve port information for device {}, {}", device.chassisId(), e);
    }
    return ImmutableList.copyOf(ports);
}
 
Example #18
Source File: Http.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXML(String url, Vertex xmlObject, String xpath, Map<String, String> headers, Network network) {
	log("POST XML", Level.INFO, url, xpath);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpPOST(url, "application/xml", data, headers);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example #19
Source File: DOMDocumentTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void findTextWithXPath() throws XPathExpressionException {
	DOMDocument document = DOMParser.getInstance().parse("<a><b><c>XXXX</c></b></a>", "test", null);

	XPath xPath = XPathFactory.newInstance().newXPath();
	Object result = xPath.evaluate("/a/b/c/text()", document, XPathConstants.NODE);
	assertNotNull(result);
	assertTrue(result instanceof DOMText);
	DOMText text = (DOMText) result;
	assertEquals("XXXX", text.getData());

	result = xPath.evaluate("/a/b/c/text()", document, XPathConstants.STRING);
	assertNotNull(result);
	assertEquals("XXXX", result.toString());
}
 
Example #20
Source File: NodeAssert.java    From initializr with Apache License 2.0 5 votes vote down vote up
ListAssert<Node> nodesAtPath(String xpath) {
	try {
		NodeList nodeList = (NodeList) this.xpath.evaluate(xpath, this.actual, XPathConstants.NODESET);
		return new ListAssert<>(toList(nodeList));
	}
	catch (XPathExpressionException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #21
Source File: XmlSchemaParser.java    From simple-binary-encoding with Apache License 2.0 5 votes vote down vote up
/**
 * Scan XML for all types (encodedDataType, compositeType, enumType, and setType) and save in map.
 *
 * @param document for the XML parsing
 * @param xPath    for XPath expression reuse
 * @return {@link java.util.Map} of name {@link java.lang.String} to Type
 * @throws Exception on parsing error.
 */
public static Map<String, Type> findTypes(final Document document, final XPath xPath) throws Exception
{
    final Map<String, Type> typeByNameMap = new HashMap<>();

    typeByNameMap.put("char", new EncodedDataType("char", REQUIRED, null, null, CHAR, 1, false));
    typeByNameMap.put("int8", new EncodedDataType("int8", REQUIRED, null, null, INT8, 1, false));
    typeByNameMap.put("int16", new EncodedDataType("int16", REQUIRED, null, null, INT16, 1, false));
    typeByNameMap.put("int32", new EncodedDataType("int32", REQUIRED, null, null, INT32, 1, false));
    typeByNameMap.put("int64", new EncodedDataType("int64", REQUIRED, null, null, INT64, 1, false));
    typeByNameMap.put("uint8", new EncodedDataType("uint8", REQUIRED, null, null, UINT8, 1, false));
    typeByNameMap.put("uint16", new EncodedDataType("uint16", REQUIRED, null, null, UINT16, 1, false));
    typeByNameMap.put("uint32", new EncodedDataType("uint32", REQUIRED, null, null, UINT32, 1, false));
    typeByNameMap.put("uint64", new EncodedDataType("uint64", REQUIRED, null, null, UINT64, 1, false));
    typeByNameMap.put("float", new EncodedDataType("float", REQUIRED, null, null, FLOAT, 1, false));
    typeByNameMap.put("double", new EncodedDataType("double", REQUIRED, null, null, DOUBLE, 1, false));

    forEach((NodeList)xPath.compile(TYPE_XPATH_EXPR).evaluate(document, XPathConstants.NODESET),
        (node) -> addTypeWithNameCheck(typeByNameMap, new EncodedDataType(node), node));

    forEach((NodeList)xPath.compile(COMPOSITE_XPATH_EXPR).evaluate(document, XPathConstants.NODESET),
        (node) -> addTypeWithNameCheck(typeByNameMap, new CompositeType(node), node));

    forEach((NodeList)xPath.compile(ENUM_XPATH_EXPR).evaluate(document, XPathConstants.NODESET),
        (node) -> addTypeWithNameCheck(typeByNameMap, new EnumType(node), node));

    forEach((NodeList)xPath.compile(SET_XPATH_EXPR).evaluate(document, XPathConstants.NODESET),
        (node) -> addTypeWithNameCheck(typeByNameMap, new SetType(node), node));

    return typeByNameMap;
}
 
Example #22
Source File: XPathSearchableAttribute.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public List<DocumentAttribute> extractDocumentAttributes(@WebParam(name = "extensionDefinition") ExtensionDefinition extensionDefinition,
                                                         @WebParam(name = "documentWithContent") DocumentWithContent documentWithContent) {
    List<DocumentAttribute> attribs = new ArrayList<DocumentAttribute>(1);
    String appContent = documentWithContent.getDocumentContent().getApplicationContent();
    XPath xpath = XPathHelper.newXPath();
    try {
        //InputSource source = new StringReader(appContent);
        Element source = DocumentBuilderFactory
                .newInstance().newDocumentBuilder().parse(new InputSource(new BufferedReader(new StringReader(appContent)))).getDocumentElement();
        String result = (String) xpath.evaluate(xpathExpression, source, XPathConstants.STRING);
        // xpath has no concept of null node, missing text values are the empty string
        if (StringUtils.isNotEmpty(result)) {
            try {
                attribs.add(createAttribute(this.key, result, this.dataType));
            } catch (ParseException pe) {
                log.error("Error converting value '" + result + "' to type '" + this.dataType + "'");
            }
        }
    } catch (XPathExpressionException xep) {
        log.error("Error evaluating searchable attribute expression: '" + this.xpathExpression + "'", xep);
    } catch (SAXException se) {
        log.error("Error parsing application content: '" + appContent + "'", se);
    } catch (ParserConfigurationException pce) {
        log.error("Error parsing application content: '" + appContent + "'", pce);
    } catch (IOException ioe) {
        log.error("Error parsing application content: '" + appContent + "'", ioe);
    }
    return attribs;
}
 
Example #23
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) {
   if (!encapsulate) {
      return ConnectorXmlUtils.toByteArray((Node)sig.getElement());
   } else {
      Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement()));
      Node insertBeforeNode = null;
      if (StringUtils.isNotBlank(xpathLocation)) {
         try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() == 1) {
               LOG.debug("1 node found, inserting at location [" + xpathLocation + "]");
               insertBeforeNode = nodes.item(0);
            } else {
               LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default.");
            }
         } catch (XPathExpressionException var9) {
            LOG.info("Unable to determine XPath Location, using default.", var9);
         }
      } else {
         LOG.debug("Using default location (last child tag)");
      }

      doc.getFirstChild().insertBefore(toInsert, insertBeforeNode);
      return ConnectorXmlUtils.toByteArray((Node)doc);
   }
}
 
Example #24
Source File: DomDatabaseWrapper.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
private void init() {
    document = domDatabase.getDoc();
    try {
        dbRootGroup = ((Element) DomHelper.xpath.evaluate("/KeePassFile/Root/Group", document, XPathConstants.NODE));
        dbMeta = ((Element) DomHelper.xpath.evaluate("/KeePassFile/Meta", document, XPathConstants.NODE));
    } catch (XPathExpressionException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #25
Source File: MockDriverHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec,
        DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) {

    // Had to split into declaration and initialization to make stylecheck happy
    // else line was considered too long
    // and auto format couldn't be tweak to make it correct
    Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours;
    behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>();

    try {
        String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec), StandardCharsets.UTF_8);
        InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resp);

        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i += 1) {
            Node node = list.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("api").getNodeValue());
            Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("impl").getNodeValue());
            behaviours.put(api, impl);
        }
        init(behaviours, mockDeviceId, mockCoreService, mockDeviceService);
    } catch (Exception e) {
        fail(e.toString());
    }
}
 
Example #26
Source File: ConfigTransformerTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void testProperties(Element element, Map<String, Object> expected) throws XPathExpressionException {
    NodeList propertyElements = (NodeList) xPathFactory.newXPath().evaluate("property", element, XPathConstants.NODESET);
    Map<String, String> properties = new HashMap<>();
    for (int i = 0; i < propertyElements.getLength(); i++) {
        Element item = (Element) propertyElements.item(i);
        properties.put(getText(item, "name"), getText(item, "value"));
    }
    assertEquals(expected.entrySet().stream().collect(Collectors.toMap(Map.Entry<String, Object>::getKey, e -> nullToEmpty(e.getValue()))), properties);
}
 
Example #27
Source File: AndroidManifestParser.java    From buck with Apache License 2.0 5 votes vote down vote up
public Optional<String> parseMinSdkVersion(Path androidManifestPath) {
  Optional<Document> manifestDocument =
      readAndroidManifestDocument(projectFilesystem.getPathForRelativePath(androidManifestPath));
  if (!manifestDocument.isPresent()) {
    return Optional.empty();
  }
  String minSdkVersion = null;
  try {
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList usesSdkNodes =
        (NodeList) xPath.evaluate("//uses-sdk", manifestDocument.get(), XPathConstants.NODESET);
    if (usesSdkNodes.getLength() > 0) {
      Node usesSdkNode = usesSdkNodes.item(0);
      NamedNodeMap attrs = usesSdkNode.getAttributes();
      if (attrs.getLength() > 0) {
        Node minSdkVersionAttribute =
            usesSdkNode.getAttributes().getNamedItem("android:minSdkVersion");
        if (minSdkVersionAttribute != null) {
          minSdkVersion = minSdkVersionAttribute.getNodeValue();
        }
      }
    }
  } catch (XPathExpressionException e) {
    LOG.debug(
        e, "Cannot find android:minSdkVersion attribute in the manifest %s", androidManifestPath);
  }

  return Optional.ofNullable(minSdkVersion);
}
 
Example #28
Source File: WebserviceSAMLSPTestSetup.java    From development with Apache License 2.0 5 votes vote down vote up
private void updateElementValue(XPath path, Document doc, String pathValue,
        String attribute, String value) throws XPathExpressionException {
    Element node = (Element) path.evaluate(pathValue, doc,
            XPathConstants.NODE);
    if (node != null) {
        node.setAttribute(attribute, value);
    }
}
 
Example #29
Source File: TestCase.java    From jlibs with Apache License 2.0 5 votes vote down vote up
public Object jdkResults(int i){
    if(!translated.contains(i) && xpaths.get(i).resultType.equals(XPathConstants.NODESET)){
        translateDOMResult(i);
        translated.add(i);
    }
    return jdkResult.get(i);
}
 
Example #30
Source File: SituationPluginUtils.java    From container with Apache License 2.0 5 votes vote down vote up
public static Collection<AbstractNodeTemplate> fetchUsedNodeTemplates(BPELPlanContext context) {
    // in some cases plugins use operations of other node templates (e.g. docker containers and docker
    // engines or VM's and cloud providers)
    // therefore we have to find those node templates here
    Collection<AbstractNodeTemplate> nodes = new ArrayList<AbstractNodeTemplate>();

    Element provPhaseElement = context.getProvisioningPhaseElement();
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        NodeList nodeTemplateIDNodes =
            (NodeList) xpath.evaluate("//*[local-name()='invokeOperationAsync']/*[local-name()='NodeTemplateID']",
                provPhaseElement, XPathConstants.NODESET);

        for (int i = 0; i < nodeTemplateIDNodes.getLength(); i++) {
            String nodeTemplateId = nodeTemplateIDNodes.item(i).getTextContent();
            for (AbstractNodeTemplate node : context.getNodeTemplates()) {
                if (node.getId().equals(nodeTemplateId)) {
                    nodes.add(node);
                }
            }
        }
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return nodes;
}