protected Element copyElementToName(Element element, String tagName) { Element newElement = element.getOwnerDocument().createElement(tagName); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attribute = attrs.item(i); newElement.setAttribute(attribute.getNodeName(), attribute.getNodeValue()); } for (int i = 0; i < element.getChildNodes().getLength(); i++) { newElement.appendChild(element.getChildNodes().item(i).cloneNode(true)); } return newElement; }
private void processFilter(Session session, Element element, HashMap additionalInformation) { String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText()); String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText()); String filterName = getAttribute(element, SessionAttribute.NAME.getText()); TrackFilter filter = new TrackFilter(filterName, null); additionalInformation.put(SessionElement.FILTER, filter); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); // Save the filter session.setFilter(filter); // Set filter properties if ("all".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(true); } else if ("any".equalsIgnoreCase(match)) { IGV.getInstance().setFilterMatchAll(false); } if ("true".equalsIgnoreCase(showAllTracks)) { IGV.getInstance().setFilterShowAllTracks(true); } else { IGV.getInstance().setFilterShowAllTracks(false); } }
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 Element[] filterChildElements(Element parent, String ns, String lname) { /* way too noisy if (LOGGER.isDebugEnabled()) { StringBuilder buf = new StringBuilder(100); buf.append("XmlaUtil.filterChildElements: "); buf.append(" ns=\""); buf.append(ns); buf.append("\", lname=\""); buf.append(lname); buf.append("\""); LOGGER.debug(buf.toString()); } */ List<Element> elems = new ArrayList<Element>(); NodeList nlst = parent.getChildNodes(); for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) { Node n = nlst.item(i); if (n instanceof Element) { Element e = (Element) n; if ((ns == null || ns.equals(e.getNamespaceURI())) && (lname == null || lname.equals(e.getLocalName()))) { elems.add(e); } } } return elems.toArray(new Element[elems.size()]); }
public IXArchElement cloneElement(int depth) { synchronized (DOMUtils.getDOMLock(elt)) { Document doc = elt.getOwnerDocument(); if (depth == 0) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } else if (depth == 1) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); NodeList nl = elt.getChildNodes(); int size = nl.getLength(); for (int i = 0; i < size; i++) { Node n = nl.item(i); Node cloneNode = (Node) n.cloneNode(false); cloneNode = doc.importNode(cloneNode, true); cloneElt.appendChild(cloneNode); } return cloneImpl; } else /* depth = infinity */ { Element cloneElt = (Element) elt.cloneNode(true); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } } }
private void processColorScale(Session session, Element element, HashMap additionalInformation) { String trackType = getAttribute(element, SessionAttribute.TYPE.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); setColorScaleSet(session, trackType, value); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); }
/** @deprecated use allText(Element elem, boolean trim) */ public static String allTextFromElement(Element elem, boolean trim) throws DOMException { StringBuffer textBuf = new StringBuffer(); NodeList nl = elem.getChildNodes(); for (int j = 0, len = nl.getLength(); j < len; ++j) { Node node = nl.item(j); if (node instanceof Text) // includes Text and CDATA! textBuf.append(node.getNodeValue()); } String out = textBuf.toString(); return (trim ? out.trim() : out); }
private void processPreferences(Session session, Element element, HashMap additionalInformation) { NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node child = elements.item(i); if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) { Element childNode = (Element) child; String name = getAttribute(childNode, SessionAttribute.NAME.getText()); String value = getAttribute(childNode, SessionAttribute.VALUE.getText()); session.setPreference(name, value); } } }
public static String textInElement(Element elem) { StringBuilder buf = new StringBuilder(100); elem.normalize(); NodeList nlst = elem.getChildNodes(); for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) { Node n = nlst.item(i); if (n instanceof Text) { final String data = ((Text) n).getData(); buf.append(data); } } return buf.toString(); }
private void processRegion(Session session, Element element, HashMap additionalInformation) { String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText()); String start = getAttribute(element, SessionAttribute.START_INDEX.getText()); String end = getAttribute(element, SessionAttribute.END_INDEX.getText()); String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText()); RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description); IGV.getInstance().addRegionOfInterest(region); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); }
@Test public void testNodeValueOnTextNode() throws Exception { String xml = "<?xml version=\"1.0\"?>" + "<root>" + " <property>Hello World</property>" + "</root>"; // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(Utils.createInputSource(xml)); Element root = doc.getDocumentElement(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element elem = (Element) node; Node textNode = elem.getChildNodes().item(0); Assert.assertEquals( "Text.getNodeValue", textNode.getNodeValue(), textNode.getTextContent()); return; } } Assert.assertEquals("Text.getNodeValue", true, false); }
/** * Searches the children of an element looking for a Text node. If it finds one, it returns it. * * @param element The element whose children will be searched * @return The text for the element, or null if there is none */ public static String getElementString(Element element) { NodeList nodes = element.getChildNodes(); int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); if (node instanceof Text) { return ((Text) node).getData(); } } return null; }
public void validateContent(IProgressMonitor monitor) { Element element = getDocumentRoot(); if (element == null) return; String elementName = element.getNodeName(); if (!"plugin".equals(elementName) && !"fragment".equals(elementName)) { // $NON-NLS-1$ //$NON-NLS-2$ reportIllegalElement(element, CompilerFlags.ERROR); } else { int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED); if (severity != CompilerFlags.IGNORE) { NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { reportUnusedAttribute(element, attrs.item(i).getNodeName(), severity); } } NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if (monitor.isCanceled()) break; Element child = (Element) children.item(i); String name = child.getNodeName(); if (name.equals("extension")) { // $NON-NLS-1$ validateExtension(child); } else if (name.equals("extension-point")) { // $NON-NLS-1$ validateExtensionPoint(child); } else { if (!name.equals("runtime") && !name.equals("requires")) { // $NON-NLS-1$ //$NON-NLS-2$ severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); if (severity != CompilerFlags.IGNORE) reportIllegalElement(child, severity); } else { severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED); if (severity != CompilerFlags.IGNORE) reportUnusedElement(child, severity); } } } IExtensions extensions = fModel.getExtensions(); if (extensions != null && extensions.getExtensions().length == 0 && extensions.getExtensionPoints().length == 0) report( MDECoreMessages.Builders_Manifest_useless_file, -1, IMarker.SEVERITY_WARNING, MDEMarkerFactory.P_USELESS_FILE, MDEMarkerFactory.CAT_OTHER); } }
private void processHiddenAttributes( Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> attributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) { attributes.add( ((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } session.setHiddenAttributes(attributes); } }
protected static XmlConfigurator parse(Element root_element) throws java.io.IOException { XmlConfigurator configurator = null; final LinkedList<ProtocolConfiguration> prot_data = new LinkedList<ProtocolConfiguration>(); /** * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty * amateurish... But it seems to work, and it is executed only on startup, so no perf loss on * the critical path. If somebody wants to improve this, please be my guest. */ try { String root_name = root_element.getNodeName(); if (!"config".equals(root_name.trim().toLowerCase())) throw new IOException("the configuration does not start with a <config> element"); NodeList prots = root_element.getChildNodes(); for (int i = 0; i < prots.getLength(); i++) { Node node = prots.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element tag = (Element) node; String protocol = tag.getTagName(); Map<String, String> params = new HashMap<String, String>(); NamedNodeMap attrs = tag.getAttributes(); int attrLength = attrs.getLength(); for (int a = 0; a < attrLength; a++) { Attr attr = (Attr) attrs.item(a); String name = attr.getName(); String value = attr.getValue(); params.put(name, value); } ProtocolConfiguration cfg = new ProtocolConfiguration(protocol, params); prot_data.add(cfg); } configurator = new XmlConfigurator(prot_data); } catch (Exception x) { if (x instanceof java.io.IOException) throw (java.io.IOException) x; else { IOException tmp = new IOException(); tmp.initCause(x); throw tmp; } } return configurator; }
/** extracts XML from PDF */ protected byte[] getXMLFromPDF(PdfReader reader) throws Exception { XfaForm xfaForm = reader.getAcroFields().getXfa(); Node domDocument = xfaForm.getDomDocument(); if (domDocument == null) return null; Element documentElement = ((Document) domDocument).getDocumentElement(); Element datasetsElement = (Element) documentElement.getElementsByTagNameNS(XFA_NS, "datasets").item(0); Element dataElement = (Element) datasetsElement.getElementsByTagNameNS(XFA_NS, "data").item(0); Element xmlElement = (Element) dataElement.getChildNodes().item(0); Node budgetElement = getBudgetElement(xmlElement); byte[] serializedXML = XfaForm.serializeDoc(budgetElement); return serializedXML; }
@Test public void testgetAttributesWithNamedNodeMap() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml"); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(f); Element root = doc.getDocumentElement(); // System.out.println("* current impl: " + doc.getClass().getName()); // id, class Map<String, String> actualMap = new HashMap<String, String>(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element elem = (Element) node; if (elem.getTagName().equals("beans:bean")) { // System.out.println("bean[" + elem.getAttribute("id") + "]"); NamedNodeMap map = elem.getAttributes(); String valueId = null; String valueClass = null; for (int x = 0; x < map.getLength(); x++) { Node attr = map.item(x); if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue(); if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue(); } if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass); } } } Map<String, String> expected = new HashMap<String, String>(); expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager"); expected.put( "daoAuthenticationProvider", "org.springframework.security.providers.dao.DaoAuthenticationProvider"); expected.put( "loggerListener", "org.springframework.security.event.authentication.LoggerListener"); Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap); }
JdbcIndexDefinition( DataSource ds, Element element, Set allIndexedFields, boolean storeText, boolean mergeText, Analyzer a, boolean isSub) { this.dataSource = ds; indexSql = element.getAttribute("sql"); key = element.getAttribute("key"); String elementId = element.getAttribute("identifier"); identifier = "".equals(elementId) ? key : elementId; findSql = element.getAttribute("find"); NodeList childNodes = element.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { if (childNodes.item(k) instanceof Element) { Element childElement = (Element) childNodes.item(k); if ("field".equals(childElement.getLocalName())) { if (childElement.getAttribute("keyword").equals("true")) { keyWords.add(childElement.getAttribute("name")); } String m = childElement.getAttribute("multiple"); if ("".equals(m)) m = "add"; if (!m.equals("add")) { nonDefaultMultiples.put( childElement.getAttribute("name"), Indexer.Multiple.valueOf(m.toUpperCase())); } String b = childElement.getAttribute("boost"); if (!b.equals("")) { boosts.put(childElement.getAttribute("name"), Float.valueOf(b)); } } else if ("related".equals(childElement.getLocalName())) { subQueries.add( new JdbcIndexDefinition( ds, childElement, allIndexedFields, storeText, mergeText, a, true)); } } } this.analyzer = a; this.isSub = isSub; assert !isSub || "".equals(findSql); }
private void processFrames(Element element) { NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Map<String, ReferenceFrame> frames = new HashMap(); for (ReferenceFrame f : FrameManager.getFrames()) { frames.put(f.getName(), f); } List<ReferenceFrame> reorderedFrames = new ArrayList(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) { String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText()); ReferenceFrame f = frames.get(frameName); if (f != null) { reorderedFrames.add(f); try { String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText()); final String startString = getAttribute((Element) childNode, SessionAttribute.START.getText()) .replace(",", ""); final String endString = getAttribute((Element) childNode, SessionAttribute.END.getText()) .replace(",", ""); int start = ParsingUtils.parseInt(startString); int end = ParsingUtils.parseInt(endString); org.broad.igv.feature.Locus locus = new Locus(chr, start, end); f.jumpTo(locus); } catch (NumberFormatException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } } } } if (reorderedFrames.size() > 0) { FrameManager.setFrames(reorderedFrames); } } IGV.getInstance().resetFrames(); }
/** * This interface method is called to set all the fieldValues of this object of <code>InPort * </code>, using the specified XML string. * * @param port The new fieldValues value * @exception FioranoException if an error occurs while parsing the XMLString * @since Tifosi2.0 */ public void setFieldValues(Element port) throws FioranoException { // Document doc = XMLUtils.getDOMDocumentFromXML(xmlString); // Element port = doc.getDocumentElement(); if (port != null) { m_bIsSyncRequestType = XMLDmiUtil.getAttributeAsBoolean(port, "isSyncRequestType"); NodeList children = port.getChildNodes(); Node child = null; for (int i = 0; children != null && i < children.getLength(); ++i) { child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase("Name")) { m_strPortName = XMLUtils.getNodeValueAsString(child).toUpperCase(); } if (nodeName.equalsIgnoreCase("Description")) { m_strDscription = XMLUtils.getNodeValueAsString(child); } if (nodeName.equalsIgnoreCase("XSD")) { m_strXSD = XMLUtils.getNodeValueAsString(child); } if (nodeName.equalsIgnoreCase("JavaClass")) { m_strJavaClass = XMLUtils.getNodeValueAsString(child); } if (nodeName.equalsIgnoreCase("Param")) { Param paramDmi = new Param(); paramDmi.setFieldValues((Element) child); addParam(paramDmi); } } } validate(); }
private void processFilterElement( Session session, Element element, HashMap additionalInformation) { TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER); String item = getAttribute(element, SessionAttribute.ITEM.getText()); String operator = getAttribute(element, SessionAttribute.OPERATOR.getText()); String value = getAttribute(element, SessionAttribute.VALUE.getText()); String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText()); TrackFilterElement trackFilterElement = new TrackFilterElement( filter, item, Operator.findEnum(operator), value, BooleanOperator.findEnum(booleanOperator)); filter.add(trackFilterElement); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); }
private static Vector<Annotation> parseAnnotations(Node parent) throws XmlParserException { Vector<Annotation> annotations = new Vector<Annotation>(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("annotation")) { String label = null, value = null, valuetype = null, unit = null; NodeList annotation_nodes = element.getChildNodes(); for (int annotationid = 0; annotationid < annotation_nodes.getLength(); ++annotationid) { Node annotation_node = annotation_nodes.item(annotationid); if (annotation_node.getNodeType() != Node.ELEMENT_NODE) continue; Element annotation_element = (Element) annotation_node; if (annotation_element.getTagName().equals("label")) label = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("value")) value = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("valuetype")) valuetype = annotation_element.getTextContent(); } if (label == null || value == null || valuetype == null) throw new XmlParserException("Annotation is missing either: label, value or valuetype"); Annotation annotation = new Annotation(label, value, Annotation.ValueType.valueOf(valuetype)); annotation.setUnit(unit); if (annotation.getValueType() == Annotation.ValueType.ONTOLOGY) annotation.setOntologyRef(element.getAttribute("ontologyref")); if (element.getAttribute("unit") != null) annotation.setUnit(element.getAttribute("unit")); annotations.add(annotation); } } return annotations; }
/** * Reads the children of an XML element and matches them to properties of a bean. * * @param ob The bean to receive the values * @param element The element the corresponds to the bean * @throws IOException If there is an error reading the document */ public void readObject(Object ob, Element element) throws IOException { // If the object is null, skip the element if (ob == null) { return; } try { BeanInfo info = (BeanInfo) beanCache.get(ob.getClass()); if (info == null) { // Get the bean info for the object info = Introspector.getBeanInfo(ob.getClass(), Object.class); beanCache.put(ob.getClass(), info); } // Get the object's properties PropertyDescriptor[] props = info.getPropertyDescriptors(); // Get the attributes of the node NamedNodeMap attrs = element.getAttributes(); // Get the children of the XML element NodeList nodes = element.getChildNodes(); int numNodes = nodes.getLength(); for (int i = 0; i < props.length; i++) { // Treat indexed properties a little differently if (props[i] instanceof IndexedPropertyDescriptor) { readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs); } else { readProperty(ob, props[i], nodes, attrs); } } } catch (IntrospectionException exc) { throw new IOException( "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString()); } }
private static NodeList getChildElements(Element self, String elementName) { List result = new ArrayList(); NodeList nodeList = self.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if ("*".equals(elementName) || child.getTagName().equals(elementName)) { result.add(child); } } else if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue(); if (trimWhitespace) { value = value.trim(); } if ("*".equals(elementName) && value.length() > 0) { node.setNodeValue(value); result.add(node); } } } return new NodesHolder(result); }
@Test public void testAddText() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); String xml = "<?xml version=\"1.0\"?>" + "<root>" + "<item id=\"a\"/>" + "<child id=\"1\"/>" + "<item id=\"b\"/>" + "<child id=\"2\"/>" + "</root>"; DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = doc.getDocumentElement(); Text text = doc.createTextNode("hello world"); root.insertBefore(text, root.getFirstChild().getNextSibling()); Assert.assertEquals( "append text", "hello world", root.getChildNodes().item(1).getTextContent()); }
/** * For backward compatibility * * @param session * @param element * @param additionalInformation */ private void processVisibleAttributes( Session session, Element element, HashMap additionalInformation) { // session.clearRegionsOfInterest(); NodeList elements = element.getChildNodes(); if (elements.getLength() > 0) { Set<String> visibleAttributes = new HashSet(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode .getNodeName() .equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) { visibleAttributes.add( ((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText())); } } final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames(); Set<String> hiddenAttributes = new HashSet<String>(attributeNames); hiddenAttributes.removeAll(visibleAttributes); session.setHiddenAttributes(hiddenAttributes); } }
private void validateRequiredExtensionAttributes(Element element, ISchemaElement schemaElement) { int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_NO_REQUIRED_ATT); if (severity == CompilerFlags.IGNORE) return; ISchemaAttribute[] attInfos = schemaElement.getAttributes(); for (int i = 0; i < attInfos.length; i++) { ISchemaAttribute attInfo = attInfos[i]; if (attInfo.getUse() == ISchemaAttribute.REQUIRED) { boolean found = element.getAttributeNode(attInfo.getName()) != null; if (!found && attInfo.getKind() == IMetaAttribute.JAVA) { NodeList children = element.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (attInfo.getName().equals(children.item(j).getNodeName())) { found = true; break; } } } if (!found) { reportMissingRequiredAttribute(element, attInfo.getName(), severity); } } } }
@Test public void loopCheckElementNameAndAttribute() throws ParserConfigurationException, IOException, SAXException { // builderFactory = DocumentBuilderFactory.newInstance(); String xml = "<?xml version=\"1.0\"?>" + "<root>" + "<item name=\"a\" />" + "<item name=\"b\" />" + "<item name=\"c\" />" + "</root>"; DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = doc.getDocumentElement(); NodeList nodeList = root.getChildNodes(); char ch = 'a'; for (int i = 0; i < nodeList.getLength(); i++) { Element node = (Element) nodeList.item(i); Assert.assertEquals("node name", "item", node.getNodeName()); Assert.assertEquals("attribute value", String.valueOf(ch), node.getAttribute("name")); ch += 1; } }
/** * Constructs an attribute element from an existing XML block. * * @param element representing a DOM tree element. * @exception SAMLException if there is an error in the sender or in the element definition. */ public Attribute(Element element) throws SAMLException { // make sure that the input xml block is not null if (element == null) { SAMLUtilsCommon.debug.message("Attribute: Input is null."); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } // Make sure this is an Attribute. String tag = null; tag = element.getLocalName(); if ((tag == null) || (!tag.equals("Attribute"))) { SAMLUtilsCommon.debug.message("Attribute: wrong input"); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } int i = 0; // handle attributes NamedNodeMap atts = element.getAttributes(); int attrCount = atts.getLength(); for (i = 0; i < attrCount; i++) { Node att = atts.item(i); if (att.getNodeType() == Node.ATTRIBUTE_NODE) { String attName = att.getLocalName(); if (attName == null) { attName = att.getNodeName(); } if (attName == null || attName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute:" + "Attribute Name is either null or empty."); } continue; // throw new SAMLRequesterException( // SAMLUtilsCommon.bundle.getString("nullInput")); } if (attName.equals("AttributeName")) { this._attributeName = ((Attr) att).getValue().trim(); } else if (attName.equals("AttributeNamespace")) { this._attributeNameSpace = ((Attr) att).getValue().trim(); } } } // AttributeName is required if (_attributeName == null || _attributeName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute: " + "AttributeName is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // AttributeNamespace is required if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute: " + "AttributeNamespace is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // handle the children of Attribute element NodeList nodes = element.getChildNodes(); int nodeCount = nodes.getLength(); if (nodeCount > 0) { for (i = 0; i < nodeCount; i++) { Node currentNode = nodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { String tagName = currentNode.getLocalName(); String tagNS = currentNode.getNamespaceURI(); if ((tagName == null) || tagName.length() == 0 || tagNS == null || tagNS.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute:" + " The tag name or tag namespace of child" + " element is either null or empty."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } if (tagName.equals("AttributeValue") && tagNS.equals(SAMLConstants.assertionSAMLNameSpaceURI)) { if (_attributeValue == null) { _attributeValue = new ArrayList(); } if (!(_attributeValue.add((Element) currentNode))) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute: failed to " + "add to the attribute value list."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError")); } } else { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute:" + "wrong element:" + tagName); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } } // end of if (currentNode.getNodeType() == Node.ELEMENT_NODE) } // end of for loop } // end of if (nodeCount > 0) if (_attributeValue == null || _attributeValue.isEmpty()) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute: " + "should contain at least one AttributeValue."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingElement")); } }
protected void init(Element root) { NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equals("meta")) { Element meta = (Element) child; String value = XMLUtil.getText(meta); this.metaAttributes.put(meta.getAttribute("name"), value); } } // handle registers - OPTIONAL Element r = XMLUtil.getChildElement(root, "registers"); if (r != null) { List registers = XMLUtil.getChildElements(r, "register"); for (int i = 0; i < registers.size(); i++) { Element register = (Element) registers.get(i); RegisterDescriptor registerDescriptor = DescriptorFactory.getFactory().createRegisterDescriptor(register); registerDescriptor.setParent(this); this.registers.add(registerDescriptor); } } // handle global-conditions - OPTIONAL Element globalConditionsElement = XMLUtil.getChildElement(root, "global-conditions"); if (globalConditionsElement != null) { Element globalConditions = XMLUtil.getChildElement(globalConditionsElement, "conditions"); ConditionsDescriptor conditionsDescriptor = DescriptorFactory.getFactory().createConditionsDescriptor(globalConditions); conditionsDescriptor.setParent(this); this.globalConditions = conditionsDescriptor; } // handle initial-steps - REQUIRED Element intialActionsElement = XMLUtil.getChildElement(root, "initial-actions"); List initialActions = XMLUtil.getChildElements(intialActionsElement, "action"); for (int i = 0; i < initialActions.size(); i++) { Element initialAction = (Element) initialActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(initialAction); actionDescriptor.setParent(this); this.initialActions.add(actionDescriptor); } // handle global-actions - OPTIONAL Element globalActionsElement = XMLUtil.getChildElement(root, "global-actions"); if (globalActionsElement != null) { List globalActions = XMLUtil.getChildElements(globalActionsElement, "action"); for (int i = 0; i < globalActions.size(); i++) { Element globalAction = (Element) globalActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(globalAction); actionDescriptor.setParent(this); this.globalActions.add(actionDescriptor); } } // handle common-actions - OPTIONAL // - Store actions in HashMap for now. When parsing Steps, we'll resolve // any common actions into local references. Element commonActionsElement = XMLUtil.getChildElement(root, "common-actions"); if (commonActionsElement != null) { List commonActions = XMLUtil.getChildElements(commonActionsElement, "action"); for (int i = 0; i < commonActions.size(); i++) { Element commonAction = (Element) commonActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(commonAction); actionDescriptor.setParent(this); addCommonAction(actionDescriptor); } } // handle timer-functions - OPTIONAL Element timerFunctionsElement = XMLUtil.getChildElement(root, "trigger-functions"); if (timerFunctionsElement != null) { List timerFunctions = XMLUtil.getChildElements(timerFunctionsElement, "trigger-function"); for (int i = 0; i < timerFunctions.size(); i++) { Element timerFunction = (Element) timerFunctions.get(i); Integer id = new Integer(timerFunction.getAttribute("id")); FunctionDescriptor function = DescriptorFactory.getFactory() .createFunctionDescriptor(XMLUtil.getChildElement(timerFunction, "function")); function.setParent(this); this.timerFunctions.put(id, function); } } // handle steps - REQUIRED Element stepsElement = XMLUtil.getChildElement(root, "steps"); List steps = XMLUtil.getChildElements(stepsElement, "step"); for (int i = 0; i < steps.size(); i++) { Element step = (Element) steps.get(i); StepDescriptor stepDescriptor = DescriptorFactory.getFactory().createStepDescriptor(step, this); this.steps.add(stepDescriptor); } // handle splits - OPTIONAL Element splitsElement = XMLUtil.getChildElement(root, "splits"); if (splitsElement != null) { List split = XMLUtil.getChildElements(splitsElement, "split"); for (int i = 0; i < split.size(); i++) { Element s = (Element) split.get(i); SplitDescriptor splitDescriptor = DescriptorFactory.getFactory().createSplitDescriptor(s); splitDescriptor.setParent(this); this.splits.add(splitDescriptor); } } // handle joins - OPTIONAL: Element joinsElement = XMLUtil.getChildElement(root, "joins"); if (joinsElement != null) { List join = XMLUtil.getChildElements(joinsElement, "join"); for (int i = 0; i < join.size(); i++) { Element s = (Element) join.get(i); JoinDescriptor joinDescriptor = DescriptorFactory.getFactory().createJoinDescriptor(s); joinDescriptor.setParent(this); this.joins.add(joinDescriptor); } } }