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:ch.entwine.weblounge.bridge.oaipmh.util.XmlGen.java

protected Node $aSome(final String name, final Option<String> value) {
    return value.fold(new Option.Match<String, Node>() {
        public Node some(String value) {
            Attr a = document.createAttribute(name);
            a.setValue(value);
            return a;
        }//  ww  w  .j  a  v  a 2 s . co  m

        public Node none() {
            return nodeZero();
        }
    });
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void execute0(Document document, MessageContext msgCtxt) throws Exception {
    String xpath = getXpath(msgCtxt);
    XPathEvaluator xpe = getXpe(msgCtxt);
    NodeList nodes = (NodeList) xpe.evaluate(xpath, document, XPathConstants.NODESET);
    validate(nodes);//from ww w  .j a  va 2  s  .  com
    EditAction action = getAction(msgCtxt);
    if (action == EditAction.Remove) {
        remove(nodes);
        return;
    }

    short newNodeType = getNewNodeType(msgCtxt);
    String text = getNewNodeText(msgCtxt);
    Node newNode = null;
    switch (newNodeType) {
    case Node.ELEMENT_NODE:
        // Create a duplicate node and transfer ownership of the
        // new node into the destination document.
        Document temp = XmlUtils.parseXml(text);
        newNode = document.importNode(temp.getDocumentElement(), true);
        break;
    case Node.ATTRIBUTE_NODE:
        if (text.indexOf("=") < 1) {
            throw new IllegalStateException("attribute spec must be name=value");
        }
        String[] parts = text.split("=", 2);
        if (parts.length != 2)
            throw new IllegalStateException("attribute spec must be name=value");
        Attr attr = document.createAttribute(parts[0]);
        attr.setValue(parts[1]);
        newNode = attr;
        break;
    case Node.TEXT_NODE:
        newNode = document.createTextNode(text);
        break;
    }
    switch (action) {
    case InsertBefore:
        insertBefore(nodes, newNode, newNodeType);
        break;
    case Append:
        append(nodes, newNode, newNodeType);
        break;
    case Replace:
        replace(nodes, newNode, newNodeType);
        break;
    }
}

From source file:com.hydroLibCreator.action.Creator.java

private void buildDrumKitXML() {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*from ww  w. j av a 2  s.co  m*/
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException parserException) {
        parserException.printStackTrace();
    }

    Element drumkit_info = document.createElement("drumkit_info");
    document.appendChild(drumkit_info);

    Attr xmlns = document.createAttribute("xmlns");
    xmlns.setValue("http://www.hydrogen-music.org/drumkit");

    Attr xmlns_xsi = document.createAttribute("xmlns:xsi");
    xmlns_xsi.setValue("http://www.w3.org/2001/XMLSchema-instance");

    drumkit_info.setAttributeNode(xmlns);
    drumkit_info.setAttributeNode(xmlns_xsi);

    Node nameNode = createNameNode(document);
    drumkit_info.appendChild(nameNode);

    Node authorNode = createAuthorNode(document);
    drumkit_info.appendChild(authorNode);

    Node infoNode = createInfoNode(document);
    drumkit_info.appendChild(infoNode);

    Node licenseNode = createLicenseNode(document);
    drumkit_info.appendChild(licenseNode);

    Node instrumentListNode = createInstrumentListNode(document);
    drumkit_info.appendChild(instrumentListNode);

    // write the XML document to disk
    try {

        // create DOMSource for source XML document
        Source xmlSource = new DOMSource(document);

        // create StreamResult for transformation result
        Result result = new StreamResult(new FileOutputStream(destinationPath + "/drumkit.xml"));

        // create TransformerFactory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create Transformer for transformation
        Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        // transform and deliver content to client
        transformer.transform(xmlSource, result);
    }

    // handle exception creating TransformerFactory
    catch (TransformerFactoryConfigurationError factoryError) {
        System.err.println("Error creating " + "TransformerFactory");
        factoryError.printStackTrace();
    } catch (TransformerException transformerError) {
        System.err.println("Error transforming document");
        transformerError.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

From source file:it.unibas.spicy.persistence.xml.operators.ExportXSD.java

private void processRoot(INode root, Document document) {
    Element schema = document.createElementNS(XSD_NS, PREFIX + "schema");
    document.appendChild(schema);//from   w  w w . ja  va  2 s.c o  m
    Attr elementFormDefault = document.createAttribute("elementFormDefault");
    elementFormDefault.setValue("qualified");
    schema.setAttributeNode(elementFormDefault);
}

From source file:org.gvnix.dynamic.configuration.roo.addon.config.XpathAttributesDynamicConfiguration.java

/**
 * {@inheritDoc}/*from   w w  w.  jav a 2  s . c  om*/
 */
@Override
public void write(DynPropertyList dynProps) {

    // Get the XML file path
    MutableFile file = getFile();
    if (file != null) {

        // Obtain document representation of the XML file
        Document doc = getXmlDocument(file);

        // Update the root element property values with dynamic properties
        for (DynProperty dynProp : dynProps) {

            // Obtain the element related to this dynamic property
            String xpath = getXpath() + XPATH_ARRAY_PREFIX + XPATH_ATTRIBUTE_PREFIX + getKey()
                    + XPATH_EQUALS_SYMBOL + XPATH_STRING_DELIMITER + getKeyValue(dynProp.getKey())
                    + XPATH_STRING_DELIMITER + XPATH_ARRAY_SUFIX;
            Element elem = XmlUtils.findFirstElement(xpath, doc.getDocumentElement());
            if (elem == null) {

                logger.log(Level.WARNING, "Element " + xpath + " to set attribute value not exists on file");
            } else {

                // If value attribute exists, set new value
                Attr attr = elem.getAttributeNode(getValue());
                if (attr == null) {

                    logger.log(Level.WARNING,
                            "Element attribute " + xpath + " to set value not exists on file");
                } else {

                    attr.setValue(dynProp.getValue());
                }
            }
        }

        // Update the XML file
        XmlUtils.writeXml(file.getOutputStream(), doc);

    } else if (!dynProps.isEmpty()) {

        logger.log(Level.WARNING,
                "File " + getFilePath() + " not exists and there are dynamic properties to set it");
    }
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

public Document generateHibernateConfiguration(RDBMSDataSource rdbmsDataSource)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//  www. j a  va2  s  .c  o m
    factory.setExpandEntityReferences(false);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    documentBuilder.setEntityResolver(HibernateStorage.ENTITY_RESOLVER);
    Document document = documentBuilder
            .parse(DefaultStorageClassLoader.class.getResourceAsStream(HIBERNATE_CONFIG_TEMPLATE));
    String connectionUrl = rdbmsDataSource.getConnectionURL();
    String userName = rdbmsDataSource.getUserName();
    String driverClass = rdbmsDataSource.getDriverClassName();
    RDBMSDataSource.DataSourceDialect dialectType = rdbmsDataSource.getDialectName();
    String dialect = getDialect(dialectType);
    String password = rdbmsDataSource.getPassword();
    String indexBase = rdbmsDataSource.getIndexDirectory();
    int connectionPoolMinSize = rdbmsDataSource.getConnectionPoolMinSize();
    int connectionPoolMaxSize = rdbmsDataSource.getConnectionPoolMaxSize();
    if (connectionPoolMaxSize == 0) {
        LOGGER.info("No value provided for property connectionPoolMaxSize of datasource " //$NON-NLS-1$
                + rdbmsDataSource.getName() + ". Using default value: " //$NON-NLS-1$
                + RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT);
        connectionPoolMaxSize = RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT;
    }

    setPropertyValue(document, "hibernate.connection.url", connectionUrl); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.username", userName); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.driver_class", driverClass); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dialect", dialect); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.password", password); //$NON-NLS-1$
    // Sets up DBCP pool features
    setPropertyValue(document, "hibernate.dbcp.initialSize", String.valueOf(connectionPoolMinSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxActive", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxIdle", String.valueOf(10)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxTotal", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxWaitMillis", "60000"); //$NON-NLS-1$ //$NON-NLS-2$

    Node sessionFactoryElement = document.getElementsByTagName("session-factory").item(0); //$NON-NLS-1$
    if (rdbmsDataSource.supportFullText()) {
        /*
        <property name="hibernate.search.default.directory_provider" value="filesystem"/>
        <property name="hibernate.search.default.indexBase" value="/var/lucene/indexes"/>
         */
        addProperty(document, sessionFactoryElement, "hibernate.search.default.directory_provider", //$NON-NLS-1$
                "filesystem"); //$NON-NLS-1$
        addProperty(document, sessionFactoryElement, "hibernate.search.default.indexBase", //$NON-NLS-1$
                indexBase + '/' + storageName);
        addProperty(document, sessionFactoryElement, "hibernate.search.default.sourceBase", //$NON-NLS-1$
                indexBase + '/' + storageName);
        addProperty(document, sessionFactoryElement, "hibernate.search.default.source", ""); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.search.default.exclusive_index_use", "false"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.search.lucene_version", "LUCENE_CURRENT"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        addProperty(document, sessionFactoryElement, "hibernate.search.autoregister_listeners", "false"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (dataSource.getCacheDirectory() != null && !dataSource.getCacheDirectory().isEmpty()) {
        /*
        <!-- Second level cache -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
        <property name="hibernate.cache.use_query_cache">true</property>
        <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
         */
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.cache.provider_class", //$NON-NLS-1$
                "net.sf.ehcache.hibernate.EhCacheProvider"); //$NON-NLS-1$
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_query_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "net.sf.ehcache.configurationResourceName", "ehcache.xml"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(
                    "Hibernate configuration does not define second level cache extensions due to datasource configuration."); //$NON-NLS-1$
        }
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "false"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    // Override default configuration with values from configuration
    Map<String, String> advancedProperties = rdbmsDataSource.getAdvancedProperties();
    for (Map.Entry<String, String> currentAdvancedProperty : advancedProperties.entrySet()) {
        setPropertyValue(document, currentAdvancedProperty.getKey(), currentAdvancedProperty.getValue());
    }
    // Order of elements highly matters and mapping shall be declared after <property/> and before <event/>.
    Element mapping = document.createElement("mapping"); //$NON-NLS-1$
    Attr resource = document.createAttribute("resource"); //$NON-NLS-1$
    resource.setValue(HIBERNATE_MAPPING);
    mapping.getAttributes().setNamedItem(resource);
    sessionFactoryElement.appendChild(mapping);

    if (rdbmsDataSource.supportFullText()) {
        addEvent(document, sessionFactoryElement, "post-update", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
        addEvent(document, sessionFactoryElement, "post-insert", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
        addEvent(document, sessionFactoryElement, "post-delete", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Hibernate configuration does not define full text extensions due to datasource configuration."); //$NON-NLS-1$
    }

    return document;
}

From source file:de.interactive_instruments.ShapeChange.Target.Metadata.ApplicationSchemaMetadata.java

/** Add attribute to an element */
protected void addAttribute(Element e, String name, String value) {
    Attr att = document.createAttribute(name);
    att.setValue(value);
    e.setAttributeNode(att);//from   w w w.j  a  v  a 2  s  .c  o m
}

From source file:com.marklogic.dom.ElementImpl.java

protected Node cloneNode(Document doc, boolean deep) {
    Element elem = doc.createElementNS(getNamespaceURI(), getTagName());
    elem.setPrefix(getPrefix());/* ww w. j  a va2  s.  c om*/

    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (attr instanceof AttrImpl) {
            elem.setAttributeNode((Attr) ((AttrImpl) attr).cloneNode(doc, deep));
        } else {
            // ns decl, stored as Java DOM Attr
            // uri of xmlns is "http://www.w3.org/2000/xmlns/"
            Attr clonedAttr = doc.createAttributeNS("http://www.w3.org/2000/xmlns/", attr.getName());
            clonedAttr.setValue(attr.getValue());
            elem.setAttributeNode(clonedAttr);
        }
    }

    if (deep) {
        // clone children
        NodeList list = getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            NodeImpl n = (NodeImpl) list.item(i);
            Node c = n.cloneNode(doc, true);
            elem.appendChild(c);
        }
    }
    return elem;
}

From source file:com.amalto.core.history.UniqueIdTransformer.java

private void _addIds(org.w3c.dom.Document document, Element element, Stack<Integer> levels) {
    NamedNodeMap attributes = element.getAttributes();
    Attr id = document.createAttribute(ID_ATTRIBUTE_NAME);

    int thisElementId = levels.pop() + 1;
    StringBuilder builder;/*from w ww.  j a v  a 2  s .  com*/
    {
        builder = new StringBuilder();
        for (Integer level : levels) {
            builder.append(level);
        }
    }
    String prefix = builder.toString().isEmpty() ? StringUtils.EMPTY : builder.toString() + '-';
    id.setValue(prefix + element.getNodeName() + '-' + thisElementId);
    attributes.setNamedItem(id);

    levels.push(thisElementId);
    {
        levels.push(0);
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element child = (Element) children.item(i);
                _addIds(document, child, levels);
            }
        }
        levels.pop();
    }
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Performas any pending activity against an element to finalize it. In this
 * case, it adds any pending attributes needing namespace mapping.
 * // w w w.j a v a 2s . c  om
 * Also if the node has a namespace attached, it recreates the node with
 * specific URI.
 */
public void finalizeElement() {
    // Add all remaining attributes
    for (String col_name : pendingAttributes.keySet()) {
        String value = pendingAttributes.get(col_name);
        int cIdx = col_name.indexOf(':');
        String ns = col_name.substring(0, cIdx);
        String nsURI = nsMap.get(ns);
        if (nsURI == null)
            nsURI = generalNSURI;
        Attr attr = doc.createAttributeNS(nsURI, col_name.substring(cIdx + 1));
        attr.setPrefix(ns);
        attr.setValue(value);
        ((Element) cur_element).setAttributeNodeNS(attr);
    }
    // If the element had a namespace prefix, it has to be recreated.
    if (!currentElementNS.equals("") && !doc.getDocumentElement().equals(cur_element)) {
        Node parent = cur_element.getParentNode();
        Element cur_ele = (Element) parent.removeChild(cur_element);
        String node_name = cur_ele.getNodeName();
        String nsURI = nsMap.get(currentElementNS);
        if (nsURI == null)
            nsURI = generalNSURI;
        Element new_node = doc.createElementNS(nsURI, currentElementNS + ":" + node_name);
        parent.appendChild(new_node);
        // Add all attributes
        NamedNodeMap attrs = cur_ele.getAttributes();
        while (attrs.getLength() > 0) {
            Attr attr = (Attr) attrs.item(0);
            cur_ele.removeAttributeNode(attr);
            nsURI = attr.getNamespaceURI();
            new_node.setAttributeNodeNS(attr);
        }
        // Add all CData sections
        NodeList childNodes = cur_ele.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() == Node.CDATA_SECTION_NODE)
                new_node.appendChild(node);
        }
        cur_element = new_node;
    }
    pendingAttributes = new Hashtable<String, String>();
}