List of usage examples for javax.xml.xpath XPathConstants NODESET
QName NODESET
To view the source code for javax.xml.xpath XPathConstants NODESET.
Click Source Link
The XPath 1.0 NodeSet data type.
Maps to Java org.w3c.dom.NodeList .
From source file:com.mirth.connect.plugins.datatypes.xml.XMLBatchAdaptor.java
private String getMessageFromReader() throws Exception { SplitType splitType = batchProperties.getSplitType(); if (splitType == SplitType.Element_Name || splitType == SplitType.Level || splitType == SplitType.XPath_Query) { if (nodeList == null) { StringBuilder query = new StringBuilder(); if (splitType == SplitType.Element_Name) { query.append("//*[local-name()='"); query.append(batchProperties.getElementName()); query.append("']"); } else if (splitType == SplitType.Level) { query.append("/*"); for (int i = 0; i < batchProperties.getLevel(); i++) { query.append("/*"); }/*from www .j a v a 2 s. c o m*/ } else if (splitType == SplitType.XPath_Query) { query.append(batchProperties.getQuery()); } XPath xpath = xPathFactory.newXPath(); nodeList = (NodeList) xpath.evaluate(query.toString(), new InputSource(bufferedReader), XPathConstants.NODESET); } if (currentNode < nodeList.getLength()) { Node node = nodeList.item(currentNode++); if (node != null) { return toXML(node); } } } else if (splitType == SplitType.JavaScript) { if (StringUtils.isEmpty(batchProperties.getBatchScript())) { throw new BatchMessageException("No batch script was set."); } try { final String batchScriptId = ScriptController.getScriptId(ScriptController.BATCH_SCRIPT_KEY, sourceConnector.getChannelId()); MirthContextFactory contextFactory = contextFactoryController .getContextFactory(sourceConnector.getChannel().getResourceIds()); if (!factory.getContextFactoryId().equals(contextFactory.getId())) { synchronized (factory) { contextFactory = contextFactoryController .getContextFactory(sourceConnector.getChannel().getResourceIds()); if (!factory.getContextFactoryId().equals(contextFactory.getId())) { JavaScriptUtil.recompileGeneratedScript(contextFactory, batchScriptId); factory.setContextFactoryId(contextFactory.getId()); } } } String result = JavaScriptUtil .execute(new JavaScriptTask<String>(contextFactory, "XML Batch Adaptor", sourceConnector) { @Override public String doCall() throws Exception { Script compiledScript = CompiledScriptCache.getInstance() .getCompiledScript(batchScriptId); if (compiledScript == null) { logger.error("Batch script could not be found in cache"); return null; } else { Logger scriptLogger = Logger .getLogger(ScriptController.BATCH_SCRIPT_KEY.toLowerCase()); try { Scriptable scope = JavaScriptScopeUtil.getBatchProcessorScope( getContextFactory(), scriptLogger, sourceConnector.getChannelId(), sourceConnector.getChannel().getName(), getScopeObjects(bufferedReader)); return (String) Context.jsToJava(executeScript(compiledScript, scope), String.class); } finally { Context.exit(); } } } }); if (StringUtils.isEmpty(result)) { return null; } else { return result; } } catch (JavaScriptExecutorException e) { logger.error(e.getCause()); } catch (Throwable e) { logger.error(e); } } else { throw new BatchMessageException("No valid batch splitting method configured"); } return null; }
From source file:com.concursive.connect.cms.portal.dao.DashboardTemplateList.java
private void parseLibrary(XMLUtils library) { LOG.debug("objectType=" + objectType); LOG.debug("has xml? " + (library != null)); if (LOG.isTraceEnabled()) { LOG.trace(library.toString());/*w w w . jav a 2s . co m*/ } // Use XPath for querying xml elements XPath xpath = XPathFactory.newInstance().newXPath(); // Build a list of dashboard pages ArrayList<Element> pageElements = new ArrayList<Element>(); XMLUtils.getAllChildren(XMLUtils.getFirstChild(library.getDocumentElement(), objectType), "page", pageElements); Iterator i = pageElements.iterator(); int count = 0; while (i.hasNext()) { ++count; Element el = (Element) i.next(); DashboardTemplate thisTemplate = new DashboardTemplate(); thisTemplate.setId(count); thisTemplate.setName(el.getAttribute("name")); // Check for xml included fragments declaration // <xml-include fragment="portal-fragments-id"/> // NOTE: since the document is being read as a resource, xinclude and xpointer could not be used // mainly due to xpointer not being implemented try { NodeList includeList = (NodeList) xpath.evaluate("row/column/portlet/xml-include", el, XPathConstants.NODESET); // XML Include found, so find all the fragments for (int nodeIndex = 0; nodeIndex < includeList.getLength(); nodeIndex++) { Node xmlInclude = includeList.item(nodeIndex); String fragmentId = ((Element) xmlInclude).getAttribute("fragment"); NodeList fragmentNodeList = (NodeList) xpath.evaluate( "*/fragment[@id=\"" + fragmentId + "\"]/*", library.getDocumentElement(), XPathConstants.NODESET); if (LOG.isDebugEnabled() && fragmentNodeList.getLength() == 0) { LOG.error("Could not find fragment with id: " + fragmentId); } for (int prefIndex = 0; prefIndex < fragmentNodeList.getLength(); prefIndex++) { xmlInclude.getParentNode().appendChild(fragmentNodeList.item(prefIndex).cloneNode(true)); } // Remove the XML Include declaration xmlInclude.getParentNode().removeChild(xmlInclude); } } catch (Exception e) { LOG.error("Replace xml fragments", e); } // Set the completed xml layout thisTemplate.setXmlDesign(XMLUtils.toString(el)); // Check for properties that affect the rendering of the portal page if (el.hasAttribute("permission")) { thisTemplate.setPermission(el.getAttribute("permission")); } if (el.hasAttribute("title")) { thisTemplate.setTitle(el.getAttribute("title")); } if (el.hasAttribute("description")) { thisTemplate.setDescription(el.getAttribute("description")); } if (el.hasAttribute("keywords")) { thisTemplate.setKeywords(el.getAttribute("keywords")); } if (el.hasAttribute("category")) { thisTemplate.setCategory(el.getAttribute("category")); } this.add(thisTemplate); } }
From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); String url = (String) session.getAttribute(HttpCookies.TARGET_URL); String root = (URLS.LOCALHOST() ? "http://" : "https://") + req.getServerName() + (URLS.LOCALHOST() ? (req.getServerPort() == 80 || req.getServerPort() == 443 ? "" : (":" + req.getServerPort())) : "") + URLS.ROOT() + (URLS.LOCALHOST() ? "?gwt.codesvr=127.0.0.1:9997" : ""); String authHeader = req.getHeader("Authorization"); if (authHeader != null) { String decodedHeader = decode(req, authHeader); String pass = configuration.getHttpBasicPass(); if (pass == null || "".equals(pass.trim()) || pass.length() < 4) { requrireAuthentication(resp); }// ww w .j ava2 s . c o m if (decodedHeader.equals(ALLOWED_PREFIX + pass)) { session.setAttribute(HttpCookies.TARGET_URL, null); session.setAttribute(HttpCookies.SESSION_ID_KEY, "https://www.google.com/profiles/109255519115168093543"); session.setAttribute(HttpCookies.NAME_KEY, "admin"); session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES); ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + decodedHeader.substring(0, decodedHeader.indexOf(":")) + " with openID BASIC_AUTH and IP " + req.getRemoteAddr()); URLS.redirect(resp, url == null ? root : url); return; } else { requrireAuthentication(resp); return; } } session.setAttribute(HttpCookies.TARGET_URL, null); String token = req.getParameter("token"); String appID = configuration.getOpenIDApiKey(); String openIdurl = configuration.getOpenIDApiURL(); RPX rpx = new RPX(appID, openIdurl); Element e = null; try { e = rpx.authInfo(token); } catch (ConnectionException connEx) { requrireAuthentication(resp); return; } String idXPath = "//identifier"; String nameXPath = "//displayName"; XPathFactory xpfactory = XPathFactory.newInstance(); XPath xpath = xpfactory.newXPath(); String identifier = null; String name = null; try { XPathExpression expr1 = xpath.compile(idXPath); XPathExpression expr2 = xpath.compile(nameXPath); NodeList nodes1 = (NodeList) expr1.evaluate(e.getOwnerDocument(), XPathConstants.NODESET); NodeList nodes2 = (NodeList) expr2.evaluate(e.getOwnerDocument(), XPathConstants.NODESET); Element el = null; if (nodes1.getLength() != 0) { el = (Element) nodes1.item(0); } if (el != null) { identifier = el.getTextContent(); } if (nodes2.getLength() != 0) { el = (Element) nodes2.item(0); } if (el != null) { name = el.getTextContent(); } } catch (XPathExpressionException e1) { e1.printStackTrace(); } if (identifier != null && !"".equals(identifier)) { ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + name + " with openID " + identifier + " and IP " + req.getRemoteAddr()); int userStatus = UserDAO.UNKNOWN; try { userStatus = userDAO.isSupported(identifier); } catch (DatabaseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } switch (userStatus) { case UserDAO.UNKNOWN: // TODO handle DB error (inform user) break; case UserDAO.USER: // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY, // identifier); session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); URLS.redirect(resp, url == null ? root : url); break; case UserDAO.ADMIN: // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY, // identifier); // HttpCookies.setCookie(req, resp, HttpCookies.ADMIN, // HttpCookies.ADMIN_YES); session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES); URLS.redirect(resp, url == null ? root : url); break; case UserDAO.NOT_PRESENT: default: session.setAttribute(HttpCookies.UNKNOWN_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); URLS.redirect(resp, root + URLS.INFO_PAGE); break; } } else { URLS.redirect(resp, root + (URLS.LOCALHOST() ? URLS.LOGIN_LOCAL_PAGE : URLS.LOGIN_PAGE)); } // System.out.println("ID:" + identifier); // if user is supported redirect to homepage else show him a page that he // has to be added to system first by admin }
From source file:eu.interedition.collatex.tools.CollationPipe.java
public static void start(CommandLine commandLine) throws Exception { List<SimpleWitness> witnesses = null; Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT; Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS; Comparator<Token> comparator = new EqualityTokenComparator(); CollationAlgorithm collationAlgorithm = null; boolean joined = true; final String[] witnessSpecs = commandLine.getArgs(); final InputStream[] inputStreams = new InputStream[witnessSpecs.length]; for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) { try {/*w w w.ja va 2 s . c o m*/ inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]); } catch (MalformedURLException urlEx) { throw new ParseException("Invalid resource: " + witnessSpecs[wc]); } } if (inputStreams.length < 1) { throw new ParseException("No input resource(s) given"); } else if (inputStreams.length < 2) { try (InputStream inputStream = inputStreams[0]) { final SimpleCollation collation = JsonProcessor.read(inputStream); witnesses = collation.getWitnesses(); collationAlgorithm = collation.getAlgorithm(); joined = collation.isJoined(); } } final String script = commandLine.getOptionValue("s"); try { final PluginScript pluginScript = (script == null ? PluginScript.read("<internal>", new StringReader("")) : PluginScript.read(argumentToInput(script))); tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer); normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer); comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator); } catch (IOException e) { throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage()); } switch (commandLine.getOptionValue("a", "").toLowerCase()) { case "needleman-wunsch": collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator); break; case "medite": collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR); break; case "gst": collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2); break; default: collationAlgorithm = Optional.ofNullable(collationAlgorithm) .orElse(CollationAlgorithmFactory.dekker(comparator)); break; } if (witnesses == null) { final Charset inputCharset = Charset .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name())); final boolean xmlMode = commandLine.hasOption("xml"); final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath() .compile(commandLine.getOptionValue("xp", "//text()")); witnesses = new ArrayList<>(inputStreams.length); for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) { try (InputStream stream = inputStreams[wc]) { final String sigil = "w" + (wc + 1); if (!xmlMode) { final BufferedReader reader = new BufferedReader( new InputStreamReader(stream, inputCharset)); final StringWriter writer = new StringWriter(); final char[] buf = new char[1024]; while (reader.read(buf) != -1) { writer.write(buf); } witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer)); } else { final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); final Document document = documentBuilder.parse(stream); document.normalizeDocument(); final SimpleWitness witness = new SimpleWitness(sigil); final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET); final List<Token> tokens = new ArrayList<>(tokenNodes.getLength()); for (int nc = 0; nc < tokenNodes.getLength(); nc++) { final String tokenText = tokenNodes.item(nc).getTextContent(); tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText))); } witness.setTokens(tokens); witnesses.add(witness); } } } } final VariantGraph variantGraph = new VariantGraph(); collationAlgorithm.collate(variantGraph, witnesses); if (joined && !commandLine.hasOption("t")) { VariantGraph.JOIN.apply(variantGraph); } final String output = commandLine.getOptionValue("o", "-"); final Charset outputCharset = Charset .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name())); final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase(); try (PrintWriter out = argumentToOutput(output, outputCharset)) { final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph); if ("csv".equals(outputFormat)) { serializer.toCsv(out); } else if ("dot".equals(outputFormat)) { serializer.toDot(out); } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) { XMLStreamWriter xml = null; try { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xml.writeStartDocument(outputCharset.name(), "1.0"); if ("graphml".equals(outputFormat)) { serializer.toGraphML(xml); } else { serializer.toTEI(xml); } xml.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } finally { if (xml != null) { try { xml.close(); } catch (XMLStreamException e) { // ignored } } } } else { JsonProcessor.write(variantGraph, out); } } }
From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java
private List<RatingScale> readScales(String id, String lang) { List<RatingScale> scales = new ArrayList<RatingScale>(); try {/*from w w w. ja v a2s.c o m*/ Document document = getScalesDocument(); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); SimpleNamespaceContext ns = new SimpleNamespaceContext(); ns.bindNamespaceUri("s", SCALES_XML_NS); xPath.setNamespaceContext(ns); XPathExpression exprScales = xPath.compile("/s:ratings/s:rating[@id='" + id + "']/s:scale"); XPathExpression exprName = xPath.compile("s:name[@lang='" + lang + "']"); XPathExpression exprColor = xPath.compile("s:color[@type='html']"); NodeList nodes = (NodeList) exprScales.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); int score = Integer.parseInt(node.getAttributes().getNamedItem("score").getTextContent()); String name = exprName.evaluate(node); String color = exprColor.evaluate(node); RatingScale rs = new RatingScale(name, i, score, color); if (i == 0) { rs.setDefaultRating(true); } scales.add(rs); } } catch (Exception ex) { _log.warn( "Unable to load default scales for id=" + id + ",lang=" + lang + " ratings from " + SCALES_XML, ex); } return scales; }
From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java
private void parseConnectorsThreadData() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(tomcatXML)); Document doc = builder.parse(is); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList connectorsNodeList = (NodeList) xpath.compile("//status/connector") .evaluate(doc.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < connectorsNodeList.getLength(); i++) { Node connector = connectorsNodeList.item(i); NodeList connectorChildren = connector.getChildNodes(); final String connectorName = connector.getAttributes().getNamedItem("name").getNodeValue(); for (int j = 0; j < connectorChildren.getLength(); j++) { Node node = connectorChildren.item(j); if (node.getNodeName().equalsIgnoreCase("threadInfo")) { NamedNodeMap atts = node.getAttributes(); long maxThreads = Long.parseLong(atts.getNamedItem("maxThreads").getNodeValue()); long currentThreadsBusy = Long .parseLong(atts.getNamedItem("currentThreadsBusy").getNodeValue()); long currentThreadCount = Long .parseLong(atts.getNamedItem("currentThreadCount").getNodeValue()); connectorThreadData.put(connectorName, new ThreadData(connectorName, currentThreadCount, currentThreadsBusy, maxThreads)); }/* w w w . ja v a2 s .c om*/ } } }
From source file:au.csiro.casda.sodalint.ValidateCapabilities.java
/** * One or more of the sync and async SODA endpoints should be listed in the capabilities document. * //from w w w . ja va 2 s . c om * @param reporter * validation message destination * @param document * The capabilities XML document * @param sodaService * The service being tested. * @throws XPathExpressionException * If ther eis acoding error in the xpath expression. */ private void checkForSyncAsync(Reporter reporter, Document document, SodaService sodaService) throws XPathExpressionException { final String sodaStdIdPrefix = "ivo://ivoa.net/std/SODA"; final String sodaStdIdSync = "ivo://ivoa.net/std/SODA#sync-1.0"; final String sodaStdIdAsync = "ivo://ivoa.net/std/SODA#async-1.0"; final String accessDataStdIdSync = "ivo://ivoa.net/std/AccessData#sync"; final String accessDataStdIdAsync = "ivo://ivoa.net/std/AccessData#async"; XPath xpath = XPathFactory.newInstance().newXPath(); NodeList capNodeList = (NodeList) xpath.evaluate("capability", document.getDocumentElement(), XPathConstants.NODESET); boolean hasSoda = false; Node syncCapNode = null; Node asyncCapNode = null; for (int i = 0; i < capNodeList.getLength(); i++) { Node capNode = capNodeList.item(i); Node stdIdAttr = capNode.getAttributes().getNamedItem("standardID"); if (stdIdAttr != null && StringUtils.isNotBlank(stdIdAttr.getNodeValue())) { String stdId = stdIdAttr.getNodeValue(); if (stdId.startsWith(sodaStdIdPrefix)) { hasSoda = true; } if (stdId.equals(sodaStdIdSync)) { syncCapNode = capNode; } else if (stdId.equals(sodaStdIdAsync)) { asyncCapNode = capNode; } else if (stdId.equals(accessDataStdIdSync)) { reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId); syncCapNode = capNode; } else if (stdId.equals(accessDataStdIdAsync)) { reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId); asyncCapNode = capNode; } } } if (syncCapNode == null && asyncCapNode == null) { if (hasSoda) { reporter.report(SodaCode.E_CPEP, "SODA endpoints found but they do not have v1.0 sync or async qualifiers"); } else { reporter.report(SodaCode.E_CPEP, "SODA requires at least one of the sync and async endpoints"); } } if (syncCapNode != null) { NodeList interfaces = (NodeList) xpath.evaluate("interface", syncCapNode, XPathConstants.NODESET); if (interfaces == null || interfaces.getLength() == 0) { reporter.report(SodaCode.E_CPIF, "SODA sync endpoint does not contain an interface"); } else { sodaService.setSyncServiceNode(syncCapNode); } } if (asyncCapNode != null) { NodeList interfaces = (NodeList) xpath.evaluate("interface", asyncCapNode, XPathConstants.NODESET); if (interfaces == null || interfaces.getLength() == 0) { reporter.report(SodaCode.E_CPIF, "SODA async endpoint does not contain an interface"); } sodaService.setAsyncServiceNode(asyncCapNode); } }
From source file:org.eclipse.lyo.testsuite.oslcv2.QueryTests.java
@Test public void validLessThanQueryContainsExpectedDefects() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, ParseException { //Build the query using the specified comparison property String query = getQueryBase() + "oslc.where=" + queryComparisonProperty + URLEncoder.encode("<\"" + queryComparisonValue + "\"", "UTF-8") + "&oslc.select=" + queryComparisonProperty;// w w w . j av a 2 s . c om //Get response HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, currentUrl + query, basicCreds, "application/xml", headers); String respBody = EntityUtils.toString(resp.getEntity()); Document doc = OSLCUtils.createXMLDocFromResponseBody(respBody); NodeList results = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest", doc, XPathConstants.NODESET); if (results == null) results = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description", doc, XPathConstants.NODESET); assertTrue(results != null); assertTrue("Expecting query results >0", results.getLength() > 0); //Check that the property elements are less than the query comparison property checkLessThanProperty(results, queryComparisonProperty, queryComparisonValue, doc); }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java
@Test public void testPerformEntityResolutionWithDetermFactors() throws Exception { XmlConverter converter = new XmlConverter(); converter.getDocumentBuilderFactory().setNamespaceAware(true); InputStream attributeParametersStream = getClass() .getResourceAsStream("/xml/TestAttributeParametersWithDeterm.xml"); entityResolutionMessageHandler.setAttributeParametersStream(attributeParametersStream); testRequestMessageInputStream = getClass() .getResourceAsStream("/xml/EntityMergeRequestMessageForDeterm.xml"); Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream); Node entityContainerNode = testRequestMessage .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer") .item(0);//from w ww . jav a 2 s . c o m assertNotNull(entityContainerNode); Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null, null); resultDocument.normalizeDocument(); // LOG.info(converter.toString(resultDocument)); XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(new EntityResolutionNamespaceContext()); NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); for (int i = 0; i < entityNodes.getLength(); i++) { Element e = (Element) entityNodes.item(i); String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref"); assertNotNull(entityIdRef); assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument, XPathConstants.NODE)); } }
From source file:com.dianping.zebra.shard.jdbc.base.SingleDBBaseTestCase.java
protected void parseCreateTableScriptFile() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document configDoc = builder//from w w w . j a va 2 s .c o m .parse(SingleDBBaseTestCase.class.getClassLoader().getResourceAsStream(getCreateTableScriptPath())); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList tableScriptList = (NodeList) xpath.compile("/tables/table").evaluate(configDoc, XPathConstants.NODESET); for (int i = 0; i < tableScriptList.getLength(); i++) { SingleCreateTableScriptEntry entry = new SingleCreateTableScriptEntry(); Element ele = (Element) tableScriptList.item(i); entry.setTableName(ele.getAttribute("name")); entry.setCreateTableScript(ele.getTextContent()); createdTableList.add(entry); } }