List of usage examples for javax.xml.xpath XPathConstants BOOLEAN
QName BOOLEAN
To view the source code for javax.xml.xpath XPathConstants BOOLEAN.
Click Source Link
The XPath 1.0 boolean data type.
Maps to Java Boolean .
From source file:net.javacrumbs.springws.test.util.DefaultXmlUtil.java
@SuppressWarnings("unchecked") public boolean isSoap(Document document) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(SOAP_NAMESPACE_CONTEXT); try {/*from w w w . j av a 2 s .c om*/ for (Iterator iterator = SOAP_NAMESPACE_CONTEXT.getBoundPrefixes(); iterator.hasNext();) { String prefix = (String) iterator.next(); if ((Boolean) xpath.evaluate("/" + prefix + ":Envelope", document, XPathConstants.BOOLEAN)) { return true; } } } catch (XPathExpressionException e) { logger.warn(e); } return false; }
From source file:org.codice.ddf.admin.sources.csw.CswSourceUtils.java
public Optional<CswSourceConfiguration> getPreferredConfig(CswSourceConfiguration config) { CswSourceConfiguration preferred = new CswSourceConfiguration(config); HttpGet getCapabilitiesRequest = new HttpGet(preferred.endpointUrl() + GET_CAPABILITIES_PARAMS); CloseableHttpClient client = null;//from w ww. j av a2 s . co m CloseableHttpResponse response = null; if (config.endpointUrl().startsWith("https") && config.sourceUserName() != null && config.sourceUserPassword() != null) { byte[] auth = Base64 .encodeBase64((config.sourceUserName() + ":" + config.sourceUserPassword()).getBytes()); getCapabilitiesRequest.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth)); } XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT); try { client = getCloseableHttpClient(true); response = client.execute(getCapabilitiesRequest); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document capabilitiesXml = builder.parse(response.getEntity().getContent()); if ((Boolean) xpath.compile(HAS_CATALOG_METACARD_EXP).evaluate(capabilitiesXml, XPathConstants.BOOLEAN)) { return Optional.of((CswSourceConfiguration) preferred.factoryPid(CSW_PROFILE_FACTORY_PID)); } else if ((Boolean) xpath.compile(HAS_GMD_ISO_EXP).evaluate(capabilitiesXml, XPathConstants.BOOLEAN)) { return Optional.of(((CswSourceConfiguration) preferred.factoryPid(CSW_GMD_FACTORY_PID)) .outputSchema(GMD_OUTPUT_SCHEMA)); } else { return Optional.of(((CswSourceConfiguration) (preferred.factoryPid(CSW_SPEC_FACTORY_PID))) .outputSchema(xpath.compile(GET_FIRST_OUTPUT_SCHEMA).evaluate(capabilitiesXml))); } } catch (Exception e) { return Optional.empty(); } finally { closeClientAndResponse(client, response); } }
From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java
Article addArticle(Document articleDom, DigitalObjectElement article, CejshContext p) { if (articleDom == null) { p.getStatus().error(article, "Missing article MODS!", null, null); return null; }//ww w.j a v a 2s.c o m try { Object isReviewed = getReviewedArticlePath().evaluate(articleDom, XPathConstants.BOOLEAN); if (!(isReviewed instanceof Boolean) || !((Boolean) isReviewed)) { LOG.log(logLevel, "Skipped not reviewed article: {0}", article.getPid()); return new Article().setReviewed(false); } } catch (XPathExpressionException ex) { p.getStatus().error(article, "Unexpected error!", null, ex); } if (getTitle() == null) { p.getStatus().error(article, "Missing title!", null, null); return null; } if (getVolume() == null) { p.getStatus().error(article, "Missing volume!", null, null); return null; } try { String articleIssn = getIssnPath().evaluate(articleDom); // XXX check mods vs modsCollection? Element modsElement = articleDom.getDocumentElement(); return new Article(article, modsElement, articleIssn).setReviewed(true); } catch (Exception ex) { p.getStatus().error(article, "Unexpected error!", null, ex); } return null; }
From source file:hudson.plugins.plot.XMLSeries.java
/** * Convert a given object into a String. * /*from w w w . jav a2 s .c om*/ * @param obj * Xpath Object * @return String representation of the node */ private String nodeToString(Object obj) { String ret = null; if (nodeType == XPathConstants.BOOLEAN) { return (((Boolean) obj)) ? "1" : "0"; } if (nodeType == XPathConstants.NUMBER) return ((Double) obj).toString().trim(); if (nodeType == XPathConstants.NODE || nodeType == XPathConstants.NODESET) { if (obj instanceof String) { ret = ((String) obj).trim(); } else { if (null == obj) { return null; } Node node = (Node) obj; NamedNodeMap nodeMap = node.getAttributes(); if ((null != nodeMap) && (null != nodeMap.getNamedItem("time"))) { ret = nodeMap.getNamedItem("time").getTextContent(); } if (null == ret) { ret = node.getTextContent().trim(); } } } if (nodeType == XPathConstants.STRING) ret = ((String) obj).trim(); // for Node/String/NodeSet, try and parse it as a double. // we don't store a double, so just throw away the result. Scanner scanner = new Scanner(ret); if (scanner.hasNextDouble()) { return String.valueOf(scanner.nextDouble()); } return null; }
From source file:com.espertech.esper.client.ConfigurationParser.java
private static void handleXMLDOM(String name, Configuration configuration, Element xmldomElement) { String rootElementName = getRequiredAttribute(xmldomElement, "root-element-name"); String rootElementNamespace = getOptionalAttribute(xmldomElement, "root-element-namespace"); String schemaResource = getOptionalAttribute(xmldomElement, "schema-resource"); String schemaText = getOptionalAttribute(xmldomElement, "schema-text"); String defaultNamespace = getOptionalAttribute(xmldomElement, "default-namespace"); String resolvePropertiesAbsoluteStr = getOptionalAttribute(xmldomElement, "xpath-resolve-properties-absolute"); String propertyExprXPathStr = getOptionalAttribute(xmldomElement, "xpath-property-expr"); String eventSenderChecksRootStr = getOptionalAttribute(xmldomElement, "event-sender-validates-root"); String xpathFunctionResolverClass = getOptionalAttribute(xmldomElement, "xpath-function-resolver"); String xpathVariableResolverClass = getOptionalAttribute(xmldomElement, "xpath-variable-resolver"); String autoFragmentStr = getOptionalAttribute(xmldomElement, "auto-fragment"); String startTimestampProperty = getOptionalAttribute(xmldomElement, "start-timestamp-property-name"); String endTimestampProperty = getOptionalAttribute(xmldomElement, "end-timestamp-property-name"); ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM(); xmlDOMEventTypeDesc.setRootElementName(rootElementName); xmlDOMEventTypeDesc.setSchemaResource(schemaResource); xmlDOMEventTypeDesc.setSchemaText(schemaText); xmlDOMEventTypeDesc.setRootElementNamespace(rootElementNamespace); xmlDOMEventTypeDesc.setDefaultNamespace(defaultNamespace); xmlDOMEventTypeDesc.setXPathFunctionResolver(xpathFunctionResolverClass); xmlDOMEventTypeDesc.setXPathVariableResolver(xpathVariableResolverClass); xmlDOMEventTypeDesc.setStartTimestampPropertyName(startTimestampProperty); xmlDOMEventTypeDesc.setEndTimestampPropertyName(endTimestampProperty); if (resolvePropertiesAbsoluteStr != null) { xmlDOMEventTypeDesc// ww w .j a v a 2 s .c o m .setXPathResolvePropertiesAbsolute(Boolean.parseBoolean(resolvePropertiesAbsoluteStr)); } if (propertyExprXPathStr != null) { xmlDOMEventTypeDesc.setXPathPropertyExpr(Boolean.parseBoolean(propertyExprXPathStr)); } if (eventSenderChecksRootStr != null) { xmlDOMEventTypeDesc.setEventSenderValidatesRoot(Boolean.parseBoolean(eventSenderChecksRootStr)); } if (autoFragmentStr != null) { xmlDOMEventTypeDesc.setAutoFragment(Boolean.parseBoolean(autoFragmentStr)); } configuration.addEventType(name, xmlDOMEventTypeDesc); DOMElementIterator propertyNodeIterator = new DOMElementIterator(xmldomElement.getChildNodes()); while (propertyNodeIterator.hasNext()) { Element propertyElement = propertyNodeIterator.next(); if (propertyElement.getNodeName().equals("namespace-prefix")) { String prefix = getRequiredAttribute(propertyElement, "prefix"); String namespace = getRequiredAttribute(propertyElement, "namespace"); xmlDOMEventTypeDesc.addNamespacePrefix(prefix, namespace); } if (propertyElement.getNodeName().equals("xpath-property")) { String propertyName = getRequiredAttribute(propertyElement, "property-name"); String xPath = getRequiredAttribute(propertyElement, "xpath"); String propertyType = getRequiredAttribute(propertyElement, "type"); QName xpathConstantType; if (propertyType.toUpperCase().equals("NUMBER")) { xpathConstantType = XPathConstants.NUMBER; } else if (propertyType.toUpperCase().equals("STRING")) { xpathConstantType = XPathConstants.STRING; } else if (propertyType.toUpperCase().equals("BOOLEAN")) { xpathConstantType = XPathConstants.BOOLEAN; } else if (propertyType.toUpperCase().equals("NODE")) { xpathConstantType = XPathConstants.NODE; } else if (propertyType.toUpperCase().equals("NODESET")) { xpathConstantType = XPathConstants.NODESET; } else { throw new IllegalArgumentException("Invalid xpath property type for property '" + propertyName + "' and type '" + propertyType + '\''); } String castToClass = null; if (propertyElement.getAttributes().getNamedItem("cast") != null) { castToClass = propertyElement.getAttributes().getNamedItem("cast").getTextContent(); } String optionaleventTypeName = null; if (propertyElement.getAttributes().getNamedItem("event-type-name") != null) { optionaleventTypeName = propertyElement.getAttributes().getNamedItem("event-type-name") .getTextContent(); } if (optionaleventTypeName != null) { xmlDOMEventTypeDesc.addXPathPropertyFragment(propertyName, xPath, xpathConstantType, optionaleventTypeName); } else { xmlDOMEventTypeDesc.addXPathProperty(propertyName, xPath, xpathConstantType, castToClass); } } } }
From source file:org.apache.servicemix.wsn.jms.JmsSubscription.java
protected boolean doFilter(Element content) { if (contentFilter != null) { if (!contentFilter.getDialect().equals(XPATH1_URI)) { throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect()); }/*from w w w . j a va 2s . c o m*/ try { XPathFactory xpfactory = XPathFactory.newInstance(); XPath xpath = xpfactory.newXPath(); XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString()); Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN); return ret.booleanValue(); } catch (XPathExpressionException e) { log.warn("Could not filter notification", e); } return false; } return true; }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private void handleFileElement(String pid, int itemIndex, Element fileElement) throws URISyntaxException, IOException, FedoraClientException, XPathExpressionException { Node tempFile = fileElement.getElementsByTagName("TempFile").item(0); Node pathName = fileElement.getElementsByTagName("PathName").item(0); if (tempFile == null || pathName == null) { return;//from w w w . j a v a 2 s .c om } String id = pid.substring("qucosa:".length()); String tmpFileName = tempFile.getTextContent(); String targetFilename = pathName.getTextContent(); URI fileUri = fileHandlingService.copyTempfileToTargetFileSpace(tmpFileName, targetFilename, id); Node labelNode = fileElement.getElementsByTagName("Label").item(0); String label = (labelNode != null) ? labelNode.getTextContent() : ""; final Path filePath = new File(fileUri).toPath(); String detectedContentType = Files.probeContentType(filePath); if (!(Boolean) xPath.evaluate("MimeType[text()!='']", fileElement, XPathConstants.BOOLEAN)) { if (detectedContentType != null) { Element mimeTypeElement = fileElement.getOwnerDocument().createElement("MimeType"); mimeTypeElement.setTextContent(detectedContentType); fileElement.appendChild(mimeTypeElement); } } if (!(Boolean) xPath.evaluate("FileSize[text()!='']", fileElement, XPathConstants.BOOLEAN)) { Element fileSizeElement = fileElement.getOwnerDocument().createElement("FileSize"); fileSizeElement.setTextContent(String.valueOf(Files.size(filePath))); fileElement.appendChild(fileSizeElement); } String dsid = DSID_QUCOSA_ATT + (itemIndex); String state = determineDatastreamState(fileElement); DatastreamProfile dsp = fedoraRepository.createExternalReferenceDatastream(pid, dsid, label, fileUri, detectedContentType, state); fileElement.setAttribute("id", String.valueOf(itemIndex)); addHashValue(fileElement, dsp); fileElement.removeChild(tempFile); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private String determineDatastreamState(Element fileElement) throws XPathExpressionException { if (!(Boolean) xPath.evaluate("FrontdoorVisible[text()='1']", fileElement, XPathConstants.BOOLEAN)) { return "I"; }/*from w w w . j a v a 2 s .c om*/ return "A"; }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private void modifyDcDatastream(String pid, List<String> urns, String title) throws FedoraClientException, ParserConfigurationException, IOException, SAXException, TransformerException, XPathExpressionException { if ((urns == null || urns.isEmpty()) && (title == null || title.isEmpty())) return;/*from w w w. j a v a 2s. c om*/ InputStream dcStream = fedoraRepository.getDatastreamContent(pid, "DC"); Document dcDocument = documentBuilder.parse(dcStream); if (urns != null) { for (String urnnbn : urns) { String urn = urnnbn.trim().toLowerCase(); if (!(boolean) xPath.compile("//ns:identifier[text()='" + urn + "']").evaluate(dcDocument, XPathConstants.BOOLEAN)) { Element newDcIdentifier = dcDocument.createElementNS("http://purl.org/dc/elements/1.1/", "identifier"); newDcIdentifier.setTextContent(urn); dcDocument.getDocumentElement().appendChild(newDcIdentifier); } } } if ((title != null) && (!title.isEmpty())) { Element dcTitle = (Element) dcDocument .getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "title").item(0); dcTitle.setTextContent(title); } InputStream modifiedDcStream = IOUtils.toInputStream(DOMSerializer.toString(dcDocument)); fedoraRepository.modifyDatastreamContent(pid, "DC", "text/xml", modifiedDcStream); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private Tuple<Collection<String>> updateWith(Document targetDocument, final Document updateDocument, List<FileUpdateOperation> fileUpdateOperations) throws XPathExpressionException, IOException, FedoraClientException { Element targetRoot = (Element) targetDocument.getElementsByTagName("Opus_Document").item(0); Element updateRoot = (Element) updateDocument.getElementsByTagName("Opus_Document").item(0); Set<String> distinctUpdateFieldList = new LinkedHashSet<>(); NodeList updateFields = updateRoot.getChildNodes(); for (int i = 0; i < updateFields.getLength(); i++) { distinctUpdateFieldList.add(updateFields.item(i).getNodeName()); }// ww w.j a va 2 s . c o m for (String fn : distinctUpdateFieldList) { // cannot use getElementsByTagName() here because it searches recursively for (Node victim : getChildNodesByName(targetRoot, fn)) { if (!victim.getLocalName().equals("File")) { targetRoot.removeChild(victim); } } } for (int i = 0; i < updateFields.getLength(); i++) { // Update node needs to be cloned, otherwise it will // be removed from updateFields by adoptNode(). Node updateNode = updateFields.item(i).cloneNode(true); if (updateNode.hasChildNodes() && !updateNode.getLocalName().equals("File")) { targetDocument.adoptNode(updateNode); targetRoot.appendChild(updateNode); } } List<String> purgeDatastreamList = new LinkedList<>(); if ((Boolean) xPath.evaluate("//File", updateDocument, XPathConstants.BOOLEAN)) { updateFileElementsInPlace(targetDocument, updateDocument, fileUpdateOperations, targetRoot, updateRoot, purgeDatastreamList); } targetDocument.normalizeDocument(); return new Tuple<>(distinctUpdateFieldList, purgeDatastreamList); }