List of usage examples for org.w3c.dom Element getAttributes
public NamedNodeMap getAttributes();
NamedNodeMap
containing the attributes of this node (if it is an Element
) or null
otherwise. From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
@Override protected Element getStructure(Document doc, LayoutStructure ls) { Element structure = null;/*from ww w . j av a2 s. c om*/ String type = ls.getType(); if (ls.isChannel()) { final IPortletDefinition channelDef = this.portletDefinitionRegistry .getPortletDefinition(String.valueOf(ls.getChanId())); if (channelDef != null && channelApproved(channelDef.getApprovalDate())) { structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef, ls.getLocale()); } else { structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), MissingPortletDefinition.INSTANCE, null); } } else { // create folder objects including dlm new types in cp namespace if (type != null && type.startsWith(Constants.NS)) { structure = doc.createElementNS(Constants.NS_URI, type); } else { structure = doc.createElement("folder"); } structure.setAttribute("name", ls.getName()); structure.setAttribute("type", (type != null ? type : "regular")); } structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false")); structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false")); structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false")); if (localeAware) { structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji } /* * Parameters from up_layout_param are loaded slightly differently for * folders and channels. For folders all parameters are added as attributes * of the Element. For channels only those parameters with names starting * with the dlm namespace Constants.NS are added as attributes to the Element. * Others are added as child parameter Elements. */ if (ls.getParameters() != null) { for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) { final StructureParameter sp = (StructureParameter) itr.next(); String pName = sp.getName(); if (!ls.isChannel()) { // Folder if (pName.startsWith(Constants.NS)) { structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue()); } else { structure.setAttribute(pName, sp.getValue()); } } else // Channel { // if dealing with a dlm namespace param add as attribute if (pName.startsWith(Constants.NS)) { structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue()); itr.remove(); } else { /* * do traditional override processing. some explanation is in * order. The structure element was created by the * ChannelDefinition and only contains parameter children if the * definition had defined parameters. These are checked for each * layout loaded parameter as found in LayoutStructure.parameters. * If a name match is found then we need to see if overriding is * allowed and if so we set the value on the child parameter * element. At that point we are done with that version loaded * from the layout so we remove it from the in-memory set of * parameters that are being merged-in. Then, after all such have * been checked against those added by the channel definition we * add in any remaining as adhoc, unregulated parameters. */ final NodeList nodeListParameters = structure.getElementsByTagName("parameter"); for (int j = 0; j < nodeListParameters.getLength(); j++) { final Element parmElement = (Element) nodeListParameters.item(j); final NamedNodeMap nm = parmElement.getAttributes(); final String nodeName = nm.getNamedItem("name").getNodeValue(); if (nodeName.equals(pName)) { final Node override = nm.getNamedItem("override"); if (override != null && override.getNodeValue().equals("yes")) { final Node valueNode = nm.getNamedItem("value"); valueNode.setNodeValue(sp.getValue()); } itr.remove(); break; // found the corresponding one so skip the rest } } } } } // For channels, add any remaining parameter elements loaded with the // layout as adhoc, unregulated, parameter children that can be overridden. if (ls.isChannel()) { for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) { final StructureParameter sp = (StructureParameter) itr.next(); final Element parameter = doc.createElement("parameter"); parameter.setAttribute("name", sp.getName()); parameter.setAttribute("value", sp.getValue()); parameter.setAttribute("override", "yes"); structure.appendChild(parameter); } } } // finish setting up elements based on loaded params final String origin = structure.getAttribute(Constants.ATT_ORIGIN); final String prefix = ls.isChannel() ? channelPrefix : folderPrefix; // if not null we are dealing with a node incorporated from another // layout and this node contains changes made by the user so handle // id swapping. if (!origin.equals("")) { structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId()); structure.setAttribute("ID", origin); } else if (!ls.isChannel()) // regular folder owned by this user, need to check if this is a // directive or ui element. If the latter then use traditional id // structure { if (type != null && type.startsWith(Constants.NS)) { structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId()); } else { structure.setAttribute("ID", folderPrefix + ls.getStructId()); } } else { logger.debug("Adding identifier {}{}", folderPrefix, ls.getStructId()); structure.setAttribute("ID", channelPrefix + ls.getStructId()); } structure.setIdAttribute(Constants.ATT_ID, true); return structure; }
From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
@Override protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt) throws SQLException { if (node == null) { // No more return 0; }//w w w .j av a 2 s . c o m if (node.getNodeName().equals("parameter")) { //parameter, skip it and go on to the next node return this.saveStructure(node.getNextSibling(), structStmt, parmStmt); } if (!(node instanceof Element)) { return 0; } final Element structure = (Element) node; if (logger.isDebugEnabled()) { logger.debug("saveStructure XML content: {}", XmlUtilitiesImpl.toString(node)); } // determine the struct_id for storing in the db. For incorporated nodes in // the plf their ID is a system-wide unique ID while their struct_id for // storing in the db is cached in a dlm:plfID attribute. int saveStructId = -1; final String plfID = structure.getAttribute(Constants.ATT_PLF_ID); if (!plfID.equals("")) { saveStructId = Integer.parseInt(plfID.substring(1)); } else { final String id = structure.getAttribute("ID"); saveStructId = Integer.parseInt(id.substring(1)); } int nextStructId = 0; int childStructId = 0; int chanId = -1; IPortletDefinition portletDef = null; final boolean isChannel = node.getNodeName().equals("channel"); if (isChannel) { chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue()); portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId)); if (portletDef == null) { //Portlet doesn't exist any more, drop the layout node return 0; } } if (node.hasChildNodes()) { childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt); } nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt); structStmt.clearParameters(); structStmt.setInt(1, saveStructId); structStmt.setInt(2, nextStructId); structStmt.setInt(3, childStructId); final String externalId = structure.getAttribute("external_id"); if (externalId != null && externalId.trim().length() > 0) { final Integer eID = new Integer(externalId); structStmt.setInt(4, eID.intValue()); } else { structStmt.setNull(4, java.sql.Types.NUMERIC); } if (isChannel) { structStmt.setInt(5, chanId); structStmt.setNull(6, java.sql.Types.VARCHAR); } else { structStmt.setNull(5, java.sql.Types.NUMERIC); structStmt.setString(6, structure.getAttribute("name")); } final String structType = structure.getAttribute("type"); structStmt.setString(7, structType); structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden")))); structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable")))); structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable")))); logger.debug(structStmt.toString()); structStmt.executeUpdate(); // code to persist extension attributes for dlm final NamedNodeMap attribs = node.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { final Node attrib = attribs.item(i); final String name = attrib.getNodeName(); if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID) && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) { // a cp extension attribute. Push into param table. parmStmt.clearParameters(); parmStmt.setInt(1, saveStructId); parmStmt.setString(2, name); parmStmt.setString(3, attrib.getNodeValue()); logger.debug(parmStmt.toString()); parmStmt.executeUpdate(); } } final NodeList parameters = node.getChildNodes(); if (parameters != null && isChannel) { for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeName().equals("parameter")) { final Element parmElement = (Element) parameters.item(i); final NamedNodeMap nm = parmElement.getAttributes(); final String parmName = nm.getNamedItem("name").getNodeValue(); final String parmValue = nm.getNamedItem("value").getNodeValue(); final Node override = nm.getNamedItem("override"); // if no override specified then default to allowed if (override != null && !override.getNodeValue().equals("yes")) { // can't override } else { // override only for adhoc or if diff from chan def final IPortletDefinitionParameter cp = portletDef.getParameter(parmName); if (cp == null || !cp.getValue().equals(parmValue)) { parmStmt.clearParameters(); parmStmt.setInt(1, saveStructId); parmStmt.setString(2, parmName); parmStmt.setString(3, parmValue); logger.debug(parmStmt.toString()); parmStmt.executeUpdate(); } } } } } return saveStructId; }
From source file:org.chiba.xml.xforms.constraints.Validator.java
/** * Validates the specified instance data node and its descendants. * * @param instance the instance to be validated. * @param path an xpath denoting an arbitrary subtre of the instance. * @return <code>true</code> if all relevant instance data nodes are valid * regarding in terms of their <code>constraint</code> and * <code>required</code> properties, otherwise <code>false</code>. *//*from w ww . j a va2 s . c o m*/ public boolean validate(Instance instance, String path) { // initialize boolean result = true; String expressionPath = path; if (!path.endsWith("/")) { expressionPath = expressionPath + "/"; } // set expression path to contain the specified path and its subtree expressionPath = expressionPath + "descendant-or-self::*"; // evaluate expression path JXPathContext context = instance.getInstanceContext(); Iterator iterator = context.iteratePointers(expressionPath); Pointer locationPointer; String locationPath; while (iterator.hasNext()) { locationPointer = (Pointer) iterator.next(); locationPath = locationPointer.asPath(); Element element = (Element) locationPointer.getNode(); // validate element node against type String type = element.getAttributeNS(NamespaceCtx.XMLSCHEMA_INSTANCE_NS, "type"); result &= validateNode(instance, locationPath, type); // handle attributes explicitely since JXPath has // seriuos problems with namespaced attributes NamedNodeMap attributes = element.getAttributes(); for (int index = 0; index < attributes.getLength(); index++) { Attr attr = (Attr) attributes.item(index); if (isInstanceAttribute(attr)) { // validate attribute node result &= validateNode(instance, locationPath + "/@" + attr.getNodeName()); } } } return result; }
From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java
/** * @param cruxPageMetaData/*from w w w .j av a 2 s. c o m*/ * @param cruxArrayMetaData */ private void generateCruxMetaDataAttributes(Element cruxPageMetaData, StringBuilder cruxArrayMetaData) { NamedNodeMap attributes = cruxPageMetaData.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attrName = attribute.getLocalName(); if (attrName == null) { attrName = attribute.getNodeName(); } String attrValue = attribute.getNodeValue(); String namespaceURI = attribute.getNamespaceURI(); if (!StringUtils.isEmpty(attrValue) && (namespaceURI == null || !namespaceURI.endsWith("/xmlns/"))) { cruxArrayMetaData.append(","); cruxArrayMetaData.append("\"" + attrName + "\":"); cruxArrayMetaData.append("\"" + HTMLUtils.escapeJavascriptString(attrValue, escapeXML) + "\""); } } } }
From source file:org.dhatim.xml.DomUtils.java
/** * Rename element./*from ww w . jav a 2 s .co m*/ * @param element The element to be renamed. * @param replacementElement The tag name of the replacement element. Can be a prefix qualified * name if the namespace is not the null namepsace ({@link javax.xml.XMLConstants#NULL_NS_URI}). * @param namespace The element namespace. * @param keepChildContent <code>true</code> if the target element's child content * is to be copied to the replacement element, false if not. Default <code>true</code>. * @param keepAttributes <code>true</code> if the target element's attributes * are to be copied to the replacement element, false if not. Default <code>true</code>. * @return The renamed element. */ public static Element renameElementNS(Element element, String replacementElement, String namespace, boolean keepChildContent, boolean keepAttributes) { AssertArgument.isNotNull(element, "element"); AssertArgument.isNotNull(replacementElement, "replacementElement"); Element replacement; if (namespace != null && !XMLConstants.NULL_NS_URI.equals(namespace)) { replacement = element.getOwnerDocument().createElementNS(namespace, replacementElement); } else { replacement = element.getOwnerDocument().createElement(replacementElement); } if (keepChildContent) { DomUtils.copyChildNodes(element, replacement); } if (keepAttributes) { NamedNodeMap attributes = element.getAttributes(); int attributeCount = attributes.getLength(); for (int i = 0; i < attributeCount; i++) { Attr attribute = (Attr) attributes.item(i); replacement.setAttribute(attribute.getName(), attribute.getValue()); } } DomUtils.replaceNode(replacement, element); return replacement; }
From source file:org.dita.dost.writer.ConrefPushParser.java
private void writeNode(final Node node) throws SAXException { switch (node.getNodeType()) { case Node.DOCUMENT_FRAGMENT_NODE: { final NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { writeNode(children.item(i)); }/*from w w w.j av a 2 s. co m*/ break; } case Node.ELEMENT_NODE: final Element e = (Element) node; final AttributesBuilder b = new AttributesBuilder(); final NamedNodeMap atts = e.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { b.add((Attr) atts.item(i)); } final String ns = e.getNamespaceURI() != null ? e.getNamespaceURI() : NULL_NS_URI; getContentHandler().startElement(ns, e.getTagName(), e.getNodeName(), b.build()); final NodeList children = e.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { writeNode(children.item(i)); } getContentHandler().endElement(ns, e.getTagName(), e.getNodeName()); break; case Node.TEXT_NODE: final char[] data = node.getNodeValue().toCharArray(); getContentHandler().characters(data, 0, data.length); break; case Node.PROCESSING_INSTRUCTION_NODE: getContentHandler().processingInstruction(node.getNodeName(), node.getNodeValue()); break; default: throw new UnsupportedOperationException(); } }
From source file:org.dita.dost.writer.TestConrefPushParser.java
@Test public void testWrite() throws DITAOTException, ParserConfigurationException, SAXException, IOException { /*// w ww .ja va 2 s.co m * the part of content of conrefpush_stub2.xml is * <ol> * <li id="A">A</li> * <li id="B">B</li> * <li id="C">C</li> * </ol> * * the part of content of conrefpush_stup.xml is * <steps> * <step conaction="pushbefore"><cmd>before</cmd></step> * <step conref="conrefpush_stub2.xml#X/A" conaction="mark"/> * <step conref="conrefpush_stub2.xml#X/B" conaction="mark"/> * <step conaction="pushafter"><cmd>after</cmd></step> * <step conref="conrefpush_stub2.xml#X/C" conaction="pushreplace"><cmd>replace</cmd></step> * </steps> * * after conrefpush the part of conrefpush_stub2.xml should be like this * <ol class="- topic/ol "> * <li class="- topic/li task/step "> * <ph class="- topic/ph task/cmd "> * before * </ph> * </li> * <li id="A" class="- topic/li ">A</li> * <li id="B" class="- topic/li ">B</li> * <li class="- topic/li task/step "> * <ph class="- topic/ph task/cmd "> * after * </ph> * </li> * <li class="- topic/li task/step "> * <ph class="- topic/ph task/cmd "> * replace * </ph> * </li> * </ol> */ final ConrefPushParser parser = new ConrefPushParser(); parser.setLogger(new TestUtils.TestLogger()); parser.setJob(new Job(tempDir)); final ConrefPushReader reader = new ConrefPushReader(); reader.read(inputFile.getAbsoluteFile()); final Map<File, Hashtable<MoveKey, DocumentFragment>> pushSet = reader.getPushMap(); final Iterator<Map.Entry<File, Hashtable<MoveKey, DocumentFragment>>> iter = pushSet.entrySet().iterator(); if (iter.hasNext()) { final Map.Entry<File, Hashtable<MoveKey, DocumentFragment>> entry = iter.next(); // initialize the parsed file copyFile(new File(srcDir, "conrefpush_stub2_backup.xml"), entry.getKey()); // final Content content = new ContentImpl(); // content.setValue(entry.getValue()); // parser.setContent(content); parser.setMoveTable(entry.getValue()); parser.write(entry.getKey()); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(entry.getKey()); final Element elem = document.getDocumentElement(); NodeList nodeList = elem.getChildNodes(); // according to the structure, it comes to the <li> after 2 iterations. for (int i = 0; i < 2; i++) { for (int j = 0; j < nodeList.getLength(); j++) { if (nodeList.item(j).getNodeType() == Node.ELEMENT_NODE) { nodeList = nodeList.item(j).getChildNodes(); break; } } } Element element; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { element = (Element) node; if (element.getAttributes().getNamedItem("id") != null && element.getAttributes().getNamedItem("id").getNodeValue().equals("A")) { // get node of before node = element.getPreviousSibling(); while (node.getNodeType() != Node.ELEMENT_NODE) { node = node.getPreviousSibling(); } assertEquals( "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">before</ph></li>", nodeToString((Element) node)); } else if (element.getAttributes().getNamedItem("id") != null && element.getAttributes().getNamedItem("id").getNodeValue().equals("B")) { // get node of after node = element.getNextSibling(); while (node.getNodeType() != Node.ELEMENT_NODE) { node = node.getNextSibling(); } assertEquals( "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">after</ph></li>", nodeToString((Element) node)); // get node of replacement node = node.getNextSibling(); while (node.getNodeType() != Node.ELEMENT_NODE) { node = node.getNextSibling(); } assertEquals( "<li class=\"- topic/li task/step \" id=\"C\"><ph class=\"- topic/ph task/cmd \">replace</ph></li>", nodeToString((Element) node)); } } } } }
From source file:org.dita.dost.writer.TestConrefPushParser.java
private String nodeToString(final Element elem) { final StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(Constants.LESS_THAN).append(elem.getNodeName()); final NamedNodeMap namedNodeMap = elem.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { stringBuffer.append(Constants.STRING_BLANK).append(namedNodeMap.item(i).getNodeName()) .append(Constants.EQUAL) .append(Constants.QUOTATION + namedNodeMap.item(i).getNodeValue() + Constants.QUOTATION); }/*from w ww . j a v a 2s . co m*/ stringBuffer.append(Constants.GREATER_THAN); final NodeList nodeList = elem.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // If the type of current node is ELEMENT_NODE, process it stringBuffer.append(nodeToString((Element) node)); } if (node.getNodeType() == Node.TEXT_NODE) { stringBuffer.append(node.getNodeValue()); } } stringBuffer.append("</").append(elem.getNodeName()).append(Constants.GREATER_THAN); return stringBuffer.toString(); }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.wst.WTPCopyUtil.java
private static void updatePrefixes(Element element, Map<String, String> prefixMap) { NamedNodeMap namedNodeMap = element.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { String attrValue = namedNodeMap.item(i).getNodeValue(); String attrName = namedNodeMap.item(i).getNodeName(); for (String str : prefixMap.keySet()) { if (StringUtils.isNotEmpty(attrValue) && attrValue.trim().startsWith(str + ":")) { String trimmedAttrValue = attrValue.trim(); String newAttrValue = trimmedAttrValue; if (trimmedAttrValue.startsWith(str + ":xs:")) { newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":xs:", "xs:"); } else if (StringUtils.countMatches(trimmedAttrValue, ":") == 2) { //already contains a prefix trimmedAttrValue = StringUtils.substringAfter(trimmedAttrValue, ":"); String oldPrefix = StringUtils.substringBefore(trimmedAttrValue, ":"); newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, oldPrefix + ":", prefixMap.get(oldPrefix) + ":"); } else { newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":", prefixMap.get(str) + ":"); }/* w ww . ja v a 2 s. co m*/ element.getAttributeNode(attrName).setValue(newAttrValue); } } } NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child instanceof Element) updatePrefixes((Element) child, prefixMap); } }
From source file:org.eclipse.uomo.xml.test.XMLTestCase.java
private String compareAttributes(Element e1, Element e2, String p) { NamedNodeMap n1 = e1.getAttributes(); NamedNodeMap n2 = e2.getAttributes(); for (int i = 0; i < n1.getLength(); i++) { Node a1 = n1.item(0);/* ww w . ja va2 s . c o m*/ Node a2 = n2.getNamedItemNS(a1.getNamespaceURI(), a1.getLocalName()); if (a2 == null) return "Unable to find attribute " + a1.getNodeName() + " @ " + p; if (a1.getNodeValue() != null || a2.getNodeValue() != null) { if (a1.getNodeValue() == null || a2.getNodeValue() == null || !a1.getNodeValue().equals(a2.getNodeValue())) return "Attribute text differs @ " + p + "/@" + a1.getNodeName() + ": '" + a1.getNodeValue() + "' / '" + a2.getNodeValue() + "'"; } } for (int i = 0; i < n2.getLength(); i++) { Node a2 = n2.item(0); Node a1 = n1.getNamedItemNS(a2.getNamespaceURI(), a2.getLocalName()); if (a1 == null) return "Unable to find attribute " + a2.getNodeName() + " @ " + p; if (a1.getNodeValue() != null || a2.getNodeValue() != null) { if (a1.getNodeValue() == null || a2.getNodeValue() == null || !a1.getNodeValue().equals(a2.getNodeValue())) return "Attribute text differs @ " + p + "/@" + a1.getNodeName() + ": '" + a1.getNodeValue() + "' / '" + a2.getNodeValue() + "'"; } } return null; }