/** * Process the xmlfile named <code>fileName</code> with the given system * ID. * * @param fileName * meta data file name. * @param systemId * system ID. */ protected void processFile(String fileName, String systemId) throws ValidationException, ParserConfigurationException, SAXException, IOException, SchedulerException, ClassNotFoundException, ParseException, XPathException { prepForProcessing(); log.info("Parsing XML file: " + fileName + " with systemId: " + systemId); InputSource is = new InputSource(getInputStream(fileName)); is.setSystemId(systemId); process(is); maybeThrowValidationException(); }
/** * Process the xmlfile named <code>fileName</code> with the given system * ID. * * @param stream * an input stream containing the xml content. * @param systemId * system ID. */ public void processStreamAndScheduleJobs(InputStream stream, String systemId, Scheduler sched) throws ValidationException, ParserConfigurationException, SAXException, XPathException, IOException, SchedulerException, ClassNotFoundException, ParseException { prepForProcessing(); log.info("Parsing XML from stream with systemId: " + systemId); InputSource is = new InputSource(stream); is.setSystemId(systemId); process(is); executePreProcessCommands(sched); scheduleJobs(sched); maybeThrowValidationException(); }
/** * Create a new HttpPidMinter. * @param url The URL for the minter service. This is the only required argument -- all * other parameters can be blank. * @param method The HTTP method (POST, PUT or GET) used to generate a new PID (POST will * be used if the method is blank. * @param username If not blank, use this username to connect to the minter service. * @param password If not blank, use this password used to connect to the minter service. * @param regex If not blank, use this regular expression used to remove unwanted text from the * minter service response. For example, if the response text is "/foo/bar:baz" and the * desired identifier is "baz", then the regex would be ".*:". * @param xpath If not blank, use this XPath expression used to extract the desired identifier * from an XML minter response. **/ public HttpPidMinter( final String url, final String method, final String username, final String password, final String regex, final String xpath ) { if (isBlank(url)) { throw new IllegalArgumentException("Minter URL must be specified!"); } this.url = url; this.method = (method == null ? "post" : method); this.username = username; this.password = password; this.regex = regex; if ( !isBlank(xpath) ) { try { this.xpath = XPathFactory.newInstance().newXPath().compile(xpath); } catch ( final XPathException ex ) { LOGGER.warn("Error parsing xpath ({}): {}", xpath, ex.getMessage()); throw new IllegalArgumentException("Error parsing xpath" + xpath, ex); } } this.client = buildClient(); }
public void testMarshal() throws JAXBException, XPathException { final PurchaseOrderType purchaseOrder = objectFactory .createPurchaseOrderType(); purchaseOrder.setShipTo(objectFactory.createUSAddress()); purchaseOrder.getShipTo().setCity("New Orleans"); final JAXBElement<PurchaseOrderType> purchaseOrderElement = objectFactory .createPurchaseOrder(purchaseOrder); final Marshaller marshaller = context.createMarshaller(); final DOMResult result = new DOMResult(); marshaller.marshal(purchaseOrderElement, result); final XPathFactory xPathFactory = XPathFactory.newInstance(); assertEquals("Wrong city", "New Orleans", xPathFactory.newXPath() .evaluate("/purchaseOrder/shipTo/city", result.getNode())); }
@Override public void filter(Document document) throws XPathException { Object result = xPathExpression.evaluate(document, XPathConstants.NODESET); if(result != null) { NodeList nodeList = (NodeList)result; for(int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); anonymize(item); } } else { // do nothing } }
public static final Element getOptionalElement(Element root, String xpath) throws MultipleMatchesException, NestedXPathException { try { XPathExpression expr = null; if ((expr = ParserHelper.compiledMap.get(xpath)) == null) { expr = getXPathFactory().newXPath().compile(xpath); ParserHelper.compiledMap.put(xpath, expr); } // I use a NodeList here instead of an Element because I want to ensure // there are not multiple return values NodeList nl = (NodeList) expr.evaluate(root, XPathConstants.NODESET); if (nl.getLength() > 1) { throw new MultipleMatchesException(xpath); } // TODO: Ensure the return value is an Element? return (Element) nl.item(0); } catch (XPathException e) { throw new NestedXPathException(e); } }
public final ArrayList<String> getListOfRecipes() { ArrayList<String> nameList = new ArrayList<>(); XPath xp; try { xp = XPathFactory.newInstance().newXPath(); NodeList recipeList = (NodeList) xp.evaluate( "/RECIPES/RECIPE", recipeDocument, XPathConstants.NODESET); if (recipeList.getLength() == 0) { LaunchControl.setMessage("No Recipes found in file"); return null; } for (int i = 0; i < recipeList.getLength(); i++) { Node recipeNode = recipeList.item(i); String recipeName = (String) xp.evaluate("NAME/text()", recipeNode, XPathConstants.STRING); nameList.add(recipeName); } } catch (XPathException xpe) { BrewServer.LOG.warning("Couldn't run XPATH: " + xpe.getMessage()); return null; } return nameList; }
/** * Starts the merge process * * @param mainDoc The document to edit. * @param mergeDoc The document containing the edit instructions. * @throws XPathException A problem parsing the XPath location. */ protected void applyMerge(Document mainDoc, Document mergeDoc) throws XPathException { NodeList mergeActions = handler.getNodeList(mergeDoc, BASE_XPATH_EXPR); for (int i = 0; i < mergeActions.getLength(); i++) { Node node = mergeActions.item(i); // get the attribute map and action information NamedNodeMap attrMap = node.getAttributes(); String type = attrMap.getNamedItem(ATTR_TYPE).getNodeValue(); String action = attrMap.getNamedItem(ATTR_ACTION).getNodeValue(); String xpath = attrMap.getNamedItem(ATTR_XPATH).getNodeValue(); NodeList actionArgs = node.getChildNodes(); // perform the transform performTransform(mainDoc, type, action, xpath, actionArgs); } }
/** * Performs the transform on the given document with the xpath and node list * * @param doc Base document to edit. * @param type The type of element to edit (attribute or node). * @param action The action (add, delete, set) to perform. * @param xpath The XPath location to perform the edit. * @param mergeNodeList Action arguments. Nodes to add, attributes to set, etc. * @throws XPathException A problem parsing the XPath location. */ protected void performTransform(Document doc, String type, String action, String xpath, NodeList mergeNodeList) throws XPathException { NodeList editNodes = handler.getNodeList(doc, xpath); for (int i = 0; i < editNodes.getLength(); i++) { Node crntEditNode = editNodes.item(i); if (TYPE_ATTRIBUTE.equals(type)) { if (ACTION_ADD.equals(action) || ACTION_SET.equals(action)) { attributeSet(crntEditNode, mergeNodeList); } else if (ACTION_DELETE.equals(action)) { attributeDelete(crntEditNode, mergeNodeList); } } else if (TYPE_NODE.equals(type)) { if (ACTION_ADD.equals(action)) { nodeAdd(crntEditNode, mergeNodeList); } else if (ACTION_DELETE.equals(action)) { nodeDelete(crntEditNode); } } } }
@Override public NodeList asNodeList() { try { return (NodeList) this.xPathExpression.evaluate(this.baseNode, XPathConstants.NODESET); } catch (XPathException ex) { throw new FluentXmlProcessingException(ex); } }
/** * Cleans the XML file. * 1) Updates formatting and indentation. * 2) Removes liquibase "objectQuotingStrategy" attributes. * * @param file The changelog file. */ private static void cleanXmlFile(final File file) throws IOException { try { final Document doc = readXml(file); final XPath xpath = XPathFactory.newInstance().newXPath(); removeNodes(doc, xpath, "//@objectQuotingStrategy"); removeNodes(doc, xpath, "//text()[normalize-space()='']"); writeXml(doc, file); } catch (final XPathException ex) { throw new IOException(ex.getMessage(), ex); } }
static byte [] pickleXPE(XPathException xpe) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream xpeos = new ObjectOutputStream(bos); xpeos.writeObject(xpe); xpeos.close(); return bos.toByteArray(); }
@Override public Node get(int index) throws XPathException { if (index <0 || index >= size()) { throw new IndexOutOfBoundsException("Index " + index + " is out of bounds"); } if (nodeList != null) { return nodeList.item(index); } return null; }
public ClusterDefinitionLoader() { try { XPath xPath = XPathFactory.newInstance().newXPath(); clustersExpression = xPath.compile("//clusters/cluster"); nameExpression = xPath.compile("./name/text()"); subExpression = xPath.compile("./sub/text()"); centerXExpression = xPath.compile("./x/text()"); centerYExpression = xPath.compile("./y/text()"); colorExpression = xPath.compile("./color/text()"); } catch(XPathException e) { throw new DefinitionLoaderException("Could not parse configuration", e); } }
private List<Node> getClusterNodes(InputStream configurationStream) throws ParserConfigurationException, SAXException, IOException, XPathException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(configurationStream); doc.getDocumentElement().normalize(); NodeList clusterNodes = (NodeList) clustersExpression.evaluate(doc.getDocumentElement(), XPathConstants.NODESET); List<Node> nodes = Lists.newArrayList(); for(int i = 0; i < clusterNodes.getLength(); ++i) { nodes.add(clusterNodes.item(i)); } return nodes; }
private List<String> parseSub(Node genreNode) throws XPathException { List<String> l = Lists.newArrayList(subExpression.evaluate(genreNode).split(",", -1)); // return null if it would otherwise be an array with one element, the empty string if (l.size() == 1 && l.get(0).equals("")) return null; else return Lists.newArrayList(subExpression.evaluate(genreNode).split(",", -1)); }
public void sniff(Event event, InputSource source, boolean useSTAX) throws XPathException{ XMLReader reader; try{ if(useSTAX) reader = new STAXXMLReader(); else reader = SAXUtil.newSAXFactory(true, false, false).newSAXParser().getXMLReader(); sniff(event, source, reader); }catch(Exception ex){ throw new XPathException(ex); } }
public XPathResults sniff(InputSource source, boolean useSTAX) throws XPathException{ Event event = createEvent(); XPathResults results = new XPathResults(event); event.setListener(results); sniff(event, source, useSTAX); return results; }
public XPathResults sniff(InputSource source) throws XPathException{ Event event = createEvent(); XPathResults results = new XPathResults(event); event.setListener(results); sniff(event, source); return results; }
/** * Compile expression. * @param expr The expression. * @return The XPath expression. */ private static XPathExpression compileExpression(String expr) { try { return XPATH.compile(expr); } catch (XPathException e) { throw new CosmoXPathException("Unable to compile expression '" + expr + "'", e); } }
/** * Finds nodes. * @param expr The XPath Expression. * @param context The context object. * @return The node list. * @throws ParserException - if something is wrong this exception is thrown. */ private static NodeList findNodes(XPathExpression expr, Object context) throws ParserException { try { return (NodeList) expr.evaluate(context, XPathConstants.NODESET); } catch (XPathException e) { throw new ParserException("Unable to find nodes", -1, e); } }
/** * Finds nodes. * @param expr The XPath expression. * @param context The context object. * @return The node. * @throws ParserException - if something is wrong this exception is thrown. */ private static Node findNode(XPathExpression expr, Object context) throws ParserException { try { return (Node) expr.evaluate(context, XPathConstants.NODE); } catch (XPathException e) { throw new ParserException("Unable to find node", -1, e); } }
/** * Returns the first child of the parent {@link Node} with the given name, or <code>null</code> if such child is not * found. * * @param root The root node. * @param childName Name of the child node. * @return {@link Node} if a child node was found, <code>null</code> otherwise. */ public static Node getFirstChildByName(Node root, String childName) { Node node = null; try { node = getNodeByXPath(root, "/" + childName); } catch (XPathException e) { // Did not get any node } return node; }
@Override public void filter(Document document) throws XPathException { Object result = xPathExpression.evaluate(document, XPathConstants.NODESET); if(result != null) { NodeList results = (NodeList)result; for(int i = 0; i < results.getLength(); i++) { Node item = results.item(i); switch(item.getNodeType()) { case Node.ELEMENT_NODE : { Element element = (Element)item; NodeList childNodes = element.getChildNodes(); // node list is updated while(childNodes.getLength() > 0) { element.removeChild(childNodes.item(0)); } Comment comment = document.createComment(" [SUBTREE REMOVED] "); element.appendChild(comment); } } } } else { // do nothing } }
public List<String> getAttributeList(String path, String attribute) throws XPathException { NodeList nodeList = getNodeList(path); List<String> res = new ArrayList<>(nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); res.add(getAttribute(node, attribute)); } return res; }
/** * Write stub values for IDs to values.xml to match those available in public.xml. */ private void createStubIds(File values, Map<File, String> rewritten, File publicXml) throws IOException, ParserConfigurationException, SAXException { if (values.exists()) { String xml = rewritten.get(values); if (xml == null) { xml = Files.toString(values, UTF_8); } List<String> stubbed = Lists.newArrayList(); Document document = XmlUtils.parseDocument(xml, true); Element root = document.getDocumentElement(); for (Resource resource : model.getResources()) { boolean inPublicXml = resource.declarations != null && resource.declarations.contains(publicXml); NodeList existing = null; try { XPathExpression expr = XPathFactory.newInstance().newXPath().compile( String.format("//item[@type=\"id\"][@name=\"%s\"]", resource.name)); existing = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathException e) { // Failed to retrieve any existing declarations for resource. } if (resource.type == ResourceType.ID && inPublicXml && (existing == null || existing.getLength() == 0)) { Element item = document.createElement(TAG_ITEM); item.setAttribute(ATTR_TYPE, resource.type.getName()); item.setAttribute(ATTR_NAME, resource.name); root.appendChild(item); stubbed.add(resource.getUrl()); } } logger.fine("Created " + stubbed.size() + " stub IDs for:\n " + Joiner.on(", ").join(stubbed)); String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n")); rewritten.put(values, formatted); } }
static List<SupportedFormat> parseSupportedFormats(Document doc) { List<SupportedFormat> formats = new ArrayList<>(); try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//supportedMetadataFormats/format"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node formatNode = nodes.item(i); String tag = xpath.evaluate("@tag", formatNode); NodeList detectors = (NodeList) xpath.evaluate("detector", formatNode, XPathConstants.NODESET); if (detectors.getLength() != 1) { throw new EditorException(String.format("found %d detectors, need exactly 1 for format %s", detectors.getLength(), tag), EditorException.SETUP_XML_ERROR); } String detectorType = xpath.evaluate("@type", detectors.item(0)); if (!"rootNode".equals(detectorType)) { throw new EditorException(String.format( "found detector-type '%s' for format '%s', currently only 'rootNode' allowed in %s", detectorType, tag), EditorException.SETUP_XML_ERROR); } String rootNode = xpath.evaluate("arg[@name='rootNode']/@value", detectors.item(0)); String namespace = xpath.evaluate("arg[@name='namespace']/@value", detectors.item(0)); ValidationClient validationClient = parseValidationPart(formatNode, xpath); formats.add(new SupportedFormat(tag, rootNode, namespace, validationClient)); } } catch (XPathException e) { Logger.getLogger(DataStoreImpl.class.getName()).log(Level.SEVERE, null, e); } return formats; }
public Recipe[] readRecipe(Document beerDocument, String name) throws XPathException { String recipeSelector = ""; if (name != null) { recipeSelector = "[NAME[text()=\"" + name + "\"]]"; } XPath xp = XPathFactory.newInstance().newXPath(); NodeList recipeData = (NodeList) xp.evaluate( "/RECIPES/RECIPE" + recipeSelector, beerDocument, XPathConstants.NODESET); Recipe recipeList[] = new Recipe[recipeData.getLength()]; for (int i = 0; i < recipeData.getLength(); i++) { try { recipeList[i] = readSingleRecipe(recipeData.item(i)); } catch (XPathException xpe) { BrewServer.LOG.warning("Couldn't read the recipe at index " + i + " - " + xpe.getMessage()); xpe.printStackTrace(); } catch (NumberFormatException nfe) { BrewServer.LOG.warning("Couldn't read the recipe at index " + i + " due to a bad number " + nfe.getMessage()); nfe.printStackTrace(); } } return recipeList; }
/** * Add a mash Profile to a recipe. * @param recipe The @{Recipe} object to add the mash profile to. * @param mashProfile The node containing the beerXML Mash element. * @param xp an XPath object to use to run XPath expressions. * @throws XPathException If an XPath expression could not be run. */ private void parseMashProfile(Recipe recipe, Node mashProfile, XPath xp) throws XPathException { String name = getString(mashProfile, "NAME", xp); double grainTemp = getDouble(mashProfile, "GRAIN_TEMP", xp); Node mashSteps = (Node) xp.evaluate("MASH_STEPS", mashProfile, XPathConstants.NODE); String notes = getString(mashProfile, "NOTES", xp); double tunTemp = getDouble(mashProfile, "TUN_TEMP", xp); double spargeTemp = getDouble(mashProfile, "SPARGE_TEMP", xp); double ph = getDouble(mashProfile, "PH", xp); double tunWeight = getDouble(mashProfile, "TUN_WEIGHT", xp); double tunSpecificHeat = getDouble(mashProfile, "TUN_SPECIFIC_HEAT", xp); boolean tunAdjust = getBoolean(mashProfile, "TUN_ADJUST", xp, false); Mash mash = recipe.getMash(); if (mash == null) { mash = new Mash(name, recipe); recipe.setMash(mash); } else { mash.setName(name); } mash.setGrainTemp(grainTemp); mash.setNotes(notes); mash.setTunTemp(tunTemp); mash.setSpargeTemp(spargeTemp); mash.setPh(ph); mash.setTunWeight(tunWeight); mash.setTunSpecificHeat(tunSpecificHeat); mash.setTunAdjust(tunAdjust); mash.setTunWeight(getString(mashProfile, "DISPLAY_TUN_WEIGHT", xp)); mash.setMashTempUnits(getString(mashProfile, "DISPLAY_GRAIN_TEMP", xp)); parseMashSteps(mash, mashSteps, xp); }