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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: AndroidManifest.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether the version Code attribute is set in a given manifest.
 * @param manifestFile the manifest to check
 * @return true if the versionCode attribute is present and its value is not empty.
 * @throws XPathExpressionException
 * @throws StreamException If any error happens when reading the manifest.
 */
public static boolean hasVersionCode(IAbstractFile manifestFile)
        throws XPathExpressionException, StreamException {
    XPath xPath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = manifestFile.getContents();
        Object result = xPath.evaluate(
                "/"  + NODE_MANIFEST +
                "/@" + AndroidXPathFactory.DEFAULT_NS_PREFIX +
                ":"  + ATTRIBUTE_VERSIONCODE,
                new InputSource(is),
                XPathConstants.NODE);

        if (result != null) {
            Node node  = (Node)result;
            if (!node.getNodeValue().isEmpty()) {
                return true;
            }
        }
    } finally {
        try {
            Closeables.close(is, true /* swallowIOException */);
        } catch (IOException e) {
            // cannot happen
        }
    }

    return false;
}
 
Example #16
Source File: XmlRegistry.java    From gridgo with MIT License 5 votes vote down vote up
@Override
public Object lookup(String name) {
    try {
        var node = (Node) xPath.compile(name).evaluate(document, XPathConstants.NODE);
        if (node == null)
            return null;
        return node.getTextContent();
    } catch (XPathExpressionException e) {
        throw new RegistryException("Cannot lookup key: " + name, e);
    }
}
 
Example #17
Source File: XCalDocument.java    From biweekly with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Wraps an existing XML DOM object.
 * @param document the XML DOM that contains the xCal document
 */
public XCalDocument(Document document) {
	this.document = document;

	XPath xpath = XPathFactory.newInstance().newXPath();
	xpath.setNamespaceContext(nsContext);

	try {
		//find the <icalendar> element
		String prefix = nsContext.getPrefix();
		icalendarRootElement = (Element) xpath.evaluate("//" + prefix + ":" + ICALENDAR.getLocalPart(), document, XPathConstants.NODE);
	} catch (XPathExpressionException e) {
		//never thrown, xpath expression is hard coded
	}
}
 
Example #18
Source File: CienaWaveserverAiDeviceDescriptionTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscoverPortDetails() {
    List<PortDescription> result = new ArrayList<>();
    List<PortDescription> expectResult = getExpectedPorts();

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

        Node node = doRequest("/response/discoverPortDetails.xml", "/rpc-reply/data");
        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);
            result.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 (XPathExpressionException e) {
        e.printStackTrace();
    }
     assertEquals(expectResult, result);
}
 
Example #19
Source File: XmlFileReader.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public FileReader replacePropertyValuesWith( String propertyName, String replacedValue )
{
    XPath xPath = XPathFactory.newInstance().newXPath();

    try
    {
        NodeList nodes = (NodeList) xPath.evaluate( "//*[@" + propertyName + "]", document, XPathConstants.NODESET );

        for ( int i = 0; i < nodes.getLength(); i++ )
        {
            Node node = nodes.item( i ).getAttributes().getNamedItem( propertyName );

            if ( replacedValue.equalsIgnoreCase( "uniqueid" ) )
            {
                node.setNodeValue( new IdGenerator().generateUniqueId() );
                continue;
            }
            node.setNodeValue( replacedValue );
        }

    }
    catch ( XPathExpressionException e )
    {
        e.printStackTrace();
    }

    return this;
}
 
Example #20
Source File: Ciena5162DeviceDescription.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<PortDescription> discoverPortDetails() {
    List<PortDescription> ports = new ArrayList<PortDescription>();
    DeviceId deviceId = handler().data().deviceId();
    NetconfController controller = checkNotNull(handler().get(NetconfController.class));
    if (controller == null || controller.getDevicesMap() == null
            || controller.getDevicesMap().get(deviceId) == null) {
        log.warn("NETCONF session to device {} not yet established, will be retried", deviceId);
        return ports;
    }
    NetconfSession session = controller.getDevicesMap().get(deviceId).getSession();

    try {
        Node logicalPorts = TEMPLATE_MANAGER.doRequest(session, "logicalPorts");
        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList nl = (NodeList) xp.evaluate("interfaces/interface/config", logicalPorts, XPathConstants.NODESET);
        int count = nl.getLength();
        Node node;
        for (int i = 0; i < count; i += 1) {
            node = nl.item(i);
            if (xp.evaluate("type/text()", node).equals("ettp")) {
                ports.add(DefaultPortDescription.builder()
                        .withPortNumber(PortNumber.portNumber(xp.evaluate("name/text()", node)))
                        .isEnabled(Boolean.valueOf(xp.evaluate("admin-status/text()", node)))
                        .portSpeed(portSpeedToLong(xp.evaluate("port-speed/text()", node))).type(Port.Type.PACKET)
                        .build());
            }
        }
    } catch (NetconfException | XPathExpressionException e) {
        log.error("Unable to retrieve port information for device {}, {}", deviceId, e);
    }
    return ports;
}
 
Example #21
Source File: XPathFinder.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public String getStringByPath(String path, Element localElement, Document doc,
        NsContext nsContext) throws XPathExpressionException {
    // Note the difference between this function and function "getStringsByPath"
    // The path for this function should be like "/clinical_studies/clinical_study/brief_title",
    // which returns ONLY ONE string of the first matched element "brief_title"
    XPath xpath = factory.newXPath();
    Object element = getElementToBeSearched(path, localElement, doc);
    return (String) xpath.evaluate(path, element, XPathConstants.STRING);
}
 
Example #22
Source File: XPathExpressionImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSupported( QName returnType ) {
   // XPathConstants.STRING
   if ( ( returnType.equals( XPathConstants.STRING ) ) ||
        ( returnType.equals( XPathConstants.NUMBER ) ) ||
        ( returnType.equals( XPathConstants.BOOLEAN ) ) ||
        ( returnType.equals( XPathConstants.NODE ) ) ||
        ( returnType.equals( XPathConstants.NODESET ) )  ) {

       return true;
   }
   return false;
}
 
Example #23
Source File: MigrationSiteBuilder.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private String getProfileId(String protocol) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
  factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  factory.setXIncludeAware(false);
  factory.setExpandEntityReferences(false);
  factory.setNamespaceAware(true);
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(protocol)));
  
  XPath xPath = XPathFactory.newInstance().newXPath();
  return (String)xPath.evaluate("/protocol[@type='CSW']/profile", doc, XPathConstants.STRING);
}
 
Example #24
Source File: DomUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the String value of the corresponding to the XPath query.
 *
 * @param xmlNode
 *                    The node where the search should be performed.
 * @param xPathString
 *                    XPath query string
 * @return string value of the XPath query
 */
public static String getValue(final Node xmlNode, final String xPathString) {
	try {
		final XPathExpression xPathExpression = createXPathExpression(xPathString);
		final String string = (String) xPathExpression.evaluate(xmlNode, XPathConstants.STRING);
		return string.trim();
	} catch (XPathExpressionException e) {
		throw new DSSException(e);
	}
}
 
Example #25
Source File: MultiDBBaseTestCase.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private List<DBDataEntry> parseDataFile() throws Exception {
	List<DBDataEntry> datas = new ArrayList<DBDataEntry>();

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document configDoc = builder
			.parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getDataFile()));
	XPathFactory xpathFactory = XPathFactory.newInstance();
	XPath xpath = xpathFactory.newXPath();
	NodeList databaseList = (NodeList) xpath.compile("/dataset/database").evaluate(configDoc,
			XPathConstants.NODESET);
	for (int i = 0; i < databaseList.getLength(); i++) {
		DBDataEntry entry = new DBDataEntry();
		Element ele = (Element) databaseList.item(i);

		entry.setDbName(ele.getAttribute("name"));

		// add for encryption test
		entry.setUsername(ele.getAttribute("username"));
		entry.setPassword(ele.getAttribute("password"));

		NodeList scriptNodeList = ele.getChildNodes();
		List<String> scripts = new ArrayList<String>();
		for (int j = 0; j < scriptNodeList.getLength(); j++) {
			scripts.add(scriptNodeList.item(j).getTextContent());
		}
		entry.setScripts(scripts);
		datas.add(entry);
	}

	return datas;

}
 
Example #26
Source File: AndroidManifest.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the version Code attribute is set in a given manifest.
 * @param manifestFile the manifest to check
 * @return true if the versionCode attribute is present and its value is not empty.
 * @throws XPathExpressionException
 * @throws StreamException If any error happens when reading the manifest.
 */
public static boolean hasVersionCode(IAbstractFile manifestFile)
        throws XPathExpressionException, StreamException {
    XPath xPath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = manifestFile.getContents();
        Object result = xPath.evaluate(
                "/"  + NODE_MANIFEST +
                "/@" + AndroidXPathFactory.DEFAULT_NS_PREFIX +
                ":"  + ATTRIBUTE_VERSIONCODE,
                new InputSource(is),
                XPathConstants.NODE);

        if (result != null) {
            Node node  = (Node)result;
            if (!node.getNodeValue().isEmpty()) {
                return true;
            }
        }
    } finally {
        try {
            Closeables.close(is, true /* swallowIOException */);
        } catch (IOException e) {
            // cannot happen
        }
    }

    return false;
}
 
Example #27
Source File: DomSerializableDatabase.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
@Override
public void setHeaderHash(byte[] hash) {
    // Android compatibility
    String base64String = new String(Base64.encodeBase64(hash));
    try {
        ((Element) DomHelper.xpath.evaluate("//HeaderHash", doc, XPathConstants.NODE)).setTextContent(base64String);
    } catch (XPathExpressionException e) {
        throw new IllegalStateException("Can't set header hash", e);
    }
}
 
Example #28
Source File: OlapModelPropertiesFromFileInitializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
	XPath xpath = XPathFactory.newInstance().newXPath();
	XPathExpression expr = xpath.compile(xpathExpression);

	Object result = expr.evaluate(doc, XPathConstants.NODESET);
	NodeList nodes = (NodeList) result;

	return nodes;
}
 
Example #29
Source File: XPathServerConfigurationParser.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
protected Object evaluateExpression(Node source, String expression)
{
    try
    {
        return xpath.evaluate(expression, source, XPathConstants.STRING);
    }
    catch (XPathExpressionException expressionException)
    {
        throw wrapException(expressionException);
    }
}
 
Example #30
Source File: XPathImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private boolean isSupported( QName returnType ) {
   if ( ( returnType.equals( XPathConstants.STRING ) ) ||
        ( returnType.equals( XPathConstants.NUMBER ) ) ||
        ( returnType.equals( XPathConstants.BOOLEAN ) ) ||
        ( returnType.equals( XPathConstants.NODE ) ) ||
        ( returnType.equals( XPathConstants.NODESET ) )  ) {

       return true;
   }
   return false;
}