List of usage examples for javax.xml.xpath XPathFactory newXPath
public abstract XPath newXPath();
Return a new XPath
using the underlying object model determined when the XPathFactory was instantiated.
From source file:com.amalto.core.util.Util.java
/** * Get a node list from an xPath/* w w w . ja va 2 s . c om*/ * * @throws XtentisException */ public static NodeList getNodeList(Node contextNode, String xPath) throws XtentisException { try { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPathParser = xPathFactory.newXPath(); xPathParser.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String s) { if ("xsd".equals(s)) { //$NON-NLS-1$ return XMLConstants.W3C_XML_SCHEMA_NS_URI; } return null; } @Override public String getPrefix(String s) { if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(s)) { return "xsd"; //$NON-NLS-1$ } return null; } @Override public Iterator getPrefixes(String s) { return Collections.singletonList(s).iterator(); } }); return (NodeList) xPathParser.evaluate(xPath, contextNode, XPathConstants.NODESET); } catch (Exception e) { String err = "Unable to get the Nodes List for xpath '" + xPath + "'" + ((contextNode == null) ? "" : " for Node " + contextNode.getLocalName()) + ": " + e.getLocalizedMessage(); throw new XtentisException(err, e); } }
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 a v a2 s .co 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:com.alliander.osgp.adapter.ws.endpointinterceptors.WebServiceMonitorInterceptor.java
/** * Search an XML element using an XPath expression. * * @param document/*from w ww. ja va2s . c om*/ * The XML document. * @param element * The name of the desired XML element. * * @return The content of the XML element, or null if the element is not * found. * * @throws XPathExpressionException * In case the expression fails to compile or evaluate, an * exception will be thrown. */ private String evaluateXPathExpression(final Document document, final String element) throws XPathExpressionException { final String expression = String.format("//*[contains(local-name(), '%s')]", element); final XPathFactory xFactory = XPathFactory.newInstance(); final XPath xPath = xFactory.newXPath(); final XPathExpression xPathExpression = xPath.compile(expression); final NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET); if (nodeList != null && nodeList.getLength() > 0) { return nodeList.item(0).getTextContent(); } else { return null; } }
From source file:com.sixsq.slipstream.DeploymentController.java
private String[] extractRunStatusAndState(String xml) { try {// w ww. j av a 2s .co m InputSource xmlSource = new InputSource(new StringReader(xml)); XPathFactory xpfactory = XPathFactory.newInstance(); XPath xpath = xpfactory.newXPath(); Object result = xpath.evaluate(STATUS_ATTRS, xmlSource, STRING); String data = result.toString(); return data.split(","); } catch (XPathExpressionException consumed) { return new String[] { "", "" }; } }
From source file:com.seer.datacruncher.validation.MacroRulesValidation.java
/** * Apply validation macro rules.//from w ww . j av a 2 s . com * @param datastreamDTO * @return ResultStepValidation */ protected ResultStepValidation doValidation(DatastreamDTO datastreamDTO) { long schemaId = datastreamDTO.getIdSchema(); List<MacroEntity> list = new ArrayList<MacroEntity>(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder .parse(new ByteArrayInputStream(schemasXSDDao.find(schemaId).getSchemaXSD().getBytes())); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//annotation/appinfo/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { String val = nodes.item(i).getNodeValue(); if (val.startsWith("@RuleCheck")) { String[] arr = val.split(";\n"); for (String s : arr) { list.add(macrosDao.getMacroEntityByName(s.trim().substring(11))); } break; } } } catch (ParserConfigurationException e) { log.error("ParserConfigurationException", e); } catch (SAXException e) { log.error("SAXException", e); } catch (IOException e) { log.error("IOException", e); } catch (XPathExpressionException e) { log.error("XPathExpressionException", e); } ResultStepValidation resultStepValidation = new ResultStepValidation(); resultStepValidation.setValid(true); resultStepValidation.setMessageResult(I18n.getMessage("success.validationOK")); List<Element> xmlTextNodes = null; try { xmlTextNodes = StreamsUtils.parseStreamXml(datastreamDTO.getOutput()); } catch (DocumentException e) { log.error("Stream parse exception", e); } JexlEngine jexl = JexlEngineFactory.getInstance(); boolean isSuccess = true; Pattern pattern = Pattern.compile(MACRO_SQL_VALIDATOR_PATTERN, Pattern.CASE_INSENSITIVE); for (MacroEntity ent : list) { if (!isSuccess) continue; String rule = ent.getRule(); List<Map<String, String>> varsList = parseVars(ent.getVars()); combineVariableLists(varsList, schemaId); Matcher matcher = pattern.matcher(rule); while (matcher.find()) { String varName = matcher.group(4); String sqlRes = "false"; for (Map<String, String> m : varsList) { if (m.get("uniqueName").equals(varName)) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { String prepSql = matcher.group().replaceAll(matcher.group(4), "\"" + el.getText() + "\""); String signum = matcher.group(3); if (signum.equals("<")) { prepSql = prepSql.replaceAll(signum, ">="); } else if (signum.equals(">")) { prepSql = prepSql.replaceAll(signum, "<="); } else if (signum.equals("!=")) { prepSql = prepSql.replaceAll(signum, "="); } Query q = entityManager.createNativeQuery(prepSql); @SuppressWarnings("rawtypes") List resList = q.getResultList(); if ((signum.equals("=") && resList.size() > 0) || (signum.equals("!=") && resList.size() == 0) || (signum.equals(">") && resList.size() == 0) || (signum.equals("<") && resList.size() == 0)) { sqlRes = "true"; } break; } } } } rule = rule.replaceAll(matcher.group(), sqlRes); } Expression e = jexl.createExpression(rule); JexlContext context = new MapContext(); for (Map<String, String> m : varsList) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { context.set(m.get("uniqueName"), JEXLFieldFactory.getField(m.get("fieldType"), el.getText()).getValue()); break; } } } Object res = e.evaluate(context); if (res != null) { isSuccess = false; resultStepValidation.setValid(false); if (ent.getErrorType() == StreamStatus.Warning.getCode()) { resultStepValidation.setWarning(true); } resultStepValidation .setMessageResult(I18n.getMessage("error.validationMacro") + ": " + res.toString()); } } return resultStepValidation; }
From source file:ch.dbs.actions.bestellung.EZBXML.java
private List<String> getJourids(final String content) { final List<String> result = new ArrayList<String>(); try {/* w w w .ja v a 2 s. com*/ if (content != null) { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(new InputSource(new StringReader(content))); final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression exprJournals = xpath.compile("//journals/journal"); final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < journals.getLength(); i++) { final Node firstResultNode = journals.item(i); final Element journal = (Element) firstResultNode; final String id = journal.getAttribute("jourid"); if (id != null) { result.add(id); } } } } catch (final XPathExpressionException e) { LOG.error(e.toString()); } catch (final SAXParseException e) { LOG.error(e.toString()); } catch (final SAXException e) { LOG.error(e.toString()); } catch (final IOException e) { LOG.error(e.toString()); } catch (final ParserConfigurationException e) { LOG.error(e.toString()); } catch (final Exception e) { LOG.error(e.toString()); } return result; }
From source file:it.tidalwave.northernwind.frontend.ui.component.calendar.DefaultCalendarViewController.java
/******************************************************************************************************************* * * * ******************************************************************************************************************/ @PostConstruct//from w ww . j a v a 2s . c o m /* package */ void initialize() throws NotFoundException, IOException, ParserConfigurationException, SAXException, XPathExpressionException, HttpStatusException { final String pathParams = requestHolder.get().getPathParams(siteNode); final int currentYear = getCurrentYear(pathParams); final ResourceProperties siteNodeProperties = siteNode.getProperties(); final ResourceProperties viewProperties = siteNode.getPropertyGroup(view.getId()); // try // { // siteNodeProperties.getProperty(PROPERTY_ENTRIES); // } // catch (NotFoundException e) // { // throw new HttpStatusException(404); // } final String entries = siteNodeProperties.getProperty(PROPERTY_ENTRIES); final StringBuilder builder = new StringBuilder(); final int selectedYear = viewProperties.getIntProperty(PROPERTY_SELECTED_YEAR, currentYear); final int firstYear = viewProperties.getIntProperty(PROPERTY_FIRST_YEAR, Math.min(selectedYear, currentYear)); final int lastYear = viewProperties.getIntProperty(PROPERTY_LAST_YEAR, Math.max(selectedYear, currentYear)); final int columns = 4; builder.append("<div class='nw-calendar'>\n"); appendTitle(builder, siteNodeProperties); builder.append("<table class='nw-calendar-table'>\n").append("<tbody>\n"); builder.append(String.format("<tr>%n<th colspan='%d' class='nw-calendar-title'>%d</th>%n</tr>%n", columns, selectedYear)); final String[] monthNames = DateFormatSymbols.getInstance(requestLocaleManager.getLocales().get(0)) .getMonths(); final String[] shortMonthNames = DateFormatSymbols.getInstance(Locale.ENGLISH).getShortMonths(); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document document = db.parse(new InputSource(new StringReader(entries))); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); for (int month = 1; month <= 12; month++) { if ((month - 1) % columns == 0) { builder.append("<tr>\n"); for (int column = 0; column < columns; column++) { builder.append(String.format("<th width='%d%%'>%s</th>", 100 / columns, monthNames[month + column - 1])); } builder.append("</tr>\n<tr>\n"); } builder.append("<td>\n<ul>\n"); final String pathTemplate = "/calendar/year[@id='%d']/month[@id='%s']/item"; final String jq1 = String.format(pathTemplate, selectedYear, shortMonthNames[month - 1].toLowerCase()); final XPathExpression jx1 = xPath.compile(jq1); final NodeList nodes = (NodeList) jx1.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { // FIXME: verbose XML code below final Node node = nodes.item(i); final String link = site .createLink(new ResourcePath(node.getAttributes().getNamedItem("link").getNodeValue())); String linkClass = ""; Node typeNode = node.getAttributes().getNamedItem("type"); if (typeNode != null) { linkClass = String.format(" class='nw-calendar-table-link-%s'", typeNode.getNodeValue()); } final String name = node.getAttributes().getNamedItem("name").getNodeValue(); builder.append(String.format("<li><a href='%s'%s>%s</a></li>%n", link, linkClass, name)); } builder.append("</ul>\n</td>\n"); if ((month - 1) % columns == (columns - 1)) { builder.append("</tr>\n"); } } builder.append("</tbody>\n</table>\n"); appendYearSelector(builder, firstYear, lastYear, selectedYear); builder.append("</div>\n"); view.setContent(builder.toString()); }
From source file:org.openremote.foxycart.resources.FoxyCartResource.java
private String evaluateXPath(Document doc, String xPathExpression) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); String text = null;/*from w w w.jav a 2s. c o m*/ try { XPathExpression expr = xpath.compile(xPathExpression); text = (String) expr.evaluate(doc, XPathConstants.STRING); } catch (XPathExpressionException e) { } return text; }
From source file:com.netscape.cms.tomcat.PKIListener.java
@Override public void lifecycleEvent(LifecycleEvent event) { String type = event.getType(); logger.info("PKIListener: " + event.getLifecycle().getClass().getName() + " [" + type + "]"); if (type.equals(Lifecycle.BEFORE_INIT_EVENT)) { String wdPipeName = System.getenv("WD_PIPE_NAME"); if (StringUtils.isNotEmpty(wdPipeName)) { startedByWD = true;/*ww w .j ava 2 s . co m*/ logger.info("PKIListener: Initializing the watchdog"); WatchdogClient.init(); } logger.info("PKIListener: Initializing TomcatJSS"); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String catalinaBase = System.getProperty("catalina.base"); File file = new File(catalinaBase + "/conf/server.xml"); Document doc = builder.parse(file); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); Element connector = (Element) xpath.evaluate( "/Server/Service[@name='Catalina']/Connector[@name='Secure']", doc, XPathConstants.NODE); TomcatJSS tomcatjss = TomcatJSS.getInstance(); String certDb = connector.getAttribute("certdbDir"); if (certDb != null) tomcatjss.setCertdbDir(certDb); String passwordClass = connector.getAttribute("passwordClass"); if (passwordClass != null) tomcatjss.setPasswordClass(passwordClass); String passwordFile = connector.getAttribute("passwordFile"); if (passwordFile != null) tomcatjss.setPasswordFile(passwordFile); String serverCertNickFile = connector.getAttribute("serverCertNickFile"); if (serverCertNickFile != null) tomcatjss.setServerCertNickFile(serverCertNickFile); String enableOCSP = connector.getAttribute("enableOCSP"); if (enableOCSP != null) tomcatjss.setEnableOCSP(Boolean.parseBoolean(enableOCSP)); String ocspResponderURL = connector.getAttribute("ocspResponderURL"); if (ocspResponderURL != null) tomcatjss.setOcspResponderURL(ocspResponderURL); String ocspResponderCertNickname = connector.getAttribute("ocspResponderCertNickname"); if (ocspResponderCertNickname != null) tomcatjss.setOcspResponderCertNickname(ocspResponderCertNickname); String ocspCacheSize = connector.getAttribute("ocspCacheSize"); if (ocspCacheSize != null) tomcatjss.setOcspCacheSize(Integer.parseInt(ocspCacheSize)); String ocspMinCacheEntryDuration = connector.getAttribute("ocspMinCacheEntryDuration"); if (ocspMinCacheEntryDuration != null) tomcatjss.setOcspMinCacheEntryDuration(Integer.parseInt(ocspMinCacheEntryDuration)); String ocspMaxCacheEntryDuration = connector.getAttribute("ocspMaxCacheEntryDuration"); if (ocspMaxCacheEntryDuration != null) tomcatjss.setOcspMaxCacheEntryDuration(Integer.parseInt(ocspMaxCacheEntryDuration)); String ocspTimeout = connector.getAttribute("ocspTimeout"); if (ocspTimeout != null) tomcatjss.setOcspTimeout(Integer.parseInt(ocspTimeout)); String strictCiphers = connector.getAttribute("strictCiphers"); if (strictCiphers != null) tomcatjss.setStrictCiphers(strictCiphers); String sslVersionRangeStream = connector.getAttribute("sslVersionRangeStream"); if (sslVersionRangeStream != null) tomcatjss.setSslVersionRangeStream(sslVersionRangeStream); String sslVersionRangeDatagram = connector.getAttribute("sslVersionRangeDatagram"); if (sslVersionRangeDatagram != null) tomcatjss.setSslVersionRangeDatagram(sslVersionRangeDatagram); String sslRangeCiphers = connector.getAttribute("sslRangeCiphers"); if (sslRangeCiphers != null) tomcatjss.setSslRangeCiphers(sslRangeCiphers); String sslOptions = connector.getAttribute("sslOptions"); if (sslOptions != null) tomcatjss.setSslOptions(sslOptions); String ssl2Ciphers = connector.getAttribute("ssl2Ciphers"); if (ssl2Ciphers != null) tomcatjss.setSsl2Ciphers(ssl2Ciphers); String ssl3Ciphers = connector.getAttribute("ssl3Ciphers"); if (ssl3Ciphers != null) tomcatjss.setSsl3Ciphers(ssl3Ciphers); String tlsCiphers = connector.getAttribute("tlsCiphers"); if (tlsCiphers != null) tomcatjss.setTlsCiphers(tlsCiphers); tomcatjss.init(); } catch (Exception e) { throw new RuntimeException(e); } } else if (type.equals(Lifecycle.AFTER_START_EVENT)) { if (startedByWD) { logger.info("PKIListener: Sending endInit to the watchdog"); WatchdogClient.sendEndInit(0); } verifySubsystems((Server) event.getLifecycle()); } }
From source file:org.joy.config.Configuration.java
public void loadConfiguration() { try {/*from www. j a v a 2 s. co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(configurationFile); XPathFactory f = XPathFactory.newInstance(); XPath path = f.newXPath(); parseClassPathEntry(doc, path); parseConnections(doc, path); parseTemplates(doc, path); tagertProject = path.evaluate("/configuration/tagertProject/text()", doc); basePackage = path.evaluate("/configuration/basePackage/text()", doc); moduleName = path.evaluate("/configuration/moduleName/text()", doc); } catch (Exception e) { throw new Wrong(e); } }