Example usage for org.w3c.dom Element setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.commonjava.maven.plugins.monolith.handler.PluginDescriptorHandler.java

@Override
protected boolean process(final FileInfo fileInfo) throws IOException {
    if (fileInfo.isFile()) {
        String entry = fileInfo.getName().replace('\\', '/');

        if (entry.startsWith("/")) {
            entry = entry.substring(1);//ww w .j av a 2  s . co m
        }

        if (PLUGIN_XML_PATH.equals(entry)) {
            logger.info("Found plugin descriptor...");
            if (doc == null) {
                logger.info("Parsing plugin descriptor.");

                try {
                    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(fileInfo.getContents());
                } catch (final SAXException e) {
                    throw new ArchiverException("Failed to parse plugin.xml file: " + e.getMessage(), e);
                } catch (final ParserConfigurationException e) {
                    throw new ArchiverException("Failed to parse plugin.xml file: " + e.getMessage(), e);
                }

                final String modifiedVersion = monolithVersioningContext.getCurrentMonolithVersion();
                if (modifiedVersion != null) {
                    final Element version = getChild(doc.getDocumentElement(), "version");
                    if (version != null && !version.getTextContent().equals(modifiedVersion)) {
                        version.setTextContent(modifiedVersion);
                    }
                }

                final Element depRoot = getChild(doc.getDocumentElement(), "dependencies");
                if (depRoot != null) {
                    final List<Element> deps = getChildren(depRoot, "dependency");
                    for (final Element dep : deps) {
                        if (!monolithVersioningContext.isMonolith(dep)) {
                            depRoot.removeChild(dep);
                        }
                    }
                }
            } else {
                logger.info("Skipping...plugin descriptor was already stored for inclusion.");
            }

            return true;
        }
    }

    return false;
}

From source file:org.dasein.cloud.azure.storage.BlobStore.java

private void commitBlocks(@Nonnull String bucket, @Nonnull String object, @Nonnull Collection<String> blockIds)
        throws InternalException, CloudException {
    String resource = bucket + "/" + object;

    TreeMap<String, String> headers = new TreeMap<String, String>();
    TreeMap<String, String> queries = new TreeMap<String, String>();

    queries.put("comp", "blocklist");

    //Create post body
    Document doc = AzureStorageMethod.createDoc();
    Element blockList = doc.createElement("BlockList");

    for (String id : blockIds) {
        Element uncommitted = doc.createElement("Uncommitted");
        uncommitted.setTextContent(id);
        blockList.appendChild(uncommitted);
    }//  ww  w.  j a v  a 2 s  .co  m
    doc.appendChild(blockList);

    AzureStorageMethod method = new AzureStorageMethod(provider);

    method.invoke(AzureStorageMethod.Storage_OPERATION_PUT, resource, queries,
            AzureStorageMethod.convertDomToString(doc), headers, true);
}

From source file:org.dspace.app.itemupdate.MetadataUtilities.java

/**
 *    Write dublin_core.xml //from   w  w w.j  a v a 2 s  .c om
 * 
 * @param docBuilder
 * @param dtomList
 * @return xml document
 * @throws ParserConfigurationException
 * @throws TransformerConfigurationException
 * @throws TransformerException
 */
public static Document writeDublinCore(DocumentBuilder docBuilder, List<DtoMetadata> dtomList)
        throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("dublin_core");
    doc.appendChild(root);

    for (DtoMetadata dtom : dtomList) {
        Element mel = doc.createElement("dcvalue");
        mel.setAttribute("element", dtom.element);
        if (dtom.qualifier == null) {
            mel.setAttribute("qualifier", "none");
        } else {
            mel.setAttribute("qualifier", dtom.qualifier);
        }

        if (StringUtils.isEmpty(dtom.language)) {
            mel.setAttribute("language", "en");
        } else {
            mel.setAttribute("language", dtom.language);
        }
        mel.setTextContent(dtom.value);
        root.appendChild(mel);
    }

    return doc;
}

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   w  ww  .  j a v  a 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.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId,
        String dimensionXPath, List<String> values) {

    XPathFactory xpf = XPathFactory.newInstance();

    try {/*from  www. j  av  a  2  s  .c o m*/
        // load and parse the profile
        DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId);
        Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId))));
        // check if the element exists
        Node node = null;
        Node parent = null;
        XPath xp = xpf.newXPath();
        for (Iterator<String> it = values.iterator(); it.hasNext();) {
            String value = it.next();
            // look if value already exists
            node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE);
            // if value exists, value can be discarded
            if (node != null) {
                // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary
                parent = node.getParentNode();
                it.remove();
            }
        }
        if (values.isEmpty())
            return; // nothing left to do
        String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/"));
        // find path to parent
        if (parent == null) {
            String tmpPath = parentPath;
            while (parent == null) {
                tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/"));
                parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
            }
            parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null);
        }
        String tag = dimensionXPath.substring(parentPath.length() + 1);
        for (String value : values) {
            Element el = doc.createElement(tag);
            el.setTextContent(value);
            parent.appendChild(el);
        }

        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        trans.transform(new DOMSource(doc), result);
        writer.close();
        String xml = writer.toString();
        logger.debug(xml);
        storeProfile(tenantId, itemId, itemTypeId, xml, true);

    } catch (Exception e) {
        logger.error("Error inserting Multi Dimension: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.eclipse.buckminster.jnlp.componentinfo.cloudsmith.ComponentInfoProvider.java

private Element addOutline(IOutline outline) {
    Element tr = null;//from   w w w . j  a v a  2s. c  o m

    if (outline.getType() == OutlineType.RSS || outline.getType() == OutlineType.ATOM) {
        tr = m_xml.createElement(TAG_TR);

        Element td = m_xml.createElement(TAG_TD);
        tr.appendChild(td);
        td.setAttribute(ATTR_CLASS, CELL_1);
        td.setTextContent(outline.getText());

        td = m_xml.createElement(TAG_TD);
        tr.appendChild(td);
        td.setAttribute(ATTR_CLASS, CELL_N);
        String string = UiUtils.trimmedValue(outline.getDescription());
        td.setTextContent(string == null ? NBSP_VALUE : string);

        td = m_xml.createElement(TAG_TD);
        tr.appendChild(td);
        td.setAttribute(ATTR_CLASS, CELL_N);
        Element a = m_xml.createElement(TAG_A);
        td.appendChild(a);
        a.setAttribute(ATTR_HREF, outline.getXmlUrl().toString());
        a.setAttribute(ATTR_CLASS, CLASS_BLUE_LINK);
        a.setAttribute(ATTR_TITLE, outline.getDescription());
        Element rssImg = m_xml.createElement(TAG_IMG);
        a.appendChild(rssImg);
        rssImg.setAttribute(ATTR_ALT, "rss icon");
        rssImg.setAttribute(ATTR_SRC, IMG_FOLDER + IPath.SEPARATOR + IMG_RSS);

        td = m_xml.createElement(TAG_TD);
        tr.appendChild(td);
        td.setAttribute(ATTR_CLASS, CELL_N);
        a = m_xml.createElement(TAG_A);
        td.appendChild(a);
        a.setAttribute(ATTR_HREF, outline.getXmlUrl().toString());
        a.setAttribute(ATTR_CLASS, CLASS_BLUE_LINK);
        a.setAttribute(ATTR_TITLE, outline.getDescription());
        Text linkText = m_xml.createTextNode("subscribe");
        a.appendChild(linkText);
    }

    return tr;
}

From source file:org.eclipse.buckminster.jnlp.componentinfo.cloudsmith.ComponentInfoProvider.java

private void setAttribute(String nodeId, String attibuteName, String propertyName, boolean base64) {
    Element element = m_xml.getElementById(nodeId);
    if (element != null) {
        String value = m_properties.get(propertyName);
        if (base64)
            try {
                if (value != null && value.length() > 0)
                    value = new String(Base64.decodeBase64(value.getBytes()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                value = null;//from   w  w w.j  a v  a2  s .co  m
                e.printStackTrace();
            }

        if (attibuteName == null)
            element.setTextContent(value);
        else
            element.setAttribute(attibuteName, value);
    }
}

From source file:org.eclipse.ecr.common.xmap.XMLBuilder.java

public static void fillField(Element element, String value, String attribute) {
    if (attribute != null) {
        element.setAttribute(attribute, value);
    } else {/*from w ww .  ja  va  2 s  .c  om*/
        element.setTextContent(value);
    }
}

From source file:org.eclipse.ecr.runtime.model.impl.ComponentRegistrySerializer.java

public static Document toDocument() throws Exception {
    ComponentManagerImpl mgr = (ComponentManagerImpl) Framework.getRuntime().getComponentManager();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().newDocument();
    Element root = doc.createElement("components");
    doc.appendChild(root);/*from  w w w  .jav a 2s.c o m*/

    for (RegistrationInfo ri : mgr.getRegistrations()) {
        ComponentName name = ri.getName();
        if (name == null) {
            log.error("BUG: Found component with null name");
            continue;
        }

        Element comp = doc.createElement("component");
        comp.setAttribute("name", name.getName());
        String impl = ri.getImplementation();
        if (impl != null && impl.length() > 0) {
            comp.setAttribute("class", impl);
        }
        String bundle = ri.getBundle();
        if (bundle == null) {
            bundle = ri.getContext().getBundle().getSymbolicName();
        }
        if (bundle != null) {
            comp.setAttribute("bundle", bundle);
        }
        Version v = ri.getVersion();
        if (v != null) {
            comp.setAttribute("version", v.toString());
        }
        root.appendChild(comp);

        // write source if known
        String src = getComponentSrc(ri);
        if (src != null) {
            comp.setAttribute("src", src);
        }

        // write documentation
        String docText = ri.getDocumentation();
        if (docText != null) {
            docText = docText.trim();
            Element docu = doc.createElement("documentation");
            docu.setTextContent(docText);
            comp.appendChild(docu);
        }

        // write services
        String[] services = ri.getProvidedServiceNames();
        if (services != null && services.length > 0) {
            Element svcsEl = doc.createElement("services");
            for (String service : services) {
                Element svcEl = doc.createElement("service");
                svcEl.setAttribute("class", service);
                svcsEl.appendChild(svcEl);
            }
            comp.appendChild(svcsEl);
        }

        // write extension points
        ExtensionPoint[] xps = ri.getExtensionPoints();
        if (xps != null && xps.length > 0) {
            Element xpsEl = doc.createElement("extension-points");
            for (ExtensionPoint xp : xps) {
                Element xpEl = doc.createElement("extension-point");
                xpEl.setAttribute("name", xp.getName());
                docText = xp.getDocumentation();
                if (docText != null) {
                    xpEl.setTextContent(docText.trim());
                }
                xpsEl.appendChild(xpEl);
            }
            comp.appendChild(xpsEl);
        }
    }
    return doc;
}

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  ava 2 s  .c o 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 {

    }
}