// Gets the specified XML Schema doc if one is mentioned in the file public static File getSchemaFile(Document xmlDoc) { /** @todo Must be an easier way of doing this... */ logger.logComment("Getting schema file for: " + xmlDoc.getDocumentURI()); NodeList nl = xmlDoc.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { Node node = nl.item(j); logger.logComment("Type: " + node.getNodeType() + "Name: " + node.getNodeName()); if (node.getNodeName().equals(XML_STYLESHEET_NODE)) { String nodeVal = node.getNodeValue(); logger.logComment("Looking at: " + nodeVal); String xslFileName = nodeVal.substring(nodeVal.indexOf("href=\"") + 6, nodeVal.length() - 1); File xslFile = new File(xslFileName); return xslFile; } if (node.getAttributes().getLength() > 0) { logger.logComment("Attributes: " + node.getAttributes()); if (node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR) != null) { String locString = node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR).getNodeValue(); logger.logComment("Loc string: " + locString); String file = locString.split("\\s")[1]; return new File(file); } } } logger.logError("No node found with name: " + XML_STYLESHEET_NODE); return null; }
/** * Constructor * * @param filename the XML config file */ public LdapConfig(String filename) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(filename); // -- root element Node node = document.getFirstChild(); while (node != null && node.getNodeType() != Node.ELEMENT_NODE) node = node.getNextSibling(); if (node == null || !node.getNodeName().equals("ldap")) throw new Exception("root element is different from 'ldap'"); this.ldapUrl = node.getAttributes().getNamedItem("url").getNodeValue(); node = node.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("authentication")) handleAuthentication(node); else if (node.getNodeName().equals("plugins")) handlePlugins(node); else if (node.getNodeName().equals("services")) handleServices(node); else if (node.getNodeName().equals("users")) handleUsers(node); else if (node.getNodeName().equals("groups")) handleGroups(node); else Logging.getLogger().warning("unexepected node : " + node.getNodeName()); } node = node.getNextSibling(); } }
private void processPanel(Session session, Element element, HashMap additionalInformation) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); }
public static void traverseAMLforObjectNames( HashMap partialMap, Node currentNode, HashMap ObjDef_LinkId, HashMap ModelId_ModelType) { if (currentNode.hasChildNodes()) { for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) { Node currentChild = currentNode.getChildNodes().item(i); if (currentChild.getNodeName().equals("Group")) { traverseAMLforObjectNames(partialMap, currentChild, ObjDef_LinkId, ModelId_ModelType); } if (currentChild.getNodeName().equals("Model")) { if (currentChild.hasAttributes()) { String mid = currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue(); String type = currentChild.getAttributes().getNamedItem("Model.Type").getNodeValue(); ModelId_ModelType.put(mid, type); } // traverseAMLforObjectNames(partialMap, currentChild, // ObjDef_LinkId); } if (currentChild.getNodeName().equals("ObjDef")) { String id = currentChild.getAttributes().getNamedItem("ObjDef.ID").getNodeValue(); NodeList currentChildren = currentChild.getChildNodes(); String ObjName = ""; for (int k = 0; k < currentChildren.getLength(); k++) { Node Child = currentChildren.item(k); if (!Child.getNodeName().equals("AttrDef")) { continue; } else if (!Child.getAttributes() .getNamedItem("AttrDef.Type") .getNodeValue() .equals("AT_NAME")) { continue; } else if (Child.hasChildNodes()) { for (int l = 0; l < Child.getChildNodes().getLength(); l++) { if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) { continue; } else { ObjName = getTextContent(Child.getChildNodes().item(l)); ObjName = ObjName.replaceAll("\n", "\\\\n"); break; } } } } partialMap.put(id, ObjName); for (int j = 0; j < currentChild.getAttributes().getLength(); j++) { if (currentChild.getAttributes().item(j).getNodeName().equals("LinkedModels.IdRefs")) { String links = currentChild.getAttributes().getNamedItem("LinkedModels.IdRefs").getNodeValue(); /* * if (links.indexOf(" ") > -1) { * Message.add("yes, yes, yes"); links = * links.substring(0, links.indexOf(" ")); } */ ObjDef_LinkId.put(id, links); } } } } } }
public ResultValue(Node node) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if (n.getNodeName().equals("class")) { matlabClass = n.getTextContent(); } if (n.getNodeName().equals("size")) { size = string2intList(n.getTextContent()); numdims = size.size(); numel = 1; for (int d : size) { numel *= d; } } if (n.getNodeName().equals("matrix")) { resultType = RESULT_TYPE.MATRIX; matrixResult = string2doubleList(n.getTextContent()); } if (n.getNodeName().equals("imagMatrix")) { isReal = false; resultType = RESULT_TYPE.MATRIX; imagMatrixResult = string2doubleList(n.getTextContent()); } if (n.getNodeName().equals("char")) { resultType = RESULT_TYPE.CHAR; charResult = n.getTextContent(); } if (n.getNodeName().equals("logical")) { resultType = RESULT_TYPE.LOGICAL; logicalResult = string2booleanList(n.getTextContent()); } if (n.getNodeName().equals("handle")) { resultType = RESULT_TYPE.HANDLE; } if (n.getNodeName().equals("struct")) { resultType = RESULT_TYPE.STRUCT; // create struct list for first occurence of struct if (structResult == null) { structResult = new ArrayList<HashMap<String, ResultValue>>(); } // build struct HashMap<String, ResultValue> struct = new HashMap<String, ResultValue>(); NodeList children = n.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { struct.put(child.getNodeName(), new ResultValue(child)); } } structResult.add(struct); } if (n.getNodeName().equals("cell")) { resultType = RESULT_TYPE.CELL; } } }
private void loadFromXml(String fileName) throws ParserConfigurationException, SAXException, IOException, ParseException { System.out.println("NeuralNetwork : loading network topology from file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(fileName); Node nodeNeuralNetwork = doc.getDocumentElement(); if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException( "[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.", 0); // nodeNeuralNetwork ok // indexNeuralNetworkContent -> indexStructureContent -> indexLayerContent -> indexNeuronContent // -> indexNeuralInputContent NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes(); for (int innc = 0; innc < nodeNeuralNetworkContent.getLength(); innc++) { Node nodeStructure = nodeNeuralNetworkContent.item(innc); if (nodeStructure.getNodeName().equals("structure")) { // for structure element NodeList nodeStructureContent = nodeStructure.getChildNodes(); for (int isc = 0; isc < nodeStructureContent.getLength(); isc++) { Node nodeLayer = nodeStructureContent.item(isc); if (nodeLayer.getNodeName().equals("layer")) { // for layer element NeuralLayer neuralLayer = new NeuralLayer(this); this.listLayers.add(neuralLayer); NodeList nodeLayerContent = nodeLayer.getChildNodes(); for (int ilc = 0; ilc < nodeLayerContent.getLength(); ilc++) { Node nodeNeuron = nodeLayerContent.item(ilc); if (nodeNeuron.getNodeName().equals("neuron")) { // for neuron in layer Neuron neuron = new Neuron( Double.parseDouble(((Element) nodeNeuron).getAttribute("threshold")), neuralLayer); neuralLayer.listNeurons.add(neuron); NodeList nodeNeuronContent = nodeNeuron.getChildNodes(); for (int inc = 0; inc < nodeNeuronContent.getLength(); inc++) { Node nodeNeuralInput = nodeNeuronContent.item(inc); // if (nodeNeuralInput==null) System.out.print("-"); else System.out.print("*"); if (nodeNeuralInput.getNodeName().equals("input")) { // System.out.println("neuron at // STR:"+innc+" LAY:"+isc+" NEU:"+ilc+" INP:"+inc); NeuralInput neuralInput = new NeuralInput( Double.parseDouble(((Element) nodeNeuralInput).getAttribute("weight")), neuron); neuron.listInputs.add(neuralInput); } } } } } } } } }
/** * Parse groups node * * @param node the groups node */ private void handleGroups(Node node) { this.groupsDn = node.getAttributes().getNamedItem("dn").getNodeValue(); node = node.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("attribute")) handleMapping(this.groupsAttributes, node); else if (node.getNodeName().equals("mapping")) handleMapping(this.groupsMapping, node); else Logging.getLogger().warning("unexepected node : " + node.getNodeName()); } node = node.getNextSibling(); } }
/** * This is just a helper function for the fromXML method. * * @param child */ public void importHelper(Node child) { if (child.getFirstChild() instanceof Text) { Text text = (Text) child.getFirstChild(); String data = text.getData(); if (child.getNodeName().equals("description")) { setDescription(data); } if (child.getNodeName().equals("refChildPattern")) { int decID = Integer.parseInt(data.substring(1)); subPatternsID.add(decID); } } }
/** * Examine the areaspec and determine the number and position of callouts. * * <p>The <code><a href="http://docbook.org/tdg/html/areaspec.html">areaspecNodeSet</a></code> is * examined and a sorted list of the callouts is constructed. * * <p>This data structure is used to augment the result tree fragment with callout bullets. * * @param areaspecNodeSet The source document <areaspec> element. */ public void setupCallouts(NodeList areaspecNodeList) { callout = new Callout[10]; calloutCount = 0; calloutPos = 0; lineNumber = 1; colNumber = 1; // First we walk through the areaspec to calculate the position // of the callouts // <areaspec> // <areaset id="ex.plco.const" coords=""> // <area id="ex.plco.c1" coords="4"/> // <area id="ex.plco.c2" coords="8"/> // </areaset> // <area id="ex.plco.ret" coords="12"/> // <area id="ex.plco.dest" coords="12"/> // </areaspec> int pos = 0; int coNum = 0; boolean inAreaSet = false; Node areaspec = areaspecNodeList.item(0); NodeList children = areaspec.getChildNodes(); for (int count = 0; count < children.getLength(); count++) { Node node = children.item(count); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equalsIgnoreCase("areaset")) { coNum++; NodeList areas = node.getChildNodes(); for (int acount = 0; acount < areas.getLength(); acount++) { Node area = areas.item(acount); if (area.getNodeType() == Node.ELEMENT_NODE) { if (area.getNodeName().equalsIgnoreCase("area")) { addCallout(coNum, area, defaultColumn); } else { System.out.println("Unexpected element in areaset: " + area.getNodeName()); } } } } else if (node.getNodeName().equalsIgnoreCase("area")) { coNum++; addCallout(coNum, node, defaultColumn); } else { System.out.println("Unexpected element in areaspec: " + node.getNodeName()); } } } // Now sort them java.util.Arrays.sort(callout, 0, calloutCount); }
/** Helper method to perform CTS, RTS handshake. */ private void performHandshake(Node sender, Node receiver) { ArrayList<Node> NodesInRange = receiver.getNodesInRange(); for (Node i : NodesInRange) { // For each node in receiver side if not the sender node if (!i.getNodeName().equals(sender.getNodeName())) { i.setWaiting(true); } } sender.setIdle(false); receiver.setIdle(false); sender.setSentRTS(true); receiver.setSentCTS(true); sender.setReceivedCTS(true); }
public AxisName(Node node, XmlQuery xq) throws WCPSException { while ((node != null) && node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) { node = node.getNextSibling(); } if (node != null && node.getNodeName().equals(WCPSConstants.MSG_AXIS)) { log.trace(node.getNodeName()); String axis = node.getTextContent(); this.name = axis; log.trace(" " + WCPSConstants.MSG_AXIS + " " + WCPSConstants.MSG_NAME + ": " + name); } else { throw new WCPSException( ExceptionCode.InvalidRequest, WCPSConstants.ERRTXT_COULD_NOT_FIND_AXIS + " !"); } }
static { try { URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC); InputStream stream = url.openStream(); if (stream == null) throw new IOException(); // strict parsing options DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); // parses configuration xml /*- * Warning: Felix is unable to import the com.sun.rowset.internal * package, meaning this can't use the XmlErrorHandler. This causes * a warning and a default handler to be attached. Otherwise this * should have: builder.setErrorHandler(new XmlErrorHandler()); */ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); // iterates over nodes, parsing contents Node root = doc.getChildNodes().item(1); NodeList categories = root.getChildNodes(); for (int i = 0; i < categories.getLength(); ++i) { Node node = categories.item(i); if (node.getNodeName().equals(NODE_DEFAULTS)) { parseDefaults(node.getChildNodes()); } else if (node.getNodeName().equals(NODE_LOCALES)) { parseLocales(node.getChildNodes()); } else { logger.warn("Unrecognized category: " + node.getNodeName()); } } } catch (IOException exc) { logger.error("Unable to load spell checker parameters", exc); } catch (SAXException exc) { logger.error("Unable to parse spell checker parameters", exc); } catch (ParserConfigurationException exc) { logger.error("Unable to parse spell checker parameters", exc); } }
public static final Map parseFrame(Node node) { NodeList bones = node.getChildNodes(); Map bone_infos = new HashMap(); for (int i = 0; i < bones.getLength(); i++) { Node bone = bones.item(i); if (bone.getNodeName().equals("transform")) { String name = bone.getAttributes().getNamedItem("name").getNodeValue(); float[] matrix = new float[16]; matrix[0 * 4 + 0] = getAttrFloat(bone, "m00"); matrix[0 * 4 + 1] = getAttrFloat(bone, "m01"); matrix[0 * 4 + 2] = getAttrFloat(bone, "m02"); matrix[0 * 4 + 3] = getAttrFloat(bone, "m03"); matrix[1 * 4 + 0] = getAttrFloat(bone, "m10"); matrix[1 * 4 + 1] = getAttrFloat(bone, "m11"); matrix[1 * 4 + 2] = getAttrFloat(bone, "m12"); matrix[1 * 4 + 3] = getAttrFloat(bone, "m13"); matrix[2 * 4 + 0] = getAttrFloat(bone, "m20"); matrix[2 * 4 + 1] = getAttrFloat(bone, "m21"); matrix[2 * 4 + 2] = getAttrFloat(bone, "m22"); matrix[2 * 4 + 3] = getAttrFloat(bone, "m23"); matrix[3 * 4 + 0] = getAttrFloat(bone, "m30"); matrix[3 * 4 + 1] = getAttrFloat(bone, "m31"); matrix[3 * 4 + 2] = getAttrFloat(bone, "m32"); matrix[3 * 4 + 3] = getAttrFloat(bone, "m33"); bone_infos.put(name, matrix); } } return bone_infos; }
static DivisionOperatorWorkspaceObject load(Node node) throws ProgramLoadingException { if (!node.getNodeName().equals("division")) throw new ProgramLoadingException(); DivisionOperatorWorkspaceObject obj = new DivisionOperatorWorkspaceObject(Workspace.getWorkspace()); Node lop = Workspace.getChildElementByName(node, "loperand"); Node rop = Workspace.getChildElementByName(node, "roperand"); if (lop != null) { Node lopNode = Workspace.getNthChildElement(lop, 0); if (lopNode != null) { WorkspaceObject lopObj = Workspace.dispatchLoad(lopNode); if (lopObj != null) { obj.leftSink.progCombine(lopObj); } } } if (rop != null) { Node ropNode = Workspace.getNthChildElement(rop, 0); if (ropNode != null) { WorkspaceObject ropObj = Workspace.dispatchLoad(ropNode); if (ropObj != null) { obj.rightSink.progCombine(ropObj); } } } return obj; }
private void extractMBeanPolicy(MBeanPolicyConfig pConfig, Node pMBeanNode) throws MalformedObjectNameException { NodeList params = pMBeanNode.getChildNodes(); String name = null; Set<String> readAttributes = new HashSet<String>(); Set<String> writeAttributes = new HashSet<String>(); Set<String> operations = new HashSet<String>(); for (int k = 0; k < params.getLength(); k++) { Node param = params.item(k); if (param.getNodeType() != Node.ELEMENT_NODE) { continue; } assertNodeName(param, "name", "attribute", "operation"); String tag = param.getNodeName(); if (tag.equals("name")) { if (name != null) { throw new SecurityException("<name> given twice as MBean name"); } else { name = param.getTextContent().trim(); } } else if (tag.equals("attribute")) { extractAttribute(readAttributes, writeAttributes, param); } else if (tag.equals("operation")) { operations.add(param.getTextContent().trim()); } else { throw new SecurityException("Tag <" + tag + "> invalid"); } } if (name == null) { throw new SecurityException("No <name> given for <mbean>"); } pConfig.addValues(new ObjectName(name), readAttributes, writeAttributes, operations); }
private void assertNodeName(Node pNode, String... pExpected) { for (String expected : pExpected) { if (pNode.getNodeName().equals(expected)) { return; } } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < pExpected.length; i++) { buffer.append(pExpected[i]); if (i < pExpected.length - 1) { buffer.append(","); } } throw new SecurityException( "Expected element " + buffer.toString() + " but got " + pNode.getNodeName()); }
private static Command parseCommand(Node n) { NamedNodeMap atts = n.getAttributes(); String name = atts.getNamedItem("name").getNodeValue(); String desc = atts.getNamedItem("description").getNodeValue(); String command = atts.getNamedItem("command").getNodeValue(); Command com = new Command(name, desc, command); NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (!child.getNodeName().equals("Argument")) continue; NamedNodeMap childAtts = child.getAttributes(); String childName = childAtts.getNamedItem("name").getNodeValue(); String childDesc = childAtts.getNamedItem("description").getNodeValue(); String childVal = ""; if (childAtts.getNamedItem("default") != null) childVal = childAtts.getNamedItem("default").getNodeValue(); Argument arg = new Argument(childName, childDesc, childVal); com.addArgument(arg); } return com; }
private void updateComputer( Node n, Map<String, Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) { Map<Node, Computer> computers = getComputerMap(); Computer c; c = byNameMap.get(n.getNodeName()); if (c != null) { c.setNode(n); // reuse } else { // we always need Computer for the master as a fallback in case there's no other Computer. if (n.getNumExecutors() > 0 || n == Jenkins.getInstance()) { computers.put(n, c = n.createComputer()); if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) { RetentionStrategy retentionStrategy = c.getRetentionStrategy(); if (retentionStrategy != null) { // if there is a retention strategy, it is responsible for deciding to start the // computer retentionStrategy.start(c); } else { // we should never get here, but just in case, we'll fall back to the legacy behaviour c.connect(true); } } } } used.add(c); }
private void guardaRes(String resu, CliGol cliGol) throws ParserConfigurationException, SAXException, IOException { String[] nodos = {"NoHit", "Hit", "Buro"}; DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(new StringReader(resu)); Document xml = db.parse(is); Element raiz = xml.getDocumentElement(); String nombre = obtenerNombre(raiz); for (String s : nodos) { Node nodo = raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0); if (nodo != null) { String informacion = sustraerInformacionNodo(cliGol, nodo); guardarEnListas(nodo.getNodeName(), nombre + "," + informacion); } } }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; NodeList elementList; Node employeeNode; Node childNode; NodeList childNodes; int nodeType; String childName; java.util.List actual = new java.util.ArrayList(); java.util.List expected = new java.util.ArrayList(); expected.add("em"); expected.add("strong"); expected.add("code"); expected.add("sup"); expected.add("var"); expected.add("acronym"); doc = (Document) load("hc_staff", false); elementList = doc.getElementsByTagName("p"); employeeNode = elementList.item(1); childNodes = employeeNode.getChildNodes(); for (int indexN1006C = 0; indexN1006C < childNodes.getLength(); indexN1006C++) { childNode = (Node) childNodes.item(indexN1006C); nodeType = (int) childNode.getNodeType(); childName = childNode.getNodeName(); if (equals(1, nodeType)) { actual.add(childName); } else { assertEquals("textNodeType", 3, nodeType); } } assertEqualsAutoCase("element", "elementNames", expected, actual); }
/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. */ public static void prettyPrint(Document doc, Node node) { // Get the text before the node and extract the indenting Node parent = node.getParentNode(); String indenting = ""; NodeList siblingList = parent.getChildNodes(); for (int i = 1; i < siblingList.getLength(); i++) { Node sibling = siblingList.item(i); if (sibling == node) { Node nodeBefore = siblingList.item(i - 1); // Check whether this is a text node if (nodeBefore.getNodeName().equals("#text")) { // There is text before the node -> Extract the indenting String text = nodeBefore.getNodeValue(); int newlinePos = text.lastIndexOf('\n'); if (newlinePos != -1) { indenting = text.substring(newlinePos); if (indenting.trim().length() != 0) { // The indenting is no whitespace -> Forget it indenting = ""; } } } break; } } // Now pretty print the node prettyPrint(doc, node, indenting); }
/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. * @param prefix The prefix the node should get. */ private static void prettyPrint(Document doc, Node node, String prefix) { String childPrefix = prefix + " "; // Add the indenting to the children NodeList childList = node.getChildNodes(); boolean hasChildren = false; for (int i = childList.getLength() - 1; i >= 0; i--) { Node child = childList.item(i); boolean isNormalNode = (!child.getNodeName().startsWith("#")); if (isNormalNode) { // Add the indenting to this node Node textNode = doc.createTextNode(childPrefix); node.insertBefore(textNode, child); // pretty print the child's children prettyPrint(doc, child, childPrefix); hasChildren = true; } } // Add the indenting to the end tag if (hasChildren) { Node textNode = doc.createTextNode(prefix); node.appendChild(textNode); } }
public XNode(XPathParser xpathParser, Node node) { this.xpathParser = xpathParser; this.node = node; this.name = node.getNodeName(); this.attributes = parseAttributes(node); this.body = parseBody(node); }
/** * Gets a child node from a parent node. If the parent node has no such child the child of the * <code>defaultNode</code> is used. * * @param node The node to get the child from. * @param defaultNode The node to get the child from if <code>node</code> has no such child. * @param childNodeName The name of the child. * @param mandatory Specifies whether to throw an exception if none of the nodes have such a * child. * @return The child with the given name. * @throws RegainException If both the <code>node</code> and the <code>defaultNode</code> have no * child with the given name and <code>mandatory</code> is <code>true</code>. */ public static Node getCascadedChild( Node node, Node defaultNode, String childNodeName, boolean mandatory) throws RegainException { Node child = getCascadedChild(node, defaultNode, childNodeName); if (mandatory && (child == null)) { throw new RegainException( "Node '" + node.getNodeName() + "' or node '" + defaultNode.getNodeName() + "' must have a child named '" + childNodeName + "'!"); } return child; }
public static String getAttr(Node node, String name) throws ESException { Attr attr = ((Element) node).getAttributeNode(name); if (attr == null) throw new ESException( "Attribute \"" + name + "\" not " + "found in \"" + node.getNodeName() + "\""); return attr.getNodeValue(); }
/** * Prints a XML node. * * @param out The PrintStream where to print the node. * @param prefix The prefix to put before every line. * @param node The node to print. * @throws IOException If printing failed. */ private static void printNode(PrintStream out, String prefix, Node node) throws IOException { prefix = ""; String name = node.getNodeName(); boolean isText = name.equals("#text"); boolean isComment = name.equals("#comment"); boolean isCDATA = name.equals("#cdata-section"); if (isText) { // This is a text tag String text = node.getNodeValue(); text = RegainToolkit.replace(text, "<", "<"); text = RegainToolkit.replace(text, ">", ">"); text = RegainToolkit.replace(text, "--", "−−"); out.print(text); } else if (isComment) { // This is a comment tag String comment = node.getNodeValue(); out.print("<!--" + comment + "-->"); } else if (isCDATA) { String text = node.getNodeValue(); out.print("<![CDATA[" + text + "]]>"); } else { // This is a normal tag out.print(prefix + "<" + name); if (node.hasAttributes()) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attrib = attributes.item(i); out.print(" " + attrib.getNodeName() + "=\"" + attrib.getNodeValue() + "\""); } } if (!node.hasChildNodes()) { out.print("/>"); } else { out.print(">"); NodeList childList = node.getChildNodes(); String childPrefix = prefix + " "; for (int i = 0; i < childList.getLength(); i++) { printNode(out, childPrefix, childList.item(i)); } out.print(prefix + "</" + name + ">"); } } }
public void testXML() throws Exception { QueryElement q1 = new QueryElement("a", "1"); Document doc = XML.createDocument(); Node root = q1.toXML(doc); assertEquals("queryElement", root.getNodeName()); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); if ("tokenRole".equals(child.getNodeName())) { assertEquals("a", XML.text(child)); } else if ("tokenValue".equals(child.getNodeName())) { assertEquals("1", XML.text(child)); } else fail("Unknown node \"" + child.getNodeName() + "\" in XML result"); } QueryElement q2 = new QueryElement(root); assertEquals(q1, q2); }
public XNode(XPathParser xpathParser, Node node, Properties variables) { this.xpathParser = xpathParser; this.node = node; this.name = node.getNodeName(); this.variables = variables; this.attributes = parseAttributes(node); this.body = parseBody(node); }
public FieldName(Node node, XmlQuery xq, CoverageInfo covInfo) throws WCPSException { while ((node != null) && node.getNodeName().equals("#" + WcpsConstants.MSG_TEXT)) { node = node.getNextSibling(); } if (node == null) { throw new WCPSException("FieldNameType parsing error."); } String nodeName = node.getNodeName(); log.trace(nodeName); if (nodeName.equals(WcpsConstants.MSG_NAME)) { this.name = node.getTextContent(); log.trace("Found field name: " + name); String coverageName = covInfo.getCoverageName(); try { covMeta = xq.getMetadataSource().read(coverageName); } catch (Exception ex) { log.error(ex.getMessage()); throw new WCPSException(ex.getMessage(), ex); } try { nameIndex = covMeta.getRangeIndexByName(name).toString(); } catch (PetascopeException ex1) { boolean wrongFieldSubset = true; log.debug("Range field subset " + name + " does not seem by-label: trying by-index."); if (MiscUtil.isInteger(name)) { try { // range subsetting might have been done via range field /index/ (instead of label): // check this is a valid index nameIndex = name; name = covMeta.getRangeNameByIndex(Integer.parseInt(name)); wrongFieldSubset = false; // indeed subset was by-index } catch (PetascopeException ex2) { log.debug("Range field subset " + nameIndex + " is neither a valid index."); } } if (wrongFieldSubset) { log.error("Illegal range field selection: " + name); throw new WCPSException(ex1.getExceptionCode(), ex1.getExceptionText()); } } } }
/** * Extrahiert den Text eines Knotens, wandelt ihn in ein int und gibt das Ergebnis zurück. * * @param node Der Knoten, dessen Text zurückgeben werden soll. * @return Der Text des Knotens als int. * @throws RegainException Falls der Knoten keinen Text hat oder falls der Text keine Ganzzahl * ist. */ public static int getTextAsInt(Node node) throws RegainException { String asString = getText(node, true, true); try { return Integer.parseInt(asString); } catch (NumberFormatException exc) { throw new RegainException( "Value of node '" + node.getNodeName() + "' must be an integer: '" + asString + "'", exc); } }