Example usage for org.w3c.dom Attr setValue

List of usage examples for org.w3c.dom Attr setValue

Introduction

In this page you can find the example usage for org.w3c.dom Attr setValue.

Prototype

public void setValue(String value) throws DOMException;

Source Link

Document

On retrieval, the value of the attribute is returned as a string.

Usage

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Evaluate whether attribute changes exist in the ilfChild and if so
   apply them. Returns true if some changes existed. If changes existed
   but matched those in the original node then they are not applicable,
   are removed from the editSet, and false is returned.
*///from w w w.j av a2  s.  com
public static boolean applyEditSet(Element plfChild, Element original) {
    // first get edit set if it exists
    Element editSet = null;
    try {
        editSet = getEditSet(plfChild, null, null, false);
    } catch (Exception e) {
        // should never occur unless problem during create in getEditSet
        // and we are telling it not to create.
        return false;
    }

    if (editSet == null || editSet.getChildNodes().getLength() == 0)
        return false;

    if (original.getAttribute(Constants.ATT_EDIT_ALLOWED).equals("false")) {
        // can't change anymore so discard changes
        plfChild.removeChild(editSet);
        return false;
    }

    Document ilf = original.getOwnerDocument();
    boolean attributeChanged = false;
    Element edit = (Element) editSet.getFirstChild();

    while (edit != null) {
        String attribName = edit.getAttribute(Constants.ATT_NAME);
        Attr attr = plfChild.getAttributeNode(attribName);

        // preferences are only updated at preference storage time so
        // if a preference change exists in the edit set assume it is
        // still valid so that the node being edited will persist in
        // the PLF.
        if (edit.getNodeName().equals(Constants.ELM_PREF))
            attributeChanged = true;
        else if (attr == null) {
            // attribute removed. See if needs removing in original.
            attr = original.getAttributeNode(attribName);
            if (attr == null) // edit irrelevant,
                editSet.removeChild(edit);
            else {
                // edit differs, apply to original
                original.removeAttribute(attribName);
                attributeChanged = true;
            }
        } else {
            // attribute there, see if original is also there
            Attr origAttr = original.getAttributeNode(attribName);
            if (origAttr == null) {
                // original attribute isn't defined so need to add
                origAttr = (Attr) ilf.importNode(attr, true);
                original.setAttributeNode(origAttr);
                attributeChanged = true;
            } else {
                // original attrib found, see if different
                if (attr.getValue().equals(origAttr.getValue())) {
                    // they are the same, edit irrelevant
                    editSet.removeChild(edit);
                } else {
                    // edit differs, apply to original
                    origAttr.setValue(attr.getValue());
                    attributeChanged = true;
                }
            }
        }
        edit = (Element) edit.getNextSibling();
    }
    return attributeChanged;
}

From source file:org.bigtextml.topics.ParallelTopicModel.java

private Attr getAttribute(String name, String value, Document doc) {
    Attr attr = doc.createAttribute(name);
    attr.setValue(value);
    return attr;/*www. j  a va 2 s .com*/
}

From source file:org.carewebframework.ui.xml.ZK2XML.java

/**
 * Adds the root component to the XML document at the current level along with all bean
 * properties that return String or primitive types. Then, recurses over all of the root
 * component's children./*from w w w  .ja  v a 2 s.  c  o m*/
 * 
 * @param root The root component.
 * @param parent The parent XML node.
 */
private void toXML(Component root, Node parent) {
    TreeMap<String, String> properties = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    Class<?> clazz = root.getClass();
    ComponentDefinition def = root.getDefinition();
    String cmpname = def.getName();

    if (def.getImplementationClass() != clazz) {
        properties.put("use", clazz.getName());
    }

    if (def.getApply() != null) {
        properties.put("apply", def.getApply());
    }

    Node child = doc.createElement(cmpname);
    parent.appendChild(child);

    for (PropertyDescriptor propDx : PropertyUtils.getPropertyDescriptors(root)) {
        Method getter = propDx.getReadMethod();
        Method setter = propDx.getWriteMethod();
        String name = propDx.getName();

        if (getter != null && setter != null && !isExcluded(name, cmpname, null)
                && !setter.isAnnotationPresent(Deprecated.class)
                && (getter.getReturnType() == String.class || getter.getReturnType().isPrimitive())) {
            try {
                Object raw = getter.invoke(root);
                String value = raw == null ? null : raw.toString();

                if (StringUtils.isEmpty(value) || ("id".equals(name) && value.startsWith("z_"))
                        || isExcluded(name, cmpname, value)) {
                    continue;
                }

                properties.put(name, value.toString());
            } catch (Exception e) {
            }
        }
    }

    for (Entry<String, String> entry : properties.entrySet()) {
        Attr attr = doc.createAttribute(entry.getKey());
        child.getAttributes().setNamedItem(attr);
        attr.setValue(entry.getValue());
    }

    properties = null;

    for (Component cmp : root.getChildren()) {
        toXML(cmp, child);
    }
}

From source file:org.dita.dost.module.BranchFilterModule.java

/** Rewrite href or copy-to if duplicates exist. */
private void rewriteDuplicates(final Element root) {
    // collect href and copy-to
    final Map<URI, Map<Set<URI>, List<Attr>>> refs = new HashMap<>();
    for (final Element e : getTopicrefs(root)) {
        Attr attr = e.getAttributeNode(BRANCH_COPY_TO);
        if (attr == null) {
            attr = e.getAttributeNode(ATTRIBUTE_NAME_COPY_TO);
            if (attr == null) {
                attr = e.getAttributeNode(ATTRIBUTE_NAME_HREF);
            }/*  ww  w  .  j  a  va2  s. c  o  m*/
        }
        if (attr != null) {
            final URI h = stripFragment(map.resolve(attr.getValue()));
            Map<Set<URI>, List<Attr>> attrsMap = refs.computeIfAbsent(h, k -> new HashMap<>());
            final Set<URI> currentFilter = getBranchFilters(e);
            List<Attr> attrs = attrsMap.computeIfAbsent(currentFilter, k -> new ArrayList<>());
            attrs.add(attr);
        }
    }
    // check and rewrite
    for (final Map.Entry<URI, Map<Set<URI>, List<Attr>>> ref : refs.entrySet()) {
        final Map<Set<URI>, List<Attr>> attrsMaps = ref.getValue();
        if (attrsMaps.size() > 1) {
            if (attrsMaps.containsKey(Collections.EMPTY_LIST)) {
                attrsMaps.remove(Collections.EMPTY_LIST);
            } else {
                Set<URI> first = attrsMaps.keySet().iterator().next();
                attrsMaps.remove(first);
            }
            int i = 1;
            for (final Map.Entry<Set<URI>, List<Attr>> attrsMap : attrsMaps.entrySet()) {
                final String suffix = "-" + i;
                final List<Attr> attrs = attrsMap.getValue();
                for (final Attr attr : attrs) {
                    final String gen = addSuffix(attr.getValue(), suffix);
                    logger.info(MessageUtils.getMessage("DOTJ065I", attr.getValue(), gen)
                            .setLocation(attr.getOwnerElement()).toString());
                    if (attr.getName().equals(BRANCH_COPY_TO)) {
                        attr.setValue(gen);
                    } else {
                        attr.getOwnerElement().setAttribute(BRANCH_COPY_TO, gen);
                    }

                    final URI dstUri = map.resolve(gen);
                    if (dstUri != null) {
                        final FileInfo hrefFileInfo = job.getFileInfo(currentFile.resolve(attr.getValue()));
                        if (hrefFileInfo != null) {
                            final URI newResult = addSuffix(hrefFileInfo.result, suffix);
                            final FileInfo.Builder dstBuilder = new FileInfo.Builder(hrefFileInfo).uri(dstUri)
                                    .result(newResult);
                            if (hrefFileInfo.format == null) {
                                dstBuilder.format(ATTR_FORMAT_VALUE_DITA);
                            }
                            final FileInfo dstFileInfo = dstBuilder.build();
                            job.add(dstFileInfo);
                        }
                    }
                }
                i++;
            }
        }
    }
}

From source file:org.eclipse.smila.search.datadictionary.DataDictionaryController.java

/**
 * Adds the index./*from   www.j  a  v a  2 s .  c o m*/
 * 
 * @param indexTypeName
 *          the index type name
 * 
 * @throws DataDictionaryException
 *           the data dictionary exception
 */
public static void addIndex(final String indexTypeName) throws DataDictionaryException {
    synchronized (dd) {
        ensureLoaded();
        final Enumeration<DIndex> indiceTypes = _dataDictionaryTypes.getIndices();
        while (indiceTypes.hasMoreElements()) {
            final DIndex dIndexType = indiceTypes.nextElement();
            if (dIndexType.getName().equalsIgnoreCase(indexTypeName)) {
                // CLONE
                // encode to XML
                final Document doc = XMLUtils.getDocument();
                final Element rootElement = doc.createElementNS(DAnyFinderDataDictionaryCodec.NS,
                        "AnyFinderDataDictionary");
                Attr attr = null;
                attr = doc.createAttribute("xmlns:xsi");
                attr.setValue("http://www.w3.org/2001/XMLSchema-instance");
                rootElement.setAttributeNode(attr);
                attr = doc.createAttribute("xsi:schemaLocation");
                attr.setValue(DAnyFinderDataDictionaryCodec.NS + " ../xml/AnyFinderDataDictionary.xsd");
                rootElement.setAttributeNode(attr);
                doc.appendChild(rootElement);
                final DIndex dIndex;
                try {
                    DIndexCodec.encode(dIndexType, rootElement);
                } catch (final DDException e) {
                    throw new DataDictionaryException(e);
                }
                final Document doc2;
                try {
                    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    XMLUtils.stream(doc.getDocumentElement(), true, "UTF-8", bos);
                    doc2 = XMLUtils.parse(bos.toByteArray(), true);
                } catch (final XMLUtilsException e) {
                    throw new DataDictionaryException(e);
                }
                final DAnyFinderDataDictionary dictionary;
                // decode again to DIndex
                try {
                    dictionary = DAnyFinderDataDictionaryCodec.decode(doc2.getDocumentElement());
                } catch (final DDException e) {
                    throw new DataDictionaryException(e);
                }
                dIndex = dictionary.getIndex(dIndexType.getName());
                addIndex(dIndex);
                return;
            }
        }
    }
    throw new DataDictionaryException(String.format("Index type [%s] was not found!", indexTypeName));
}

From source file:org.exoplatform.cms.common.CommonUtils.java

static public File getXMLFile(ByteArrayOutputStream bos, String appName, String objectType, Date createDate,
        String fileName) throws Exception {
    byte[] byteData = bos.toByteArray();

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputStream is = new ByteArrayInputStream(byteData);
    Document document = docBuilder.parse(is);

    org.w3c.dom.Attr namespace = document.createAttribute("xmlns:exoks");
    namespace.setValue("http://www.exoplatform.com/exoks/2.0");
    document.getFirstChild().getAttributes().setNamedItem(namespace);

    org.w3c.dom.Attr attName = document.createAttribute("exoks:applicationName");
    attName.setValue(appName);/*  w  w  w .  j  a v  a 2 s.  c  o m*/
    document.getFirstChild().getAttributes().setNamedItem(attName);

    org.w3c.dom.Attr dataType = document.createAttribute("exoks:objectType");
    dataType.setValue(objectType);
    document.getFirstChild().getAttributes().setNamedItem(dataType);

    org.w3c.dom.Attr exportDate = document.createAttribute("exoks:exportDate");
    exportDate.setValue(createDate.toString());
    document.getFirstChild().getAttributes().setNamedItem(exportDate);

    org.w3c.dom.Attr checkSum = document.createAttribute("exoks:checkSum");
    checkSum.setValue(generateCheckSum(byteData));
    document.getFirstChild().getAttributes().setNamedItem(checkSum);

    DOMSource source = new DOMSource(document.getFirstChild());

    File file = new File(fileName + ".xml");
    file.deleteOnExit();
    file.createNewFile();
    StreamResult result = new StreamResult(file);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(source, result);
    return file;
}

From source file:org.firesoa.common.schema.DOMInitializer.java

protected static void createAttribute(Document doc, Element elem, XmlSchemaAttributeGroupMember attrMember) {

    if (attrMember instanceof XmlSchemaAttribute) {
        XmlSchemaAttribute attrSchema = (XmlSchemaAttribute) attrMember;

        XmlSchemaForm attrForm = attrSchema.getForm();

        Attr attr = null;
        QName attrSchemaQName = attrSchema.getQName();
        if (XmlSchemaForm.QUALIFIED.equals(attrForm)) {
            String attrQualifiedName = getQualifiedName(doc, attrSchemaQName);
            attr = doc.createAttributeNS(attrSchemaQName.getNamespaceURI(), attrQualifiedName);
        } else {/* ww  w.  ja  va2  s.c  om*/
            attr = doc.createAttribute(attrSchema.getName());
        }

        elem.setAttributeNode(attr);
        String value = "";
        if (!StringUtils.isEmpty(attrSchema.getFixedValue())) {
            value = attrSchema.getFixedValue();
        } else if (!StringUtils.isEmpty(attrSchema.getDefaultValue())) {
            value = attrSchema.getDefaultValue();
        }
        if (!StringUtils.isEmpty(value)) {
            attr.setValue(value);
        }
    } else if (attrMember instanceof XmlSchemaAttributeGroupRef) {
        XmlSchemaAttributeGroupRef attrGroupRef = (XmlSchemaAttributeGroupRef) attrMember;
        List<XmlSchemaAttributeGroupMember> groupMembers = attrGroupRef.getRef().getTarget().getAttributes();
        for (XmlSchemaAttributeGroupMember groupMember : groupMembers) {
            createAttribute(doc, elem, groupMember);
        }

    } else if (attrMember instanceof XmlSchemaAttributeGroup) {
        XmlSchemaAttributeGroup attrGroup = (XmlSchemaAttributeGroup) attrMember;
        List<XmlSchemaAttributeGroupMember> groupMembers = attrGroup.getAttributes();
        for (XmlSchemaAttributeGroupMember groupMember : groupMembers) {
            createAttribute(doc, elem, groupMember);
        }
    }

}

From source file:org.firesoa.common.schema.DOMInitializer.java

private static String getQualifiedName(Document doc, QName qName) {
    Element rootElement = (Element) doc.getDocumentElement();

    if (rootElement != null && !equalStrings(qName.getNamespaceURI(), rootElement.getNamespaceURI())) {
        //         Attr attrTmp = rootElement.getAttributeNodeNS(Constants.XMLNS_ATTRIBUTE_NS_URI, "ns0");
        //         System.out.println("===========found attrTmp=="+attrTmp);

        String nsPrefix = null;//from  w  w  w .j a v  a 2  s  .co m
        nsPrefix = rootElement.lookupPrefix(qName.getNamespaceURI());
        if (nsPrefix == null || nsPrefix.trim().equals("")) {
            int nsNumber = 1;
            NamedNodeMap attrMap = rootElement.getAttributes();
            int length = attrMap.getLength();

            for (int i = 0; i < length; i++) {
                Attr attr = (Attr) attrMap.item(i);
                String name = attr.getName();
                if (name.startsWith(Constants.XMLNS_ATTRIBUTE)) {
                    if (attr.getValue().equals(qName.getNamespaceURI())) {
                        // Namespace?
                        nsPrefix = attr.getLocalName();
                        break;
                    }
                    nsNumber++;
                }
            }
            if (nsPrefix == null) {
                nsPrefix = "ns" + nsNumber;
            }
        }

        Attr attr = doc.createAttributeNS(Constants.XMLNS_ATTRIBUTE_NS_URI,
                Constants.XMLNS_ATTRIBUTE + ":" + nsPrefix);
        attr.setValue(qName.getNamespaceURI());
        rootElement.setAttributeNode(attr);

        return nsPrefix + ":" + qName.getLocalPart();
    } else {
        return "ns0:" + qName.getLocalPart();
    }

}

From source file:org.globus.wsrf.tools.wsdl.TypesProcessor.java

private Element getSchema() throws Exception {
    Types types = this.definition.getTypes();
    if (types == null) {
        types = definition.createTypes();
        this.definition.setTypes(types);
    }/*from  w ww. j  a  v a2 s  .  c om*/
    Element schema = null;
    List elementList = types.getExtensibilityElements();
    if (elementList.isEmpty()) {
        UnknownExtensibilityElement extensibilityElement = new UnknownExtensibilityElement();

        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        schema = doc.createElementNS(XSD_NS, "xsd:schema");
        Attr nameSpace = doc.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsd");
        nameSpace.setValue(XSD_NS);
        schema.setAttributeNode(nameSpace);
        nameSpace = doc.createAttribute("targetNamespace");
        nameSpace.setValue(definition.getTargetNamespace());
        schema.setAttributeNode(nameSpace);
        schema.appendChild(doc.createTextNode("\n      "));
        doc.appendChild(schema);
        extensibilityElement.setElement(schema);
        types.addExtensibilityElement(extensibilityElement);
    } else {
        schema = ((UnknownExtensibilityElement) elementList.get(0)).getElement();
    }
    return schema;
}

From source file:org.globus.wsrf.tools.wsdl.TypesProcessor.java

public void addResourceProperties(QName portTypeName, Map resourcePropertyElements, Map schemaDocumentLocations)
        throws Exception {
    logger.debug("Starting to build resource properties element");
    PortType portType = this.getPortType(portTypeName);

    QName resourceProperties = (QName) portType.getExtensionAttribute(RP);

    addPrefix(WSRP_NS, "wsrp");

    Element schema = getSchema();
    Document doc = schema.getOwnerDocument();
    String schemaPrefix = "";
    if (schema.getPrefix() != null) {
        schemaPrefix = schema.getPrefix() + ":";
    }//  www  .  ja va  2  s.c  om

    Element properties = null;
    if (resourceProperties == null) {
        resourceProperties = new QName(portType.getQName().getLocalPart() + "GTWSDLResourceProperties");
        portType.setExtensionAttribute(RP, resourceProperties);
        properties = doc.createElementNS(XSD_NS, schemaPrefix + "element");
        properties.setAttribute("name", resourceProperties.getLocalPart());
        properties.appendChild(doc.createTextNode("\n        "));
        schema.appendChild(properties);
        schema.appendChild(doc.createTextNode("\n    "));
    } else {
        NodeList elementNodes = schema.getElementsByTagNameNS(XSD_NS, "element");
        String name;
        Element element;
        for (int i = 0; i < elementNodes.getLength(); i++) {
            element = (Element) elementNodes.item(i);
            name = element.getAttribute("name");
            if (name != null && XmlUtils.getFullQNameFromString(name, element).getLocalPart()
                    .equals(resourceProperties.getLocalPart())) {
                properties = element;
                break;
            }
        }

        if (properties == null) {
            throw new Exception(
                    "Unable to find '" + resourceProperties + "' element in WSDL schema section of '"
                            + this.definition.getDocumentBaseURI() + "' document.");
        }
    }
    String type = properties.getAttribute("type");
    NodeList complexTypeElements;
    Element complexType = null;

    if (type != null && !type.equals("")) {
        complexTypeElements = schema.getElementsByTagNameNS(XSD_NS, "complexType");
        Element currentType;
        QName currentName;
        QName typeName = XmlUtils.getFullQNameFromString(type, properties);
        for (int i = 0; i < complexTypeElements.getLength(); i++) {
            currentType = (Element) complexTypeElements.item(i);
            currentName = XmlUtils.getFullQNameFromString(currentType.getAttribute("name"), currentType);
            if (currentName.getLocalPart().equals(typeName.getLocalPart())) {
                complexType = currentType;
                break;
            }
        }
        if (complexType == null) {
            throw new Exception("Unable to find type entry for '" + resourceProperties + "' element");
        }
    } else {
        complexTypeElements = properties.getElementsByTagNameNS(XSD_NS, "complexType");
        if (complexTypeElements.getLength() > 0) {
            complexType = (Element) complexTypeElements.item(0);
        } else {
            complexType = doc.createElementNS(XSD_NS, schemaPrefix + "complexType");
            complexType.appendChild(doc.createTextNode("\n          "));
            properties.appendChild(complexType);
            properties.appendChild(doc.createTextNode("\n      "));
        }
    }

    NodeList sequenceElements = complexType.getElementsByTagNameNS(XSD_NS, "sequence");
    Element sequence;
    if (sequenceElements.getLength() > 0) {
        sequence = (Element) sequenceElements.item(0);
    } else {
        sequence = doc.createElementNS(XSD_NS, schemaPrefix + "sequence");
        complexType.appendChild(sequence);
        complexType.appendChild(doc.createTextNode("\n        "));
    }

    Collection resourcePropertiesList = resourcePropertyElements.values();
    Iterator elementIterator = resourcePropertiesList.iterator();
    int nsCounter = 0;

    while (elementIterator.hasNext()) {
        sequence.appendChild(doc.createTextNode("\n            "));
        Element resourcePropertyElement = doc.createElementNS(XSD_NS, schemaPrefix + "element");
        XSParticle particle = (XSParticle) elementIterator.next();
        XSElementDeclaration element = (XSElementDeclaration) particle.getTerm();
        String prefix = XmlUtils.getPrefix(element.getNamespace(), schema);

        addSchemaDefinitions(element, schemaDocumentLocations, schema);

        if (prefix == null) {
            prefix = "rpns" + String.valueOf(nsCounter++);
            Attr nameSpace = doc.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix);
            nameSpace.setValue(element.getNamespace());
            schema.setAttributeNode(nameSpace);
        }

        resourcePropertyElement.setAttribute("ref", prefix + ":" + element.getName());
        resourcePropertyElement.setAttribute("minOccurs", String.valueOf(particle.getMinOccurs()));
        if (particle.getMaxOccursUnbounded()) {
            resourcePropertyElement.setAttribute("maxOccurs", String.valueOf("unbounded"));
        } else {
            resourcePropertyElement.setAttribute("maxOccurs", String.valueOf(particle.getMaxOccurs()));
        }
        sequence.appendChild(resourcePropertyElement);
    }
    sequence.appendChild(doc.createTextNode("\n          "));
    logger.debug("Resource properties element: " + XmlUtils.getElementAsString(properties));
}