Example usage for org.w3c.dom Element setAttributeNS

List of usage examples for org.w3c.dom Element setAttributeNS

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttributeNS.

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:org.chiba.xml.xforms.Container.java

/**
 * Allows to set or overwrite a submission's action URI.
 * <p/>//from  w w  w .java2 s.co m
 * This method can be used to provide a parametrized URI to the Submission Driver which handles the submission's
 * action URI.
 *
 * @param id        the id of the submission.
 * @param actionURI the action URI.
 * @throws XFormsException if no document is present or the specified submission does not exist.
 * @see org.chiba.xml.xforms.connector.SubmissionHandler
 */
public void setSubmissionURI(String id, String actionURI) throws XFormsException {
    Element submissionElement = findElement(XFormsConstants.SUBMISSION, id);

    if (submissionElement == null) {
        throw new XFormsException("submission element '" + id + "' not found");
    }

    String xformsPrefix = NamespaceCtx.getPrefix(submissionElement, NamespaceCtx.XFORMS_NS);
    submissionElement.setAttributeNS(NamespaceCtx.XFORMS_NS, xformsPrefix + ":action", actionURI);
}

From source file:org.chiba.xml.xforms.core.Model.java

/**
 * adds a new instance to this model.//  w  w w.ja  v a  2  s  .  c o  m
 *
 * @param id the optional instance id.
 * @return the new instance.
 */
public Instance addInstance(String id) throws XFormsException {
    // create instance node
    Element instanceNode = this.element.getOwnerDocument().createElementNS(NamespaceConstants.XFORMS_NS,
            xformsPrefix + ":" + INSTANCE);

    // ensure id
    String realId = id;
    if (realId == null || realId.length() == 0) {
        realId = this.container.generateId();
    }

    instanceNode.setAttributeNS(null, "id", realId);
    instanceNode.setAttributeNS(NamespaceConstants.XMLNS_NS, "xmlns", "");
    this.element.appendChild(instanceNode);

    // create and initialize instance object
    createInstanceObject(instanceNode);
    return getInstance(id);
}

From source file:org.chiba.xml.xforms.Model.java

/**
 * adds a new instance to this model.//from w ww.ja va  2s .  co m
 *
 * @param id the optional instance id.
 * @return the new instance.
 */
public Instance addInstance(String id) throws XFormsException {
    // create instance node
    Element instanceNode = this.element.getOwnerDocument().createElementNS(NamespaceCtx.XFORMS_NS,
            xformsPrefix + ":" + INSTANCE);

    // ensure id
    String realId = id;
    if (realId == null || realId.length() == 0) {
        realId = this.container.generateId();
    }

    instanceNode.setAttributeNS(null, "id", realId);
    instanceNode.setAttributeNS(NamespaceCtx.XMLNS_NS, "xmlns", "");
    this.element.appendChild(instanceNode);

    // create and initialize instance object
    createInstanceObject(instanceNode);
    return getInstance(id);
}

From source file:org.chiba.xml.xforms.ui.Repeat.java

private void initializePrototype(Node parent, Node prototype) {
    Node copy = prototype.cloneNode(false);
    if (copy.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) copy;
        if (element.getAttributeNS(null, "id").length() == 0) {
            element.setAttributeNS(null, "id", this.container.generateId());
        }/*  w  w w . j  ava 2s .  com*/

        NodeList children = prototype.getChildNodes();
        for (int index = 0; index < children.getLength(); index++) {
            initializePrototype(element, children.item(index));
        }
    }

    parent.appendChild(copy);
}

From source file:org.chiba.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * Creates or updates the specified state attribute. If the value is
 * <code>null</code>, the attribute will be removed.
 *
 * @param element the element.//  w w w. j  a  v  a  2s . c o m
 * @param name the attribute name.
 * @param value the attribute value.
 */
public static void setStateAttribute(Element element, String name, String value) {
    if (value != null) {
        element.setAttributeNS(NamespaceConstants.CHIBA_NS, NamespaceConstants.CHIBA_PREFIX + ":" + name,
                value);
    } else {
        element.removeAttributeNS(NamespaceConstants.CHIBA_NS, name);
    }
}

From source file:org.dhatim.delivery.dom.DOMBuilder.java

public void startElement(StartElementEvent startEvent) throws SAXException {
    Element newElement = null;
    int attsCount = startEvent.atts.getLength();
    Node currentNode = (Node) nodeStack.peek();

    try {/*from w  ww  .j a v a 2  s . co m*/
        if (startEvent.uri != null && startEvent.qName != null && !startEvent.qName.equals("")) {
            newElement = ownerDocument.createElementNS(startEvent.uri.intern(), startEvent.qName);
        } else {
            newElement = ownerDocument.createElement(startEvent.localName.intern());
        }

        currentNode.appendChild(newElement);
        if (!emptyElements.contains(startEvent.qName != null ? startEvent.qName : startEvent.localName)) {
            nodeStack.push(newElement);
        }
    } catch (DOMException e) {
        logger.error("DOMException creating start element: namespaceURI=" + startEvent.uri + ", localName="
                + startEvent.localName, e);
        throw e;
    }

    for (int i = 0; i < attsCount; i++) {
        String attNamespace = startEvent.atts.getURI(i);
        String attQName = startEvent.atts.getQName(i);
        String attLocalName = startEvent.atts.getLocalName(i);
        String attValue = startEvent.atts.getValue(i);
        try {
            if (attNamespace != null && attQName != null) {
                attNamespace = attNamespace.intern();
                if (attNamespace.equals(XMLConstants.NULL_NS_URI)) {
                    if (attQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
                        attNamespace = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
                    } else if (attQName.startsWith("xml:")) {
                        attNamespace = XMLConstants.XML_NS_URI;
                    }
                }
                newElement.setAttributeNS(attNamespace, attQName, attValue);
            } else {
                newElement.setAttribute(attLocalName.intern(), attValue);
            }
        } catch (DOMException e) {
            logger.error("DOMException setting element attribute " + attLocalName + "=" + attValue
                    + "[namespaceURI=" + startEvent.uri + ", localName=" + startEvent.localName + "].", e);
            throw e;
        }
    }
}

From source file:org.dita.dost.platform.Integrator.java

/**
 * Parse plugin configuration files.//from w w w  .jav a 2 s.c om
 */
private void parsePlugin() {
    final Element root = pluginsDoc.createElement(ELEM_PLUGINS);
    pluginsDoc.appendChild(root);
    if (!descSet.isEmpty()) {
        final URI b = new File(ditaDir, RESOURCES_DIR + File.separator + "plugins.xml").toURI();
        for (final File descFile : descSet) {
            logger.debug("Read plug-in configuration " + descFile.getPath());
            final Element plugin = parseDesc(descFile);
            if (plugin != null) {
                final URI base = getRelativePath(b, descFile.toURI());
                plugin.setAttributeNS(XML_NS_URI, XML_NS_PREFIX + ":base", base.toString());
                root.appendChild(pluginsDoc.importNode(plugin, true));
            }
        }
    }
}

From source file:org.dspace.app.xmlui.aspect.submission.submit.JSONLookupSearcher.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {
    String query = request.getParameter("search");

    int start = 0;
    String startString = request.getParameter("start");
    if (StringUtils.isNotBlank(startString)) {
        int parsedStart = Integer.parseInt(startString);
        if (parsedStart >= 0) {
            start = parsedStart;/*from  ww w  . j ava  2  s .  c o  m*/
        }
    }

    try {
        int total = importService.getNbRecords(getLookupURI(), query);
        Collection<ImportRecord> records = importService.getRecords(getLookupURI(), query, start, 20);

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        org.w3c.dom.Document document = docBuilder.newDocument();

        Element rootnode = document.createElement("root");
        document.appendChild(rootnode);
        rootnode.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:i18n", WingConstants.I18N.URI);

        Element totalNode = document.createElement("total");
        totalNode.setTextContent(String.valueOf(total));
        rootnode.appendChild(totalNode);

        Element startNode = document.createElement("start");
        startNode.setTextContent(String.valueOf(start));
        rootnode.appendChild(startNode);

        Element recordsNode = document.createElement("records");
        recordsNode.setAttribute("array", "true");
        rootnode.appendChild(recordsNode);
        recordsNode.setAttribute("array", "true");

        MetadataFieldConfig importIdField = new DSpace().getServiceManager().getServiceByName("lookupID",
                MetadataFieldConfig.class);

        for (ImportRecord record : records) {
            Element recordWrapperNode = document.createElement("recordWrapper");
            recordWrapperNode.setAttribute("object", "true");
            recordsNode.appendChild(recordWrapperNode);

            Element recordNode = document.createElement("record");
            recordNode.setAttribute("namedObject", "true");

            HashMap<String, Element> metadatumValueNodes = new HashMap();

            for (MetadatumDTO metadatum : record.getValueList()) {
                if (!metadatumValueNodes.containsKey(getField(metadatum))) {
                    Element metadatumNode = document.createElement(getField(metadatum));
                    metadatumNode.setAttribute("array", "true");
                    metadatumValueNodes.put(getField(metadatum), metadatumNode);

                    if (getField(metadatum).equals(importIdField.getField())) {
                        Iterator<Item> iterator = itemService.findByMetadataField(context,
                                importIdField.getSchema(), importIdField.getElement(),
                                importIdField.getQualifier(), metadatum.getValue());

                        if (iterator.hasNext()) {
                            Element existsInDSpaceNode = document.createElement("imported");
                            existsInDSpaceNode.setTextContent("true");
                            recordNode.appendChild(existsInDSpaceNode);
                        }
                    }
                }

                Element metadatumValueNode = document.createElement("metadatumValue");
                metadatumValueNode.setTextContent(metadatum.getValue());

                metadatumValueNodes.get(getField(metadatum)).appendChild(metadatumValueNode);
            }

            for (Element element : metadatumValueNodes.values()) {
                recordNode.appendChild(element);
            }

            recordWrapperNode.appendChild(recordNode);
        }

        DOMStreamer streamer = new DOMStreamer(contentHandler, lexicalHandler);
        streamer.stream(document);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

private String buildResponseResource(List<Map<String, RioValue>> results, Map<String, PName> propNames,
        String reqUri) throws RioServiceException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from   w w  w .  j  a  v a  2s .  co m*/
    factory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element rdf = doc.createElementNS(IConstants.RDF_NAMESPACE, IConstants.RDF_TYPE_PTERM_RDF);
        doc.appendChild(rdf);

        Set<String> namespaces = namespacePrefixes.keySet();
        for (String namespace : namespaces) {
            rdf.setAttribute("xmlns:" + namespacePrefixes.get(namespace), namespace); //$NON-NLS-1$
        }
        //If there is are parameters on the request (e.g. ?oslc.where=...), create 2 subject URIs, one for the
        //results and one to describe the query.   If this query was for the queryBase itself all predicates 
        //go under the same subject.  
        //TODO: Refactor the services for all RIO artifacts to eliminate duplicated code.

        Element resultDescr = doc.createElementNS(IConstants.RDF_NAMESPACE,
                IConstants.RDF_TYPE_PTERM_DESCRIPTION);
        rdf.appendChild(resultDescr);

        //check for oslc query parameters
        String uriSplit[] = reqUri.split("\\?", 2);
        String baseUri = uriSplit[0];
        boolean isOslcQuery = false;
        if (uriSplit.length > 1)
            isOslcQuery = hasOSLCQuery(uriSplit[1]);

        resultDescr.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_ABOUT, baseUri);

        //if there are oslc query parameters, put the predicates under the query subject
        Element queryDescrElement = null;
        if (isOslcQuery) {
            queryDescrElement = doc.createElementNS(IConstants.RDF_NAMESPACE,
                    IConstants.RDF_TYPE_PTERM_DESCRIPTION);
            queryDescrElement.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_ABOUT, reqUri);
            rdf.appendChild(queryDescrElement);
        } else {
            //no oslc query parameters, everything goes under the queryBase subject
            queryDescrElement = resultDescr;
        }

        Element title = doc.createElementNS(IConstants.DCTERMS_NAMESPACE, IConstants.DCTERMS_PTERM_TITLE);
        queryDescrElement.appendChild(title);
        title.setTextContent(Messages.getString("ResourceQuery.Title"));

        Element count = doc.createElementNS(IConstants.OSLC_NAMESPACE, IConstants.OSLC_PTERM_TOTALCOUNT);
        queryDescrElement.appendChild(count);
        count.setTextContent(Integer.toString(results.size()));

        Element rdfType = doc.createElementNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_TYPE);
        rdfType.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_RESOURCE,
                IConstants.OSLC_RESPONSEINFO);
        queryDescrElement.appendChild(rdfType);

        Iterator<Map<String, RioValue>> iterator = results.iterator();
        while (iterator.hasNext()) {

            Element rdfMem = doc.createElementNS(IConstants.RDFS_NAMESPACE, IConstants.RDFS_PTERM_MEMBER);
            resultDescr.appendChild(rdfMem);
            Map<String, RioValue> map = iterator.next();
            RioValue uri = map.get("uri"); //$NON-NLS-1$
            rdfMem.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_RESOURCE, uri.stringValue());
        }

        return XmlUtils.prettyPrint(doc);

    } catch (ParserConfigurationException e) {
        throw new RioServiceException(e);
    } finally {

    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.parse.html.DOMBuilder.java

/**
 * Receive notification of the beginning of an element.
 * //w w w . ja v  a2  s  .  c  om
 * <p>
 * The Parser will invoke this method at the beginning of every element in the XML document; there will be a
 * corresponding endElement() event for every startElement() event (even when the element is empty). All of the
 * element's content will be reported, in order, before the corresponding endElement() event.
 * </p>
 * 
 * <p>
 * If the element name has a namespace prefix, the prefix will still be attached. Note that the attribute list
 * provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be
 * omitted.
 * </p>
 * 
 * @param ns
 *          The namespace of the node
 * @param localName
 *          The local part of the qualified name
 * @param name
 *          The element name.
 * @param atts
 *          The attributes attached to the element, if any.
 * 
 * @throws SAXException
 *           the SAX exception
 * 
 * @see #endElement
 * @see org.xml.sax.Attributes
 */
public void startElement(final String ns, final String localName, final String name, final Attributes atts)
        throws org.xml.sax.SAXException {

    Element elem;

    // Note that the namespace-aware call must be used to correctly
    // construct a Level 2 DOM, even for non-namespaced nodes.
    if ((null == ns) || (ns.length() == 0)) {
        elem = m_doc.createElementNS(null, name);
    } else {
        elem = m_doc.createElementNS(ns, name);
    }

    append(elem);

    try {
        final int nAtts = atts.getLength();

        if (0 != nAtts) {
            for (int i = 0; i < nAtts; i++) {

                // First handle a possible ID attribute
                if (atts.getType(i).equalsIgnoreCase("ID")) {
                    setIDAttribute(atts.getValue(i), elem);
                }

                String attrNS = atts.getURI(i);

                if ("".equals(attrNS)) {
                    attrNS = null; // DOM represents no-namespace as null
                }

                // System. out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i)
                // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i));
                // Crimson won't let us set an xmlns: attribute on the DOM.
                final String attrQName = atts.getQName(i);

                // In SAX, xmlns: attributes have an empty namespace, while in DOM they should have the xmlns namespace
                if (attrQName.startsWith("xmlns:")) {
                    attrNS = "http://www.w3.org/2000/xmlns/";
                }

                // ALWAYS use the DOM Level 2 call!
                elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
            }
        }

        // append(elem);

        m_elemStack.push(elem);

        m_currentNode = elem;

        // append(elem);
    } catch (final java.lang.Exception de) {
        if (LOG.isErrorEnabled()) {
            LOG.error(de);
        }
        throw new org.xml.sax.SAXException(de);
    }

}