List of usage examples for javax.xml.xpath XPathConstants NODE
QName NODE
To view the source code for javax.xml.xpath XPathConstants NODE.
Click Source Link
The XPath 1.0 NodeSet data type.
From source file:org.odk.collect.android.logic.FormRelationsManager.java
/** * Modifies the parent form if a paired node with child form is changed. * * When this method is called, both child and parent instance are saved to * disk. After opening each file, this method gets all node pairs, or * mappings, and loops through them. For each mapping, the instance value * is obtained in both files. If there is a difference, then the parent * is modified in memory. If there is any change in the parent, then the * file is rewritten to disk. If there is an exception while evaulating * xpaths or doing anything else, updating the parent form is aborted. * * If the parent form is changed, then its status is changed to * incomplete./*from w w w.ja v a 2 s. c om*/ * * @param childId Instance id * @return Returns -1 if no parent, 0 if has parent, but no updates, 1 if * has parent and updates made. */ private static int manageParentForm(long childId) { Long parentId = FormRelationsDb.getParent(childId); if (LOCAL_LOG) { Log.d(TAG, "Inside manageParentForm. Parent instance id is \'" + parentId + "\'"); } if (parentId < 0) { // No parent form to manage return -1; } int returnCode = 0; try { String parentInstancePath = getInstancePath(getInstanceUriFromId(parentId)); String childInstancePath = getInstancePath(getInstanceUriFromId(childId)); Document parentDocument = getDocument(parentInstancePath); Document childDocument = getDocument(childInstancePath); XPath xpath = XPathFactory.newInstance().newXPath(); ArrayList<MappingData> mappings = FormRelationsDb.getMappingsToParent(childId); boolean editedParentForm = false; mUseLog = new UseLog(parentInstancePath, true); for (MappingData mapping : mappings) { XPathExpression parentExpression = xpath.compile(mapping.parentNode); XPathExpression childExpression = xpath.compile(mapping.childNode); Node parentNode = (Node) parentExpression.evaluate(parentDocument, XPathConstants.NODE); Node childNode = (Node) childExpression.evaluate(childDocument, XPathConstants.NODE); if (null == parentNode || null == childNode) { throw new FormRelationsException(BAD_XPATH_INSTANCE, "Child: " + mapping.childNode + ", Parent: " + mapping.parentNode); } if (!childNode.getTextContent().equals(parentNode.getTextContent())) { mUseLog.log(UseLogContract.RELATION_CHANGE_VALUE, parentId, mapping.parentNode, childNode.getTextContent()); Log.i(TAG, "Found difference updating parent form @ parent node \'" + parentNode.getNodeName() + "\'. Child: \'" + childNode.getTextContent() + "\' <> Parent: \'" + parentNode.getTextContent() + "\'"); parentNode.setTextContent(childNode.getTextContent()); editedParentForm = true; } } if (editedParentForm) { writeDocumentToFile(parentDocument, parentInstancePath); mUseLog.writeBackLogAndClose(); ContentValues cv = new ContentValues(); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE); Collect.getInstance().getContentResolver().update(getInstanceUriFromId(parentId), cv, null, null); returnCode = 1; } } catch (FormRelationsException e) { if (e.getErrorCode() == PROVIDER_NO_INSTANCE) { Log.w(TAG, "Unable to find the instance path for either this form (id=" + childId + ") or its parent (id=" + parentId + ")"); } else if (e.getErrorCode() == BAD_XPATH_INSTANCE) { Log.w(TAG, "Bad XPath from one of child or parent. " + e.getInfo()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return returnCode; }
From source file:org.odk.collect.android.logic.FormRelationsManager.java
/** * Inserts data into child form from one morsel of traversal data. * * @param td A `saveInstance` morsel of traversal data. * @param document The child form represented as a document. * @return Returns true if and only if the child instance is modified. * @throws XPathExpressionException Another possible error that should * abort this routine.//from www .j av a 2s . c o m * @throws FormRelationsException Thrown if the xpath data for the child * form is bad. */ private static boolean insertIntoChild(TraverseData td, Document document) throws XPathExpressionException, FormRelationsException { boolean isModified = false; String childInstanceValue = td.instanceValue; if (null != childInstanceValue) { // extract nodes using xpath XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression; String childInstanceXpath = td.attrValue; expression = xpath.compile(childInstanceXpath); Node node = (Node) expression.evaluate(document, XPathConstants.NODE); if (null == node) { throw new FormRelationsException(BAD_XPATH_INSTANCE, childInstanceXpath); } if (!node.getTextContent().equals(childInstanceValue)) { Log.v(TAG, "Found difference saving child form @ child node \'" + node.getNodeName() + "\'. Child: \'" + node.getTextContent() + "\' <> Parent: \'" + childInstanceValue + "\'"); node.setTextContent(childInstanceValue); isModified = true; } } return isModified; }
From source file:org.odk.collect.android.logic.FormRelationsManager.java
/** * Removes a node identified by xpath from a document (instance). * * @param xpathStr The xpath for the node to remove. * @param document The document to mutate. * @return Returns true if and only if a node is removed. * @throws XPathExpressionException Another possible error that should * abort this routine./*www . j av a2 s . c o m*/ * @throws FormRelationsException Thrown if the xpath data for the * supplied document is bad. */ private static boolean removeFromDocument(String xpathStr, Document document) throws XPathExpressionException, FormRelationsException { boolean isModified = false; if (null != xpathStr) { // extract nodes using xpath XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression; expression = xpath.compile(xpathStr); Node node = (Node) expression.evaluate(document, XPathConstants.NODE); if (null == node) { throw new FormRelationsException(BAD_XPATH_INSTANCE, xpathStr); } if (LOCAL_LOG) { Log.i(TAG, "removeFromDocument -- attempting to delete: " + xpathStr); } Node removeNode = node.getParentNode(); removeNode.removeChild(node); isModified = true; } return isModified; }
From source file:org.ojbc.util.xml.XmlUtils.java
/** * Search the context node for a node that matches the specified xpath * /*from ww w. ja v a 2s .com*/ * @param context * the node that's the context for the xpath * @param xPath * the xpath query * @return the matching node, or null if no match * @throws Exception */ public static final Node xPathNodeSearch(Node context, String xPath) throws Exception { if (xPath == null) { return null; } XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(OJBC_NAMESPACE_CONTEXT); XPathExpression expression = xpath.compile(xPath); return (Node) expression.evaluate(context, XPathConstants.NODE); }
From source file:org.omegat.filters.TestFilterBase.java
/** * Remove version and toolname, then compare. */// ww w . ja v a2 s . co m protected void compareTMX(File f1, File f2) throws Exception { XPathExpression exprVersion = XPathFactory.newInstance().newXPath() .compile("/tmx/header/@creationtoolversion"); XPathExpression exprTool = XPathFactory.newInstance().newXPath().compile("/tmx/header/@creationtool"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(TMXReader2.TMX_DTD_RESOLVER); Document doc1 = builder.parse(f1); Document doc2 = builder.parse(f2); Node n; n = (Node) exprVersion.evaluate(doc1, XPathConstants.NODE); n.setNodeValue(""); n = (Node) exprVersion.evaluate(doc2, XPathConstants.NODE); n.setNodeValue(""); n = (Node) exprTool.evaluate(doc1, XPathConstants.NODE); n.setNodeValue(""); n = (Node) exprTool.evaluate(doc2, XPathConstants.NODE); n.setNodeValue(""); assertXMLEqual(doc1, doc2); }
From source file:org.onosproject.drivers.ciena.waveserverai.netconf.CienaWaveserverAiDeviceDescriptionTest.java
private static Node doRequest(String templateName, String baseXPath) { return mockDoRequest(templateName, baseXPath, XPathConstants.NODE); }
From source file:org.opencastproject.comments.CommentParser.java
private static Comment commentFromManifest(Node commentNode, UserDirectoryService userDirectoryService) throws UnsupportedElementException { try {/* ww w.j av a2 s.c o m*/ // id Long id = null; Double idAsDouble = ((Number) xpath.evaluate("@id", commentNode, XPathConstants.NUMBER)).doubleValue(); if (!idAsDouble.isNaN()) id = idAsDouble.longValue(); // text String text = (String) xpath.evaluate("text/text()", commentNode, XPathConstants.STRING); // Author Node authorNode = (Node) xpath.evaluate("author", commentNode, XPathConstants.NODE); User author = userFromManifest(authorNode, userDirectoryService); // ResolvedStatus Boolean resolved = BooleanUtils .toBoolean((Boolean) xpath.evaluate("@resolved", commentNode, XPathConstants.BOOLEAN)); // Reason String reason = (String) xpath.evaluate("reason/text()", commentNode, XPathConstants.STRING); if (StringUtils.isNotBlank(reason)) reason = reason.trim(); // CreationDate String creationDateString = (String) xpath.evaluate("creationDate/text()", commentNode, XPathConstants.STRING); Date creationDate = new Date(DateTimeSupport.fromUTC(creationDateString)); // ModificationDate String modificationDateString = (String) xpath.evaluate("modificationDate/text()", commentNode, XPathConstants.STRING); Date modificationDate = new Date(DateTimeSupport.fromUTC(modificationDateString)); // Create comment Comment comment = Comment.create(Option.option(id), text.trim(), author, reason, resolved, creationDate, modificationDate); // Replies NodeList replyNodes = (NodeList) xpath.evaluate("replies/reply", commentNode, XPathConstants.NODESET); for (int i = 0; i < replyNodes.getLength(); i++) { comment.addReply(replyFromManifest(replyNodes.item(i), userDirectoryService)); } return comment; } catch (XPathExpressionException e) { throw new UnsupportedElementException("Error while reading comment information from manifest", e); } catch (Exception e) { if (e instanceof UnsupportedElementException) throw (UnsupportedElementException) e; throw new UnsupportedElementException( "Error while reading comment creation or modification date information from manifest", e); } }
From source file:org.opencastproject.comments.CommentParser.java
private static CommentReply replyFromManifest(Node commentReplyNode, UserDirectoryService userDirectoryService) throws UnsupportedElementException { try {//from www .ja v a2 s. c o m // id Long id = null; Double idAsDouble = ((Number) xpath.evaluate("@id", commentReplyNode, XPathConstants.NUMBER)) .doubleValue(); if (!idAsDouble.isNaN()) id = idAsDouble.longValue(); // text String text = (String) xpath.evaluate("text/text()", commentReplyNode, XPathConstants.STRING); // Author Node authorNode = (Node) xpath.evaluate("author", commentReplyNode, XPathConstants.NODE); User author = userFromManifest(authorNode, userDirectoryService); // CreationDate String creationDateString = (String) xpath.evaluate("creationDate/text()", commentReplyNode, XPathConstants.STRING); Date creationDate = new Date(DateTimeSupport.fromUTC(creationDateString)); // ModificationDate String modificationDateString = (String) xpath.evaluate("modificationDate/text()", commentReplyNode, XPathConstants.STRING); Date modificationDate = new Date(DateTimeSupport.fromUTC(modificationDateString)); // Create reply return CommentReply.create(Option.option(id), text.trim(), author, creationDate, modificationDate); } catch (XPathExpressionException e) { throw new UnsupportedElementException("Error while reading comment reply information from manifest", e); } catch (Exception e) { if (e instanceof UnsupportedElementException) throw (UnsupportedElementException) e; throw new UnsupportedElementException( "Error while reading comment reply creation or modification date information from manifest", e); } }
From source file:org.opencastproject.mediapackage.elementbuilder.TrackBuilderPlugin.java
/** * @see org.opencastproject.mediapackage.elementbuilder.MediaPackageElementBuilderPlugin#elementFromManifest(org.w3c.dom.Node, * org.opencastproject.mediapackage.MediaPackageSerializer) *///w w w . j av a2s . c o m public MediaPackageElement elementFromManifest(Node elementNode, MediaPackageSerializer serializer) throws UnsupportedElementException { String id = null; MimeType mimeType = null; MediaPackageElementFlavor flavor = null; String reference = null; URI url = null; long size = -1; Checksum checksum = null; try { // id id = (String) xpath.evaluate("@id", elementNode, XPathConstants.STRING); // url url = serializer.resolvePath(xpath.evaluate("url/text()", elementNode).trim()); // reference reference = (String) xpath.evaluate("@ref", elementNode, XPathConstants.STRING); // size String trackSize = xpath.evaluate("size/text()", elementNode).trim(); if (!"".equals(trackSize)) size = Long.parseLong(trackSize); // flavor String flavorValue = (String) xpath.evaluate("@type", elementNode, XPathConstants.STRING); if (StringUtils.isNotEmpty(flavorValue)) flavor = MediaPackageElementFlavor.parseFlavor(flavorValue); // checksum String checksumValue = (String) xpath.evaluate("checksum/text()", elementNode, XPathConstants.STRING); String checksumType = (String) xpath.evaluate("checksum/@type", elementNode, XPathConstants.STRING); if (StringUtils.isNotEmpty(checksumValue) && checksumType != null) checksum = Checksum.create(checksumType.trim(), checksumValue.trim()); // mimetype String mimeTypeValue = (String) xpath.evaluate("mimetype/text()", elementNode, XPathConstants.STRING); if (StringUtils.isNotEmpty(mimeTypeValue)) mimeType = MimeTypes.parseMimeType(mimeTypeValue); // // Build the track TrackImpl track = TrackImpl.fromURI(url); if (StringUtils.isNotBlank(id)) track.setIdentifier(id); // Add url track.setURI(url); // Add reference if (StringUtils.isNotEmpty(reference)) track.referTo(MediaPackageReferenceImpl.fromString(reference)); // Set size if (size > 0) track.setSize(size); // Set checksum if (checksum != null) track.setChecksum(checksum); // Set mimetpye if (mimeType != null) track.setMimeType(mimeType); if (flavor != null) track.setFlavor(flavor); // description String description = (String) xpath.evaluate("description/text()", elementNode, XPathConstants.STRING); if (StringUtils.isNotBlank(description)) track.setElementDescription(description.trim()); // tags NodeList tagNodes = (NodeList) xpath.evaluate("tags/tag", elementNode, XPathConstants.NODESET); for (int i = 0; i < tagNodes.getLength(); i++) { track.addTag(tagNodes.item(i).getTextContent()); } // duration try { String strDuration = (String) xpath.evaluate("duration/text()", elementNode, XPathConstants.STRING); if (StringUtils.isNotEmpty(strDuration)) { long duration = Long.parseLong(strDuration.trim()); track.setDuration(duration); } } catch (NumberFormatException e) { throw new UnsupportedElementException("Duration of track " + url + " is malformatted"); } // audio settings Node audioSettingsNode = (Node) xpath.evaluate("audio", elementNode, XPathConstants.NODE); if (audioSettingsNode != null && audioSettingsNode.hasChildNodes()) { try { AudioStreamImpl as = AudioStreamImpl.fromManifest(createStreamID(track), audioSettingsNode, xpath); track.addStream(as); } catch (IllegalStateException e) { throw new UnsupportedElementException( "Illegal state encountered while reading audio settings from " + url + ": " + e.getMessage()); } catch (XPathException e) { throw new UnsupportedElementException( "Error while parsing audio settings from " + url + ": " + e.getMessage()); } } // video settings Node videoSettingsNode = (Node) xpath.evaluate("video", elementNode, XPathConstants.NODE); if (videoSettingsNode != null && videoSettingsNode.hasChildNodes()) { try { VideoStreamImpl vs = VideoStreamImpl.fromManifest(createStreamID(track), videoSettingsNode, xpath); track.addStream(vs); } catch (IllegalStateException e) { throw new UnsupportedElementException( "Illegal state encountered while reading video settings from " + url + ": " + e.getMessage()); } catch (XPathException e) { throw new UnsupportedElementException( "Error while parsing video settings from " + url + ": " + e.getMessage()); } } return track; } catch (XPathExpressionException e) { throw new UnsupportedElementException( "Error while reading track information from manifest: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new UnsupportedElementException("Unsupported digest algorithm: " + e.getMessage()); } catch (URISyntaxException e) { throw new UnsupportedElementException( "Error while reading presenter track " + url + ": " + e.getMessage()); } }
From source file:org.openehealth.ipf.commons.ihe.ws.cxf.audit.AbstractAuditInterceptor.java
/** * Extracts ITI-40 XUA user name from the SAML2 assertion contained * in the given CXF message, and stores it in the ATNA audit dataset. * * @param message//from w ww. j a va 2 s.c om * source CXF message. * @param auditDataset * target ATNA audit dataset. * @throws XPathExpressionException * actually cannot occur. */ protected static void extractXuaUserNameFromSaml2Assertion(SoapMessage message, WsAuditDataset auditDataset) throws XPathExpressionException { // check whether someone has already parsed the SAML2 assertion // and provided the XUA user name for us via WS message context if (message.getContextualProperty(XUA_USERNAME_CONTEXT_KEY) != null) { auditDataset.setUserName(message.getContextualProperty(XUA_USERNAME_CONTEXT_KEY).toString()); return; } // extract information from SAML2 assertion XPathExpression[] expressions = XUA_XPATH_EXPRESSIONS.get(); Node envelopeNode = message.getContent(Node.class); Node nameNode = (Node) expressions[0].evaluate(envelopeNode, XPathConstants.NODE); if (nameNode == null) { return; } String issuer = (String) expressions[1].evaluate(envelopeNode, XPathConstants.STRING); String userName = nameNode.getTextContent(); if (issuer.isEmpty() || userName.isEmpty()) { return; } // set ATNA XUA userName element StringBuilder sb = new StringBuilder().append(((Element) nameNode).getAttribute("SPProvidedID")).append('<') .append(userName).append('@').append(issuer).append('>'); auditDataset.setUserName(sb.toString()); }