/** * Extracts the workflow from the plan. * * @param plan the plan to extract the workflow from. * @return The workflow File * @throws PluginException if an error occurs extracting the workflow from the plan. */ private File getWorkflowFile(final Document plan) throws PluginException { final XPathFactory xPathfactory = XPathFactory.newInstance(); final XPath xpath = xPathfactory.newXPath(); Writer writer = null; try { xpath.setNamespaceContext(new PlanNamespaceContext()); final XPathExpression expr = xpath.compile(xpathSelectWorkflow); final Element elementWorkflow = (Element) expr.evaluate(plan, XPathConstants.NODE); // Prepare the DOM document for writing final Source source = new DOMSource(elementWorkflow); final File workflowFile = new File(new File(RODA_HOME, "data"), WORKFLOW_FILENAME); writer = new OutputStreamWriter(new FileOutputStream(workflowFile)); final Result result = new StreamResult(writer); // Write the DOM document to the file final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); writer.close(); return workflowFile; } catch (XPathExpressionException e) { logger.error("Error compiling XPATH expression or evaluating the plan - " + e.getMessage()); throw new PluginException( "Error compiling XPATH expression or evaluating the plan - " + e.getMessage(), e); } catch (FileNotFoundException e) { logger.error("Error opening output file for writting - " + e.getMessage()); throw new PluginException("Error opening output file for writting - " + e.getMessage(), e); } catch (TransformerFactoryConfigurationError e) { logger.error("Error writing workflow file - " + e.getMessage()); throw new PluginException("Error writing workflow file - " + e.getMessage(), e); } catch (TransformerException e) { logger.error("Error writing workflow file - " + e.getMessage()); throw new PluginException("Error writing workflow file - " + e.getMessage(), e); } catch (IOException e) { logger.error("Error writing workflow file - " + e.getMessage()); throw new PluginException("Error writing workflow file - " + e.getMessage(), e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { logger.error("Error closing output writer - " + e.getMessage()); } } } }
private Node evaluateXPathNode( 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 } if (nlst.getLength() != 1) { reportError( (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVAULATES_TO_TOO_MANY_TARGETS( expression, nlst.getLength())); return null; // abort } Node rnode = nlst.item(0); if (!(rnode instanceof Element)) { reportError( (Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NON_ELEMENT(expression)); return null; // abort } return rnode; }
/** * Runs an XPath expression on this node. * * @param env * @param expression * @return array of results * @throws XPathExpressionException */ public Value xpath(Env env, String expression) { try { XPath xpath = XPathFactory.newInstance().newXPath(); InputSource is = new InputSource(asXML(env).toInputStream()); NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET); int nodeLength = nodes.getLength(); if (nodeLength == 0) return NullValue.NULL; // There are matching nodes ArrayValue result = new ArrayValueImpl(); for (int i = 0; i < nodeLength; i++) { Node node = nodes.item(i); boolean isPrefix = node.getPrefix() != null; SimpleXMLElement xml = buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix); result.put(wrapJava(env, _cls, xml)); } return result; } catch (XPathExpressionException e) { env.warning(e); log.log(Level.FINE, e.getMessage()); return NullValue.NULL; } }
@Override protected String verifyWpsResponse(final String responseStr) throws Exception { final Document responseData = XmlDocumentBuilder.parse(responseStr, false); Assert.assertNotNull(responseData); // System.out.println(XmlDocumentBuilder.toString(responseData)); XPath xpath = XmlDocumentBuilder.createXPath(); String jobIdStr = null; try { Assert.assertEquals(processId, xpath.evaluate(".//Process/Identifier", responseData)); NodeList returnedNodes = XPathAPI.selectNodeList(responseData, ".//ProcessOutputs/Output"); Assert.assertEquals(1, returnedNodes.getLength()); Assert.assertEquals( "jobId", xpath.evaluate(".//ProcessOutputs/Output/Identifier", responseData)); Assert.assertEquals( "string", xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData/@dataType", responseData)); jobIdStr = xpath.evaluate(".//ProcessOutputs/Output/Data/LiteralData", responseData); Assert.assertNotNull(UUID.fromString(jobIdStr)); } catch (XPathExpressionException e) { Assert.fail("Error parsing response document: " + e.getMessage()); } return jobIdStr; }
private Element evaluateXPathNode( Node target, String expression, NamespaceContext namespaceContext) { NodeList nlst; try { xpath.setNamespaceContext(namespaceContext); nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET); } catch (XPathExpressionException e) { Util.fail("internalizer.XPathEvaluationError", e.getMessage()); return null; // abort processing this <jaxb:bindings> } if (nlst.getLength() == 0) { Util.fail("internalizer.XPathEvaluatesToNoTarget", new Object[] {expression}); return null; // abort } if (nlst.getLength() != 1) { Util.fail( "internalizer.XPathEvaulatesToTooManyTargets", new Object[] {expression, nlst.getLength()}); return null; // abort } Node rnode = nlst.item(0); if (!(rnode instanceof Element)) { Util.fail("internalizer.XPathEvaluatesToNonElement", new Object[] {expression}); return null; // abort } return (Element) rnode; }
/** * Removes all the given tags from the document. * * @param dom the document object. * @param tagName the tag name, examples: script, style, meta * @return the changed dom. */ public static Document removeTags(Document dom, String tagName) { if (dom != null) { // NodeList list = dom.getElementsByTagName("SCRIPT"); NodeList list; try { list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase()); while (list.getLength() > 0) { Node sc = list.item(0); if (sc != null) { sc.getParentNode().removeChild(sc); } list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase()); // list = dom.getElementsByTagName("SCRIPT"); } } catch (XPathExpressionException e) { LOGGER.error(e.getMessage(), e); } return dom; } return null; }
public void retrieveNews() { try { // HttpClient client = new DefaultHttpClient(); // HttpResponse response = client.execute(new // HttpGet("http://uaonline.ua.pt/xml/contents_xml.asp")); // HttpEntity tmpEntity = response.getEntity(); // SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser(); // XMLReader xmlReader = xmlParser.getXMLReader(); // NewsHandler newsHandler = new NewsHandler(); // xmlReader.setContentHandler(newsHandler); // // Reader test = new InputStreamReader(uaNewsURL.openStream()); // InputSource is = new InputSource(test); // is.setEncoding("ISO-8859-1"); // xmlReader.parse(is); // return newsHandler.getFeed(); URL uaNewsURL = new URL("http://uaonline.ua.pt/xml/contents_xml.asp"); DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document xmlNews = xmlBuilder.parse(uaNewsURL.openStream()); XPath query; NodeList newsItems; query = XPathFactory.newInstance().newXPath(); Object result = query.compile("/rss/channel/item").evaluate(xmlNews, XPathConstants.NODESET); newsItems = (NodeList) result; NewsItem tempItem; Element tmpElem; for (int i = 0; i < newsItems.getLength(); i++) { tmpElem = (Element) newsItems.item(i); tempItem = parseInfo(tmpElem); this.addItem(tempItem); } } catch (MalformedURLException e) { System.out.println("NewsFeed: retrieveNews: " + e.getMessage()); System.out.println( "NewsFeed: retrieveNews: MalformedURLException " + e.getLocalizedMessage()); } catch (ParserConfigurationException e) { System.out.println("NewsFeed: retrieveNews: " + e.getMessage()); System.out.println( "NewsFeed: retrieveNews: ParserConfigurationException " + e.getLocalizedMessage()); } catch (IOException e) { System.out.println("NewsFeed: retrieveNews: " + e.getMessage()); System.out.println("NewsFeed: retrieveNews: IOException " + e.getLocalizedMessage()); } catch (XPathExpressionException e) { System.out.println("NewsFeed: retrieveNews: " + e.getMessage()); System.out.println( "NewsFeed: retrieveNews: XPathExpressionException " + e.getLocalizedMessage()); } catch (SAXException e) { System.out.println("NewsFeed: retrieveNews: " + e.getMessage()); System.out.println("NewsFeed: retrieveNews: SAXException " + e.getLocalizedMessage()); } }
public KModuleDeploymentService() { try { processIdXPathExpression = XPathFactory.newInstance().newXPath().compile(PROCESS_ID_XPATH); } catch (XPathExpressionException e) { logger.error( "Unable to parse '{}' XPath expression due to {}", PROCESS_ID_XPATH, e.getMessage()); } }
private void initFromXml(Element ele, Version fileVersion) throws ParseException { try { partNumber = SaveUtil.parseValue(ele, "@id", partNumber); title = SaveUtil.parseValue(ele, "title", title); instrument = SaveUtil.parseValue(ele, "instrument", instrument); for (Element trackEle : XmlUtil.selectElements(ele, "track")) { // Try to find the specified track in the midi sequence by name, in case it moved int t = findTrackNumberByName(SaveUtil.parseValue(trackEle, "@name", "")); // Fall back to the track ID if that didn't work if (t == -1) t = SaveUtil.parseValue(trackEle, "@id", -1); if (t < 0 || t >= getTrackCount()) { throw SaveUtil.invalidValueException( trackEle, "Could not find track number " + t + " in original MIDI file"); } // Now set the track info trackEnabled[t] = true; enabledTrackCount++; trackTranspose[t] = SaveUtil.parseValue(trackEle, "transpose", trackTranspose[t]); trackVolumeAdjust[t] = SaveUtil.parseValue(trackEle, "volumeAdjust", trackVolumeAdjust[t]); if (instrument.isPercussion) { Element drumsEle = XmlUtil.selectSingleElement(trackEle, "drumsEnabled"); if (drumsEle != null) { boolean defaultEnabled = SaveUtil.parseValue(drumsEle, "@defaultEnabled", !isCowbellPart()); BitSet[] enabledSet; if (isCowbellPart()) { if (cowbellsEnabled == null) cowbellsEnabled = new BitSet[getTrackCount()]; enabledSet = cowbellsEnabled; } else { if (drumsEnabled == null) drumsEnabled = new BitSet[getTrackCount()]; enabledSet = drumsEnabled; } enabledSet[t] = new BitSet(MidiConstants.NOTE_COUNT); if (defaultEnabled) enabledSet[t].set(0, MidiConstants.NOTE_COUNT, true); for (Element drumEle : XmlUtil.selectElements(drumsEle, "note")) { int id = SaveUtil.parseValue(drumEle, "@id", -1); if (id >= 0 && id < MidiConstants.NOTE_COUNT) enabledSet[t].set(id, SaveUtil.parseValue(drumEle, "@isEnabled", !defaultEnabled)); } } Element drumMapEle = XmlUtil.selectSingleElement(trackEle, "drumMap"); if (drumMapEle != null) drumNoteMap[t] = DrumNoteMap.loadFromXml(drumMapEle, fileVersion); } } } catch (XPathExpressionException e) { throw new ParseException("XPath error: " + e.getMessage(), null); } }
private List<ICompletionProposal> proposeParameter( IJavaProject project, final int offset, final int length, Node statementNode, final boolean searchReadable, final String matchString) { List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); if (statementNode == null) return proposals; String statementId = null; String paramType = null; NamedNodeMap statementAttrs = statementNode.getAttributes(); for (int i = 0; i < statementAttrs.getLength(); i++) { Node attr = statementAttrs.item(i); String attrName = attr.getNodeName(); if ("id".equals(attrName)) statementId = attr.getNodeValue(); else if ("parameterType".equals(attrName)) paramType = attr.getNodeValue(); } if (statementId == null || statementId.length() == 0) return proposals; if (paramType != null) { String resolved = TypeAliasCache.getInstance().resolveAlias(project, paramType, null); proposals = ProposalComputorHelper.proposePropertyFor( project, offset, length, resolved != null ? resolved : paramType, searchReadable, -1, matchString); } else { try { final List<MapperMethodInfo> methodInfos = new ArrayList<MapperMethodInfo>(); String mapperFqn = MybatipseXmlUtil.getNamespace(statementNode.getOwnerDocument()); JavaMapperUtil.findMapperMethod( methodInfos, project, mapperFqn, statementId, true, new RejectStatementAnnotation()); if (methodInfos.size() > 0) { proposals = ProposalComputorHelper.proposeParameters( project, offset, length, methodInfos.get(0).getParams(), searchReadable, matchString); } } catch (XPathExpressionException e) { Activator.log(Status.ERROR, e.getMessage(), e); } } return proposals; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); javax.servlet.http.Cookie[] theCookies = request.getCookies(); String param = null; boolean foundit = false; if (theCookies != null) { for (javax.servlet.http.Cookie theCookie : theCookies) { if (theCookie.getName().equals("vector")) { param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8"); foundit = true; } } if (!foundit) { // no cookie found in collection param = ""; } } else { // no cookies param = ""; } String bar = new Test().doSomething(param); try { java.io.FileInputStream file = new java.io.FileInputStream( org.owasp.benchmark.helpers.Utils.getFileFromClasspath( "employees.xml", this.getClass().getClassLoader())); javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder(); org.w3c.dom.Document xmlDocument = builder.parse(file); javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xp = xpf.newXPath(); response.getWriter().println("Your query results are: <br/>"); String expression = "/Employees/Employee[@emplid='" + bar + "']"; response.getWriter().println(xp.evaluate(expression, xmlDocument) + "<br/>"); } catch (javax.xml.xpath.XPathExpressionException e) { // OK to swallow System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } catch (javax.xml.parsers.ParserConfigurationException e) { System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } catch (org.xml.sax.SAXException e) { System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } } // end doPost
/** @see com.aptana.ide.core.model.ITransformObject#fromNode(org.w3c.dom.Node) */ public void fromNode(Node node) { try { NodeList set = (NodeList) XPATH.evaluate(getItemString(), node, XPathConstants.NODESET); updateGroup(set); } catch (XPathExpressionException e1) { isLoading = false; String message = MessageFormat.format( Messages.getString("CoreGroupObject.XPath_Error_During_Parse"), // $NON-NLS-1$ new Object[] {getLoggingPrefix(), e1.getMessage()}); logError(message); } }
protected String getProcessId(String processSource) { try { InputSource inputSource = new InputSource(new StringReader(processSource)); String processId = (String) processIdXPathExpression.evaluate(inputSource, XPathConstants.STRING); return processId; } catch (XPathExpressionException e) { logger.error("Unable to find process id from process source due to {}", e.getMessage()); return null; } }
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) { // Evaluate the arguments AttributeValue[] argValues = new AttributeValue[inputs.size()]; EvaluationResult result = evalArgs(inputs, context, argValues); if (result != null) { return result; } switch (getFunctionId()) { case ID_XPATH_NODE_COUNT: { XPathAttribute xpathAttribute = ((XPathAttribute) argValues[0]); String xpathValue = xpathAttribute.getValue(); String category = xpathAttribute.getXPathCategory(); Node contextNode = null; // this must be XACML 3 Set<Attributes> attributesSet = ((XACML3EvaluationCtx) context).getAttributes(category); if (attributesSet != null) { // only one attributes can be there Attributes attributes = attributesSet.iterator().next(); contextNode = attributes.getContent(); } if (contextNode != null) { // now apply XPath try { NodeList nodeList = getXPathResults(contextNode, xpathValue); return new EvaluationResult(new IntegerAttribute(nodeList.getLength())); } catch (XPathExpressionException e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } } } case ID_XPATH_NODE_EQUAL: { // TODO } } List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, "Not supported function"); return new EvaluationResult(status); }
private void generateResults( ContentAssistRequest contentAssistRequest, int offset, int length, Node parentNode, Node typeAttr) { if (typeAttr == null) return; String typeValue = typeAttr.getNodeValue(); if (typeValue == null || typeValue.length() == 0) return; IJavaProject project = getJavaProject(contentAssistRequest); // Try resolving the alias. String qualifiedName = TypeAliasCache.getInstance().resolveAlias(project, typeValue, null); if (qualifiedName == null) { // Assumed to be FQN. qualifiedName = typeValue; } BeanPropertyInfo beanProps = BeanPropertyCache.getBeanPropertyInfo(project, qualifiedName); try { Set<String> existingProps = new HashSet<String>(); NodeList existingPropNodes = XpathUtil.xpathNodes(parentNode, "*[@property]/@property"); for (int i = 0; i < existingPropNodes.getLength(); i++) { existingProps.add(existingPropNodes.item(i).getNodeValue()); } StringBuilder resultTags = new StringBuilder(); for (Entry<String, String> prop : beanProps.getWritableFields().entrySet()) { String propName = prop.getKey(); if (!existingProps.contains(propName)) { resultTags .append("<result property=\"") .append(propName) .append("\" column=\"") .append(propName) .append("\" />\n"); } } contentAssistRequest.addProposal( new CompletionProposal( resultTags.toString(), offset, length, resultTags.length(), Activator.getIcon(), "<result /> for properties", null, null)); } catch (XPathExpressionException e) { Activator.log(Status.ERROR, e.getMessage(), e); } }
@Override public Document modifyDocument(Document document, String value) { if (value == null || value.isEmpty()) { return document; } try { Node node = getNodeFromXpath(document); node.setTextContent(value); } catch (XPathExpressionException ex) { ex.fillInStackTrace(); Logger.getLogger(HeritrixParameterValueModifier.class.getName()).warn(ex.getMessage()); } return document; }
/** * Gets the URLs of files this plan applies to. * * @param plan the plan * @return a {@link List} of file URLs. * @throws PluginException if an error occurred extracting URLs from the plan. */ private List<String> getFileURLsFromPlan(final Document plan) throws PluginException { final List<String> fileURLs = new ArrayList<String>(); final XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new PlanNamespaceContext()); try { final XPathExpression expr = xpath.compile(xpathSelectIDs); final NodeList nl = (NodeList) expr.evaluate(plan, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { final Node item = nl.item(i); fileURLs.add(item.getNodeValue()); } return fileURLs; } catch (XPathExpressionException e) { logger.error("Error reading file URLs from plan - " + e.getMessage()); throw new PluginException("Error reading file URLs from plan - " + e.getMessage(), e); } }
private String handleResponse(HttpResponse httpResponse) throws IOException { final int ok = 200; if (httpResponse.getStatusLine().getStatusCode() == ok) { String reply = IOUtils.toString(httpResponse.getEntity().getContent()); if (reply == null) { LOGGER.error("Http request failed. Service did not respond."); return "-"; } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(reply.getBytes())); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/calendarItems/status/text()"); String status = expr.evaluate(doc); if ("PROCESSED".equals(status)) { String res = xpath.compile("/calendarItems/total/text()").evaluate(doc); return res; } else { return ""; // The user does not have any notes calendar and should receive nothing. } } catch (RuntimeException ex) { LOGGER.warn(ex.getMessage()); } catch (ParserConfigurationException e) { LOGGER.warn(e.getMessage()); } catch (SAXException e) { LOGGER.warn(e.getMessage()); } catch (XPathExpressionException e) { LOGGER.warn(e.getMessage()); } return "-"; } else { LOGGER.error( "Http request failed. Response code=" + httpResponse.getStatusLine().getStatusCode() + ". " + httpResponse.getStatusLine().getReasonPhrase()); return "-"; } }
public NodeList xpathRealQuery(String doc, String query) { log.debug("xpathRealQuery(String doc, String query)"); XPathFactory xpathFact = XPathFactory.newInstance(); XPath xpath = xpathFact.newXPath(); XPathExpression expr = null; NodeList res = null; try { expr = xpath.compile(query); Object result = expr.evaluate(doc, XPathConstants.STRING); res = (NodeList) result; } catch (XPathExpressionException e) { log.debug(e.getMessage()); return null; } return res; }
private boolean splitConcatDocument(File concatFile) { try { EpubUtils.outputMessage(taskOutput, "Splitting concat document"); // create concat document Document sourceDoc = EpubUtils.createDocument(concatFile, taskOutput); if (sourceDoc == null) { return false; } // Find Source body XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node sourceBody = (Node) xpath.evaluate( "//*[local-name() = 'body']", sourceDoc.getDocumentElement(), XPathConstants.NODE); NodeList bodyNodes = sourceBody.getChildNodes(); for (int i = 0; i < bodyNodes.getLength(); i++) { Node sectionNodeAtLevel1 = bodyNodes.item(i); if (sectionNodeAtLevel1.getNodeType() == Node.ELEMENT_NODE) { createNewEpubDoc(sectionNodeAtLevel1); } } return true; } catch (XPathExpressionException xpee) { EpubUtils.outputMessage( taskOutput, "Could not split concat document. An XPathExpressionException occurred: " + xpee.getMessage()); } catch (AuthorOperationException aoe) { EpubUtils.outputMessage( taskOutput, "Could not split concat document. An AuthorOperationException occurred: " + aoe.getMessage()); } catch (Exception e) { EpubUtils.outputMessage( taskOutput, "Could not split concat document. An Exception occurred: " + e.getMessage()); } return false; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); java.util.Map<String, String[]> map = request.getParameterMap(); String param = ""; if (!map.isEmpty()) { String[] values = map.get("vector"); if (values != null) param = values[0]; } String bar = new Test().doSomething(param); try { java.io.FileInputStream file = new java.io.FileInputStream( org.owasp.benchmark.helpers.Utils.getFileFromClasspath( "employees.xml", this.getClass().getClassLoader())); javax.xml.parsers.DocumentBuilderFactory builderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder builder = builderFactory.newDocumentBuilder(); org.w3c.dom.Document xmlDocument = builder.parse(file); javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xp = xpf.newXPath(); String expression = "/Employees/Employee[@emplid='" + bar + "']"; response.getWriter().println("Your query results are: <br/>"); org.w3c.dom.NodeList nodeList = (org.w3c.dom.NodeList) xp.compile(expression).evaluate(xmlDocument, javax.xml.xpath.XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { org.w3c.dom.Element value = (org.w3c.dom.Element) nodeList.item(i); response.getWriter().println(value.getTextContent() + "<br/>"); } } catch (javax.xml.xpath.XPathExpressionException e) { // OK to swallow System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } catch (javax.xml.parsers.ParserConfigurationException e) { System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } catch (org.xml.sax.SAXException e) { System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } } // end doPost
public void fromXML(XMLDocument xmlDocument) { try { type = MarkContactType.valueOf(xmlDocument.getNodeValue(TYPE_EXPR)); name = xmlDocument.getNodeValue(NAME_EXPR); org = xmlDocument.getNodeValue(ORG_EXPR); voice = xmlDocument.getNodeValue(VOICE_EXPR); voiceExt = xmlDocument.getNodeValue(VOICE_EXT_EXPR); fax = xmlDocument.getNodeValue(FAX_EXPR); faxExt = xmlDocument.getNodeValue(FAX_EXT_EXPR); email = xmlDocument.getNodeValue(EMAIL_EXPR); Node addressElement = xmlDocument.getElement(ADDRESS_EXPR); if (addressElement != null) { address = new MarkAddress(); address.fromXML(new XMLDocument((Element) addressElement)); } } catch (XPathExpressionException e) { maintLogger.warning(e.getMessage()); } }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest(request); String param = scr.getTheParameter("foo"); String bar = doSomething(param); javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xp = xpf.newXPath(); try { xp.compile(bar); } catch (javax.xml.xpath.XPathExpressionException e) { // OK to swallow System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } } // end doPost
public static Document replaceTokens(Document doc, Policy configTokens) throws XPathExpressionException, TransformerConfigurationException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(configTokens); logger.info("============= to apply the following config tokens ================\n{}", json); try { for (int i = 0; i < configTokens.tokens.size(); i++) { logger.debug( "=============Checking for Xpath Expressions {} ================\n", configTokens.tokens.get(i).xpath); XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath); NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); for (int j = 0; j < nodes.getLength(); j++) { if (nodes.item(j).hasChildNodes()) { logger.debug( "=============Updated existing value {} to new value {} ================\n", nodes.item(j).getTextContent(), configTokens.tokens.get(i).value); nodes.item(j).setTextContent(configTokens.tokens.get(i).value); } } } return doc; } catch (XPathExpressionException e) { logger.error( String.format( "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s", e.getMessage()), e); throw e; } }
/** * Return nodeValue of given xpath expression. * * @param payload * @param xpathExpression * @return NodeValue of xpathExpression or empty string if nothing was found * @throws MojoFailureException if more then one result was found * @throws MojoExecutionException */ public static String getXpathNodeValue(Document payload, String xpathExpression) throws MojoExecutionException, MojoFailureException { String nodeValue = ""; try { final XPathFactory xpf = XPathFactory.newInstance(); final XPath xpath = xpf.newXPath(); final XPathExpression expr = xpath.compile(xpathExpression); final NodeList nodes = (NodeList) expr.evaluate(payload, XPathConstants.NODESET); if (nodes.getLength() == 1) { nodeValue = getNodeValue(nodes.item(0)); } else if (nodes.getLength() > 1) { throw new MojoFailureException("Error: found multiple nodes for " + xpathExpression); } } catch (XPathExpressionException e) { throw new MojoExecutionException(e.getMessage(), e); } return nodeValue; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; String bar = new Test().doSomething(param); javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xp = xpf.newXPath(); try { xp.compile(bar); } catch (javax.xml.xpath.XPathExpressionException e) { // OK to swallow System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } } // end doPost
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest(request); String param = scr.getTheParameter("foo"); // Chain a bunch of propagators in sequence String a20448 = param; // assign StringBuilder b20448 = new StringBuilder(a20448); // stick in stringbuilder b20448.append(" SafeStuff"); // append some safe content b20448.replace( b20448.length() - "Chars".length(), b20448.length(), "Chars"); // replace some of the end content java.util.HashMap<String, Object> map20448 = new java.util.HashMap<String, Object>(); map20448.put("key20448", b20448.toString()); // put in a collection String c20448 = (String) map20448.get("key20448"); // get it back out String d20448 = c20448.substring(0, c20448.length() - 1); // extract most of it String e20448 = new String( new sun.misc.BASE64Decoder() .decodeBuffer( new sun.misc.BASE64Encoder() .encode(d20448.getBytes()))); // B64 encode and decode it String f20448 = e20448.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g20448 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g20448); // reflection javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xp = xpf.newXPath(); try { xp.compile(bar); } catch (javax.xml.xpath.XPathExpressionException e) { // OK to swallow System.out.println("XPath expression exception caught and swallowed: " + e.getMessage()); } }
public boolean xpathQuery(Document doc, String query) { log.debug("xpathQuery(Document doc, String query)"); log.debug("path: " + query); XPathFactory xpathFact = XPathFactory.newInstance(); XPath xpath = xpathFact.newXPath(); boolean ret = false; try { ret = (xpath.evaluate(query, doc) == null) ? false : true; } catch (XPathExpressionException e) { log.debug("exception"); log.debug(e.getMessage()); return false; } if (ret == false) { log.debug("ret is false"); log.debug(BioFuzzUtils.domToString(doc)); } return ret; }
@SuppressWarnings("unused") @Override public EvaluationResult findAttribute( String contextPath, URI attributeType, String contextSelector, Node root, EvaluationCtx context, String xpathVersion) { Node contextNode = null; NamespaceContext namespaceContext = null; System.out.println( "Context path ==> " + contextPath + " AttributeType ==> " + attributeType + " Context Selector ==> " + contextSelector + " Root Node name ==> " + root.getNodeName() + " root node type==> " + root.getNodeType() + " root node value==> " + root.getNodeValue() + " Context ==> " + context + " XPath version ==> " + xpathVersion); if (root == null) { System.out.println("Root node is null "); // root == null means there is not content element defined with the // attributes element // therefore complete request is evaluated. // get the DOM root of the request document contextNode = context.getRequestRoot(); } else if (contextSelector != null) { System.out.println("Content selector is not null "); // root != null means content element is there. we can find the // context node by // evaluating the contextSelector // 1st assume context node as the root // TODO - Check if the contextNode should be assigned to root contextNode = root; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // see if the request root is in a namespace String namespace = null; if (contextNode != null) { namespace = contextNode.getNamespaceURI(); System.out.println(" nameSpace ==> " + contextNode); } // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = contextNode.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue = n.getNodeValue(); System.out.println("nodeValue of nameaspace ==> " + nodeValue); nsMap.put(prefix, nodeValue); } // if there is not any namespace is defined for content element, // default XACML request // name space would be there. if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) { nsMap.put("xacml", namespace); } namespaceContext = new DefaultNamespaceContext(nsMap); xpath.setNamespaceContext(namespaceContext); try { XPathExpression expression = xpath.compile(contextSelector); NodeList result = (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET); if (result == null || result.getLength() == 0) { throw new Exception("No node is found from context selector id evaluation"); } else if (result.getLength() != 1) { throw new Exception("More than one node is found from context selector id evaluation"); } contextNode = result.item(0); } catch (Exception e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } } else { contextNode = root; } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if (namespaceContext == null) { // see if the request root is in a namespace String namespace = null; if (contextNode != null) { namespace = contextNode.getNamespaceURI(); } // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = contextNode.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue = n.getNodeValue(); nsMap.put(prefix, nodeValue); } // if there is not any namespace is defined for content element, // default XACML request // name space would be there. if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) { nsMap.put("xacml", namespace); } namespaceContext = new DefaultNamespaceContext(nsMap); } xpath.setNamespaceContext(namespaceContext); NodeList matches; try { XPathExpression expression = xpath.compile(contextPath); matches = (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET); if (matches == null || matches.getLength() < 1) { throw new Exception("No node is found from xpath evaluation"); } } catch (XPathExpressionException e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } catch (Exception e) { List<String> codes = new ArrayList<String>(); codes.add(Status.STATUS_SYNTAX_ERROR); Status status = new Status(codes, e.getMessage()); return new EvaluationResult(status); } if (matches.getLength() == 0) { // we didn't find anything, so we return an empty bag return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); } // there was at least one match, so try to generate the values try { ArrayList<AttributeValue> list = new ArrayList<AttributeValue>(); AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); for (int i = 0; i < matches.getLength(); i++) { String text = null; Node node = matches.item(i); short nodeType = node.getNodeType(); // see if this is straight text, or a node with data under // it and then get the values accordingly if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE) || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) { // there is no child to this node text = node.getNodeValue(); } else { // the data is in a child node text = node.getFirstChild().getNodeValue(); } list.add(attrFactory.createValue(attributeType, text)); } return new EvaluationResult(new BagAttribute(attributeType, list)); } catch (ParsingException pe) { ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); return new EvaluationResult(new Status(code, pe.getMessage())); } catch (UnknownIdentifierException uie) { ArrayList<String> code = new ArrayList<String>(); code.add(Status.STATUS_PROCESSING_ERROR); return new EvaluationResult(new Status(code, "Unknown attribute type : " + attributeType)); } }
/** Get an RDF organization from the given RDF file */ private RDFOrganization getOrganization(Document xmlDocument, NamedNodeMap attrs) { RDFOrganization organization = new RDFOrganization(); try { Node node = attrs.getNamedItem("rdf:resource"); String itemDoi = node.getNodeValue(); LOGGER.info("Processing item {}", itemDoi); // Get organization name String orgName = (String) xPath .compile(orgNameExpression.replace("%s", itemDoi)) .evaluate(xmlDocument, XPathConstants.STRING); // Get country code Node countryNode = (Node) xPath .compile(orgCountryExpression.replace("%s", itemDoi)) .evaluate(xmlDocument, XPathConstants.NODE); NamedNodeMap countryAttrs = countryNode.getAttributes(); String countryGeonameUrl = countryAttrs.getNamedItem("rdf:resource").getNodeValue(); String countryCode = fetchFromGeoNames(countryGeonameUrl, "countryCode"); // Get state name Node stateNode = (Node) xPath .compile(orgStateExpression.replace("%s", itemDoi)) .evaluate(xmlDocument, XPathConstants.NODE); String stateName = null; String stateCode = null; if (stateNode != null) { NamedNodeMap stateAttrs = stateNode.getAttributes(); String stateGeoNameCode = stateAttrs.getNamedItem("rdf:resource").getNodeValue(); stateName = fetchFromGeoNames(stateGeoNameCode, "name"); stateCode = fetchFromGeoNames(stateGeoNameCode, STATE_NAME); } // Get type String orgType = (String) xPath .compile(orgTypeExpression.replace("%s", itemDoi)) .evaluate(xmlDocument, XPathConstants.STRING); // Get subType String orgSubType = (String) xPath .compile(orgSubTypeExpression.replace("%s", itemDoi)) .evaluate(xmlDocument, XPathConstants.STRING); // Fill the organization object organization.doi = itemDoi; organization.name = orgName; organization.country = countryCode; organization.state = stateName; organization.stateCode = stateCode; // TODO: since we don't have city, we fill this with the state, this // should be modified soon organization.city = stateCode; organization.type = orgType; organization.subtype = orgSubType; } catch (XPathExpressionException xpe) { LOGGER.error("XPathExpressionException {}", xpe.getMessage()); } return organization; }