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.bonitasoft.theme.builder.impl.AbstractXMLBuilder.java

/**
 * Add a child element/* w w  w.  j  a  v  a 2s.com*/
 * 
 * @param parentElement
 * @param childName
 * @param childValue
 * @param isMandatory
 * @throws InvalidThemeDescriptorDefinitionException
 */
protected void addChild(final Element parentElement, final String childName, final String childValue,
        final boolean isMandatory, final boolean isEmptyForbidden) throws InvalidXMLDefinitionException {
    if (isMandatory) {
        checkArgNotNull(childName, childValue);
    }
    if (isEmptyForbidden) {
        checkStringNotEmpty(childName, childValue);
    }
    if (childValue != null) {
        final Element element = document.createElement(childName);
        element.setTextContent(childValue);
        parentElement.appendChild(element);
    }
}

From source file:org.broad.igv.cbio.GeneNetwork.java

/**
 * Add the data specified by the score-types to our
 * network, using data from the tracks./*w ww.  ja  v  a2s. co m*/
 * <p/>
 *
 * @param tracks
 * @param nodeAttributes
 */
public void annotate(List<Track> tracks, Collection<String> nodeAttributes) {

    Set<Node> nodes = this.vertexSet();
    String name;

    for (Node node : nodes) {
        name = getNodeKeyData(node, LABEL);

        ScoreData data = this.collectScoreData(name, tracks, nodeAttributes);

        //Don't add annotation if gene has no alteration?
        float relData = data.getPercentAltered();
        if (relData == 0 && !Globals.isTesting()) {
            continue;
        }

        for (String attr : nodeAttributes) {
            Element newData = node.getOwnerDocument().createElement("data");
            newData.setAttribute(KEY, attr);
            newData.setTextContent("" + data.get(attr));
            node.appendChild(newData);
        }

        //Set total
        Element newData = node.getOwnerDocument().createElement("data");
        newData.setAttribute(KEY, PERCENT_ALTERED);
        newData.setTextContent("" + data.getPercentAltered());

        node.appendChild(newData);
    }

    addSchema(Arrays.asList(PERCENT_ALTERED), "float", "node");
    addSchema(nodeAttributes, "float", "node");
}

From source file:org.bultreebank.labpipe.converters.LineConverter.java

/**
 * Converts Line encoded data into a CLaRK document.
 * /*from  w w w .  ja  v  a 2 s .c  o m*/
 * @param   lines   Line encoded data
 * @param   eosToken   end of sentence token
 * 
 * @return  {@link org.w3c.dom.Document} - CLaRK Document
 */
public static Document toClark(String lines, String eosToken) {
    try {

        Document clarkDoc = ClarkDocumentBuilder.buildClarkDocument();

        BufferedReader br = new BufferedReader(new StringReader(lines));

        String line;

        Element root = clarkDoc.createElement("root");
        Element sentence = clarkDoc.createElement("s");
        Element token = null;
        String[] lineSegments;
        clarkDoc.appendChild(root);

        while ((line = br.readLine()) != null) {

            if (line.contains(eosToken)) {

                root.appendChild(sentence);
                sentence = clarkDoc.createElement("s");

            } else {

                token = clarkDoc.createElement("tok");
                line = line.replaceAll("\t", " ");
                lineSegments = line.split(" ");
                token.setTextContent(lineSegments[0]);
                if (lineSegments.length > 1) {
                    token.setAttribute("svm", lineSegments[1]);
                }
                if (lineSegments.length > 2) {
                    token.setAttribute("lm", lineSegments[2]);
                }
                sentence.appendChild(token);

            }

        }

        return clarkDoc;

    } catch (IOException ex) {
        logger.severe(ServiceConstants.EXCEPTION_IO);
    }

    return null;
}

From source file:org.cablelabs.playready.cryptfile.PlayReadyPSSH.java

@Override
public Element generateContentProtection(Document d) throws IOException {
    Element e = super.generateContentProtection(d);

    switch (cpType) {

    case CENC://from www .ja  v a2 s  .c  om
        e.appendChild(generateCENCContentProtectionData(d));
        break;

    case MSPRO:
        Element pro = d.createElement(MSPRO_ELEMENT);

        // Generate base64-encoded PRO
        ByteBuffer ba = ByteBuffer.allocate(4);
        ba.order(ByteOrder.LITTLE_ENDIAN);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        // PlayReady Header Object Size field
        ba.putInt(0, proSize);
        dos.write(ba.array());

        // Number of Records field
        ba.putShort(0, (short) wrmHeaders.size());
        dos.write(ba.array(), 0, 2);

        for (WRMHeader header : wrmHeaders) {

            byte[] wrmData = header.getWRMHeaderData();

            // Record Type (always 1 for WRM Headers)
            ba.putShort(0, (short) 1);
            dos.write(ba.array(), 0, 2);

            // Record Length
            ba.putShort(0, (short) wrmData.length);
            dos.write(ba.array(), 0, 2);

            // Data
            dos.write(wrmData);
        }

        pro.setTextContent(Base64.encodeBase64String(baos.toByteArray()));

        e.appendChild(pro);
        break;
    }

    return e;
}

From source file:org.collectionspace.services.nuxeo.client.java.CommonList.java

/**
 * Adds an item to the results list. Each item should have fields
 * associated to keys defined in the fieldKeys. 
 * Caller must call setFieldsReturned() before calling this.
 * /*from ww  w .ja  v a 2s . c  om*/
 * @param itemInfo
 * @throws RuntimeException if this is called before fieldKeys has been set.
 */
public void addItem(HashMap<String, String> itemInfo) {
    if (fieldKeys == null) {
        throw new RuntimeException("CommonList.addItem: Cannot add items before fieldKeys are set.");
    }
    List<AbstractCommonList.ListItem> itemsList = getListItem();
    AbstractCommonList.ListItem listItem = new AbstractCommonList.ListItem();
    itemsList.add(listItem);
    List<Element> anyList = listItem.getAny();
    for (String key : fieldKeys) {
        Element el = doc.createElement(key);
        el.setTextContent(itemInfo.get(key));
        anyList.add(el);
    }
}

From source file:org.commonjava.aprox.core.content.MavenMetadataGenerator.java

private boolean writeVersionMetadata(final List<StoreResource> firstLevelFiles, final ArtifactStore store,
        final String path) throws AproxWorkflowException {
    ArtifactPathInfo samplePomInfo = null;

    // first level will contain version directories...for each directory, we need to verify the presence of a .pom file before including 
    // as a valid version
    final List<SingleVersion> versions = new ArrayList<SingleVersion>();
    nextTopResource: for (final StoreResource topResource : firstLevelFiles) {
        final String topPath = topResource.getPath();
        if (topPath.endsWith("/")) {
            final List<StoreResource> secondLevelListing = fileManager.list(store, topPath);
            for (final StoreResource fileResource : secondLevelListing) {
                if (fileResource.getPath().endsWith(".pom")) {
                    versions.add(VersionUtils.createSingleVersion(new File(topPath).getName()));
                    if (samplePomInfo == null) {
                        samplePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                    }/*  w  w  w  . j a v  a2  s.c o  m*/

                    continue nextTopResource;
                }
            }
        }
    }

    if (versions.isEmpty()) {
        return false;
    }

    Collections.sort(versions);

    final Transfer metadataFile = fileManager.getStorageReference(store, path);
    OutputStream stream = null;
    try {
        final Document doc = xml.newDocumentBuilder().newDocument();

        final Map<String, String> coordMap = new HashMap<String, String>();
        coordMap.put(ARTIFACT_ID, samplePomInfo.getArtifactId());
        coordMap.put(GROUP_ID, samplePomInfo.getGroupId());

        final String lastUpdated = SnapshotUtils.generateUpdateTimestamp(SnapshotUtils.getCurrentTimestamp());

        doc.appendChild(doc.createElementNS(doc.getNamespaceURI(), "metadata"));
        xml.createElement(doc.getDocumentElement(), null, coordMap);

        final Map<String, String> versioningMap = new HashMap<String, String>();
        versioningMap.put(LAST_UPDATED, lastUpdated);

        final SingleVersion latest = versions.get(versions.size() - 1);
        versioningMap.put(LATEST, latest.renderStandard());

        SingleVersion release = null;
        for (int i = versions.size() - 1; i >= 0; i--) {
            final SingleVersion r = versions.get(i);
            if (r.isRelease()) {
                release = r;
                break;
            }
        }

        if (release != null) {
            versioningMap.put(RELEASE, release.renderStandard());
        }

        xml.createElement(doc, "versioning", versioningMap);
        final Element versionsElem = xml.createElement(doc, "versioning/versions",
                Collections.<String, String>emptyMap());

        for (final SingleVersion version : versions) {
            final Element vElem = doc.createElement(VERSION);
            vElem.setTextContent(version.renderStandard());

            versionsElem.appendChild(vElem);
        }

        final String xmlStr = xml.toXML(doc, true);
        stream = metadataFile.openOutputStream(TransferOperation.GENERATE);
        stream.write(xmlStr.getBytes("UTF-8"));
    } catch (final GalleyMavenXMLException e) {
        throw new AproxWorkflowException("Failed to generate maven metadata file: %s. Reason: %s", e, path,
                e.getMessage());
    } catch (final IOException e) {
        throw new AproxWorkflowException("Failed to write generated maven metadata file: %s. Reason: %s", e,
                metadataFile, e.getMessage());
    } finally {
        closeQuietly(stream);
    }

    return true;
}

From source file:org.commonjava.indy.core.content.MavenMetadataGenerator.java

private boolean writeVersionMetadata(final List<StoreResource> firstLevelFiles, final ArtifactStore store,
        final String path, final EventMetadata eventMetadata) throws IndyWorkflowException {
    ArtifactPathInfo samplePomInfo = null;

    // first level will contain version directories...for each directory, we need to verify the presence of a .pom file before including
    // as a valid version
    final List<SingleVersion> versions = new ArrayList<SingleVersion>();
    nextTopResource: for (final StoreResource topResource : firstLevelFiles) {
        final String topPath = topResource.getPath();
        if (topPath.endsWith("/")) {
            final List<StoreResource> secondLevelListing = fileManager.listRaw(store, topPath);
            for (final StoreResource fileResource : secondLevelListing) {
                if (fileResource.getPath().endsWith(".pom")) {
                    ArtifactPathInfo filePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                    // check if the pom is valid for the path
                    if (filePomInfo != null) {
                        versions.add(VersionUtils.createSingleVersion(new File(topPath).getName()));
                        if (samplePomInfo == null) {
                            samplePomInfo = filePomInfo;
                        }// ww  w  . j ava  2 s  . c  om

                        continue nextTopResource;
                    }
                }
            }
        }
    }

    if (versions.isEmpty()) {
        return false;
    }

    Collections.sort(versions);

    final Transfer metadataFile = fileManager.getTransfer(store, path);
    OutputStream stream = null;
    try {
        final Document doc = xml.newDocumentBuilder().newDocument();

        final Map<String, String> coordMap = new HashMap<String, String>();
        coordMap.put(ARTIFACT_ID, samplePomInfo.getArtifactId());
        coordMap.put(GROUP_ID, samplePomInfo.getGroupId());

        final String lastUpdated = SnapshotUtils.generateUpdateTimestamp(SnapshotUtils.getCurrentTimestamp());

        doc.appendChild(doc.createElementNS(doc.getNamespaceURI(), "metadata"));
        xml.createElement(doc.getDocumentElement(), null, coordMap);

        final Map<String, String> versioningMap = new HashMap<String, String>();
        versioningMap.put(LAST_UPDATED, lastUpdated);

        final SingleVersion latest = versions.get(versions.size() - 1);
        versioningMap.put(LATEST, latest.renderStandard());

        SingleVersion release = null;
        for (int i = versions.size() - 1; i >= 0; i--) {
            final SingleVersion r = versions.get(i);
            if (r.isRelease()) {
                release = r;
                break;
            }
        }

        if (release != null) {
            versioningMap.put(RELEASE, release.renderStandard());
        }

        xml.createElement(doc, "versioning", versioningMap);
        final Element versionsElem = xml.createElement(doc, "versioning/versions",
                Collections.<String, String>emptyMap());

        for (final SingleVersion version : versions) {
            final Element vElem = doc.createElement(VERSION);
            vElem.setTextContent(version.renderStandard());

            versionsElem.appendChild(vElem);
        }

        final String xmlStr = xml.toXML(doc, true);
        stream = metadataFile.openOutputStream(TransferOperation.GENERATE, true, eventMetadata);
        stream.write(xmlStr.getBytes("UTF-8"));
    } catch (final GalleyMavenXMLException e) {
        throw new IndyWorkflowException("Failed to generate maven metadata file: %s. Reason: %s", e, path,
                e.getMessage());
    } catch (final IOException e) {
        throw new IndyWorkflowException("Failed to write generated maven metadata file: %s. Reason: %s", e,
                metadataFile, e.getMessage());
    } finally {
        closeQuietly(stream);
    }

    return true;
}

From source file:org.commonjava.indy.pkg.maven.content.MavenMetadataGenerator.java

private boolean writeVersionMetadata(final List<StoreResource> firstLevelFiles, final ArtifactStore store,
        final String path, final EventMetadata eventMetadata) throws IndyWorkflowException {
    ArtifactPathInfo samplePomInfo = null;

    logger.debug("writeVersionMetadata, firstLevelFiles:{}, store:{}", firstLevelFiles, store.getKey());

    // first level will contain version directories...for each directory, we need to verify the presence of a .pom file before including
    // as a valid version
    final List<SingleVersion> versions = new ArrayList<>();
    nextTopResource: for (final StoreResource topResource : firstLevelFiles) {
        final String topPath = topResource.getPath();
        if (topPath.endsWith("/")) {
            final List<StoreResource> secondLevelListing = fileManager.listRaw(store, topPath);
            for (final StoreResource fileResource : secondLevelListing) {
                if (fileResource.getPath().endsWith(".pom")) {
                    ArtifactPathInfo filePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                    // check if the pom is valid for the path
                    if (filePomInfo != null) {
                        versions.add(VersionUtils.createSingleVersion(new File(topPath).getName()));
                        if (samplePomInfo == null) {
                            samplePomInfo = filePomInfo;
                        }//from   ww  w.j a v a  2 s  .  c  o m

                        continue nextTopResource;
                    }
                }
            }
        }
    }

    if (versions.isEmpty()) {
        logger.debug("writeVersionMetadata, versions is empty, store:{}", store.getKey());
        return false;
    }

    logger.debug("writeVersionMetadata, versions: {}, store:{}", versions, store.getKey());

    Collections.sort(versions);

    final Transfer metadataFile = fileManager.getTransfer(store, path);
    OutputStream stream = null;
    try {
        final Document doc = xml.newDocumentBuilder().newDocument();

        final Map<String, String> coordMap = new HashMap<>();
        coordMap.put(ARTIFACT_ID, samplePomInfo == null ? null : samplePomInfo.getArtifactId());
        coordMap.put(GROUP_ID, samplePomInfo == null ? null : samplePomInfo.getGroupId());

        final String lastUpdated = SnapshotUtils.generateUpdateTimestamp(SnapshotUtils.getCurrentTimestamp());

        doc.appendChild(doc.createElementNS(doc.getNamespaceURI(), "metadata"));
        xml.createElement(doc.getDocumentElement(), null, coordMap);

        final Map<String, String> versioningMap = new HashMap<>();
        versioningMap.put(LAST_UPDATED, lastUpdated);

        final SingleVersion latest = versions.get(versions.size() - 1);
        versioningMap.put(LATEST, latest.renderStandard());

        SingleVersion release = null;
        for (int i = versions.size() - 1; i >= 0; i--) {
            final SingleVersion r = versions.get(i);
            if (r.isRelease()) {
                release = r;
                break;
            }
        }

        if (release != null) {
            versioningMap.put(RELEASE, release.renderStandard());
        }

        xml.createElement(doc, "versioning", versioningMap);
        final Element versionsElem = xml.createElement(doc, "versioning/versions", Collections.emptyMap());

        for (final SingleVersion version : versions) {
            final Element vElem = doc.createElement(VERSION);
            vElem.setTextContent(version.renderStandard());

            versionsElem.appendChild(vElem);
        }

        final String xmlStr = xml.toXML(doc, true);
        stream = metadataFile.openOutputStream(TransferOperation.GENERATE, true, eventMetadata);
        stream.write(xmlStr.getBytes("UTF-8"));
    } catch (final GalleyMavenXMLException e) {
        throw new IndyWorkflowException("Failed to generate maven metadata file: %s. Reason: %s", e, path,
                e.getMessage());
    } catch (final IOException e) {
        throw new IndyWorkflowException("Failed to write generated maven metadata file: %s. Reason: %s", e,
                metadataFile, e.getMessage());
    } finally {
        closeQuietly(stream);
    }

    logger.debug("writeVersionMetadata, DONE, store: {}", store.getKey());
    return true;
}

From source file:org.commonjava.maven.galley.maven.model.view.AbstractMavenElementView.java

/**
 * Append new children elements to the final result(collapsed) when there are children ones found in
 * overlapping parents elements, but not found in current element children.
 *
 * @param current The element which will be collapsed during this process.
 * @param step Iteration counter./*from  w w  w .ja v  a2s . c o m*/
 * @return Final collapsed element.
 */
@SuppressWarnings("UnusedReturnValue")
private Element addToCollapsedChildElements(Element current, int step) {
    List<Element> parents = elementsAwaitingCollapse;
    while (!isElementStackEmpty(parents) && step < parents.size()) {
        NodeList originalElementChildNodeList = current.getChildNodes();
        List<String> originalElementChildNameList = new ArrayList<>();
        for (int i = 0; i <= originalElementChildNodeList.getLength(); i++) {
            Node node = originalElementChildNodeList.item(i);
            if (!(node instanceof Element)) {
                continue;
            }
            originalElementChildNameList.add(node.getNodeName());
        }

        NodeList nodeList = parents.get(step).getChildNodes();
        for (int i = 0; i <= nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (!(node instanceof Element)) {
                continue;
            }

            if (!originalElementChildNameList.contains(node.getNodeName())) {
                Document dom = current.getOwnerDocument();
                Element child = dom.createElement(node.getNodeName());
                child.setTextContent(node.getTextContent());
                current.appendChild(child);
            }
        }
        step++;
        addToCollapsedChildElements(current, step);
    }
    return current;
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public Element createElement(final Node in, final String relativePath, final Map<String, String> leafElements) {
    final Document doc;
    final Element below;
    if (in instanceof Document) {
        doc = (Document) in;/*from   ww w.  ja va2s.c o  m*/
        below = doc.getDocumentElement();
    } else if (in instanceof Element) {
        below = (Element) in;
        doc = below.getOwnerDocument();
    } else {
        throw new IllegalArgumentException("Cannot create nodes/content under a node of type: " + in);
    }

    Element insertionPoint = below;
    if (relativePath != null && relativePath.length() > 0 && !"/".equals(relativePath)) {
        final String[] intermediates = relativePath.split("/");

        // DO NOT traverse last "intermediate"...this will be the new element!
        for (int i = 0; i < intermediates.length - 1; i++) {
            final NodeList nl = insertionPoint.getElementsByTagNameNS(below.getNamespaceURI(),
                    intermediates[i]);
            if (nl != null && nl.getLength() > 0) {
                insertionPoint = (Element) nl.item(0);
            } else {
                final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[i]);
                insertionPoint.appendChild(e);
                insertionPoint = e;
            }
        }

        final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[intermediates.length - 1]);
        insertionPoint.appendChild(e);
        insertionPoint = e;
    }

    for (final Entry<String, String> entry : leafElements.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        final Element e = doc.createElementNS(below.getNamespaceURI(), key);
        insertionPoint.appendChild(e);
        e.setTextContent(value);
    }

    return insertionPoint;
}