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.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * Build the question presentation text. Its important to remove inline feedback text and interaction text while creating this text.
 * /* w w  w. j  a  v  a2 s  . c  o m*/
 * @param contentsDOM
 * @param itemBodyElement
 * @param interaction
 * @return
 * @throws Exception
 */
private String processQuestionText(String context, Document contentsDOM, Element itemElement,
        List<String> embedMedia, String interaction, String unzipBackUpLocation) throws Exception {
    String text = "";

    if (itemElement == null)
        return text;

    boolean fillBlanks = ("inlineChoiceInteraction".equalsIgnoreCase(interaction)
            || "textEntryInteraction".equalsIgnoreCase(interaction)) ? true : false;

    Element itemBodyElement = (Element) itemElement.cloneNode(true);
    List<Element> interactionElements = new ArrayList<Element>();

    // embed images
    processEmbedMedia(itemBodyElement, unzipBackUpLocation, context, embedMedia);

    itemBodyElement = removeFeedback(itemBodyElement);

    if (interaction == null || "".equals(interaction))
        return normalizeElementBody(contentsDOM, itemBodyElement);

    XPath interactionPath = new DOMXPath(".//" + interaction);
    interactionElements = interactionPath.selectNodes(itemBodyElement);

    if (interactionElements == null || interactionElements.size() == 0)
        return normalizeElementBody(contentsDOM, itemBodyElement);

    // add prompt or block quote inside interaction to question text

    for (Element i : interactionElements) {
        String additionalText = "";
        XPath promptPath = new DOMXPath("prompt|blockquote");
        List<Element> prompts = promptPath.selectNodes(i);
        for (Element prompt : prompts) {
            additionalText = additionalText.concat(normalizeElementBody(contentsDOM, prompt));
        }

        if (fillBlanks) {
            Element replaceDivElement = contentsDOM.createElement("div");
            i.setTextContent(additionalText + "{}");
            itemBodyElement.appendChild(replaceDivElement);
        } else
            i.setTextContent(additionalText);
    }

    // normalize all child nodes and create a string
    String content = normalizeElementBody(contentsDOM, itemBodyElement);
    return content;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * //from w  w  w  .  j av a2s . co  m
 * @param correctValues
 * @param interactionText
 * @param contentsDOM
 * @param mc
 * @return
 * @throws Exception
 */
private Question buildFillBlankforGapText(Pool pool, String text, String interactionText, Document contentsDOM)
        throws Exception {
    if (!("gapMatchInteraction").equals(interactionText))
        return null;

    String questionText = "";

    // correct answer
    XPath identifierPath = new DOMXPath("/assessmentItem/responseDeclaration/correctResponse/value");
    List<Element> values = identifierPath.selectNodes(contentsDOM);

    XPath gapInteractionPath = new DOMXPath("/assessmentItem/itemBody//gapMatchInteraction");
    Element gapInteractionElement = (Element) gapInteractionPath.selectSingleNode(contentsDOM);
    String interactionIdentifier = gapInteractionElement.getAttribute("responseIdentifier");

    // The bandit killed her <gap identifier="G1"/>
    XPath gapPath = new DOMXPath("/assessmentItem/itemBody//gap");
    List<Element> gaps = gapPath.selectNodes(contentsDOM);

    for (Element gap : gaps) {
        String identifier = gap.getAttribute("identifier");
        String otherId = "";

        XPath responseValuePath = new DOMXPath("/assessmentItem/responseDeclaration[@identifier='"
                + interactionIdentifier + "']/correctResponse/value[contains(text(),'" + identifier + "')]");
        Element value = (Element) responseValuePath.selectSingleNode(contentsDOM);

        if (value != null) {
            String valuePair = value.getTextContent();
            otherId = valuePair.replace(identifier, "").trim();
        } else {
            List<String> answers = getCorrectResponsefromResponseProcessing(contentsDOM, interactionIdentifier,
                    false);
            if (answers != null && answers.size() > 0)
                otherId = answers.get(0);
        }
        // <gapText identifier="F" matchMax="1">family</gapText>
        if ("".equals(otherId))
            continue;
        XPath idPath = new DOMXPath(".//gapText[@identifier='" + otherId + "']");
        Element gapTextElement = (Element) idPath.selectSingleNode(contentsDOM);
        String choiceLabel2 = normalizeElementBody(contentsDOM, gapTextElement);

        gap.setTextContent("{" + choiceLabel2 + "}");
    }

    // add hints
    XPath gaptextPath = new DOMXPath(".//gapText");
    List<Element> allGapTexts = gaptextPath.selectNodes(contentsDOM);

    String hints = "";
    for (Element g : allGapTexts) {
        hints = hints.concat("\t" + normalizeElementBody(contentsDOM, g));
        g.setTextContent("");
    }

    XPath itemBodyPath = new DOMXPath("/assessmentItem/itemBody");
    Element itemBodyElement = (Element) itemBodyPath.selectSingleNode(contentsDOM);
    questionText = normalizeElementBody(contentsDOM, itemBodyElement);

    Question question = buildMnemeFillBlanks(pool, true, questionText);
    question.setHints(hints);

    return question;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * Remove feedback element from the choice and item body so that getTextContent() doesn't bring their content
 * /*from   w ww  .java  2s  .  c o m*/
 * @param itemBodyElement
 * @return
 * @throws Exception
 */
private Element removeFeedback(Element itemBodyElement) throws Exception {
    XPath inlineFeedbackPath = new DOMXPath(".//feedbackInline | .//feedbackBlock");
    List<Element> feedbackElements = inlineFeedbackPath.selectNodes(itemBodyElement);

    if (feedbackElements != null && feedbackElements.size() > 0) {
        for (Element fb : feedbackElements)
            fb.setTextContent("");
    }

    return itemBodyElement;
}

From source file:org.geopublishing.geopublisher.AMLExporter.java

/**
 * Exports one single {@link AttributeMetadataImpl} to an aml:dataAttribute
 * tag./*www  .j av a 2s  .com*/
 * 
 * @return {@link org.w3c.dom.Element} that represents the XML tag
 * 
 * @author <a href="mailto:skpublic@wikisquare.de">Stefan Alfons Tzeggai</a>
 */
private Element exportAttributeMetadata(final DpLayerVectorFeatureSource dpe, final Document document,
        final AttributeMetadataImpl attrib) {

    final Element element = document.createElementNS(AMLUtil.AMLURI, AMLUtil.TAG_attributeMetadata);

    element.setAttribute(AMLUtil.ATT_namespace, attrib.getName().getNamespaceURI());
    element.setAttribute(AMLUtil.ATT_localname, attrib.getName().getLocalPart());

    element.setAttribute(AMLUtil.ATT_weight, new Integer(new Double(attrib.getWeight()).intValue()).toString());
    element.setAttribute(AMLUtil.ATT_functionA, new Double(attrib.getFunctionA()).toString());
    element.setAttribute(AMLUtil.ATT_functionX, new Double(attrib.getFunctionX()).toString());

    element.setAttribute("visible", String.valueOf(attrib.isVisible()));

    if (attrib.getUnit() != null && !attrib.getUnit().isEmpty())
        element.setAttribute("unit", attrib.getUnit());

    // Creating a aml:name tag...
    element.appendChild(exportTranslation(document, "name", attrib.getTitle()));

    // Creating a aml:desc tag...
    element.appendChild(exportTranslation(document, "desc", attrib.getDesc()));

    // Storing the NODATA values
    for (Object nodatavalue : attrib.getNodataValues()) {
        if (nodatavalue == null)
            continue;
        Element ndValue = document.createElementNS(AMLUtil.AMLURI, AMLUtil.TAG_nodataValue);
        ndValue.setTextContent(nodatavalue.toString());
        element.appendChild(ndValue);
    }

    return element;
}

From source file:org.geoserver.security.xml.XMLRoleStore.java

@Override
protected void serialize() throws IOException {

    DocumentBuilder builder = null;
    try {/* w w  w .ja  v a  2 s . c  o  m*/
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        throw new IOException(e1);
    }
    Document doc = builder.newDocument();

    Element rolereg = doc.createElement(E_ROLEREGISTRY_RR);
    doc.appendChild(rolereg);
    rolereg.setAttribute(javax.xml.XMLConstants.XMLNS_ATTRIBUTE, NS_RR);
    rolereg.setAttribute(A_VERSION_RR, VERSION_RR_1_0);

    Element rolelist = doc.createElement(E_ROLELIST_RR);
    rolereg.appendChild(rolelist);

    for (GeoServerRole roleObject : helper.roleMap.values()) {
        Element role = doc.createElement(E_ROLE_RR);
        rolelist.appendChild(role);
        role.setAttribute(A_ROLEID_RR, roleObject.getAuthority());
        GeoServerRole parentObject = helper.role_parentMap.get(roleObject);
        if (parentObject != null) {
            role.setAttribute(A_PARENTID_RR, parentObject.getAuthority());
        }
        for (Object key : roleObject.getProperties().keySet()) {
            Element property = doc.createElement(E_PROPERTY_RR);
            role.appendChild(property);
            property.setAttribute(A_PROPERTY_NAME_RR, key.toString());
            property.setTextContent(roleObject.getProperties().getProperty(key.toString()));
        }
    }

    Element userList = doc.createElement(E_USERLIST_RR);
    rolereg.appendChild(userList);
    for (String userName : helper.user_roleMap.keySet()) {
        Element userroles = doc.createElement(E_USERROLES_RR);
        userList.appendChild(userroles);
        userroles.setAttribute(A_USERNAME_RR, userName);
        SortedSet<GeoServerRole> roleObjects = helper.user_roleMap.get(userName);
        for (GeoServerRole roleObject : roleObjects) {
            Element ref = doc.createElement(E_ROLEREF_RR);
            userroles.appendChild(ref);
            ref.setAttribute(A_ROLEREFID_RR, roleObject.getAuthority());
        }
    }

    Element groupList = doc.createElement(E_GROUPLIST_RR);
    rolereg.appendChild(groupList);

    for (String groupName : helper.group_roleMap.keySet()) {
        Element grouproles = doc.createElement(E_GROUPROLES_RR);
        groupList.appendChild(grouproles);
        grouproles.setAttribute(A_GROUPNAME_RR, groupName);
        SortedSet<GeoServerRole> roleObjects = helper.group_roleMap.get(groupName);
        for (GeoServerRole roleObject : roleObjects) {
            Element ref = doc.createElement(E_ROLEREF_RR);
            grouproles.appendChild(ref);
            ref.setAttribute(A_ROLEREFID_RR, roleObject.getAuthority());
        }
    }

    // serialize the dom
    try {
        //            TODO, wait for JAVA 6
        //            if (isValidatingXMLSchema()) {
        //                XMLValidator.Singleton.validateRoleRegistry(doc);
        //            }

        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.METHOD, "XML");
        tx.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tx.setOutputProperty(OutputKeys.INDENT, "yes");

        OutputStream out = new BufferedOutputStream(new FileOutputStream(roleFile));
        try {
            tx.transform(new DOMSource(doc), new StreamResult(out));
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }

        /* standard java, but there is no possibility to set 
         * the number of chars to indent, each line is starting at 
         * column 0
        Source source = new DOMSource(doc);
        // Prepare the output file            
        Result result = new StreamResult(
            new OutputStreamWriter(new FileOutputStream(roleFile),"UTF-8"));
                
        TransformerFactory fac = TransformerFactory.newInstance();
        Transformer xformer = fac.newTransformer();                        
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");            
        xformer.transform(source, result);
        */

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.geoserver.security.xml.XMLUserGroupStore.java

@Override
protected void serialize() throws IOException {

    DocumentBuilder builder = null;
    try {// w w  w.j a  va  2 s  . co m
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        builder = fac.newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        throw new IOException(e1);
    }
    Document doc = builder.newDocument();

    Element userreg = doc.createElement(E_USERREGISTRY_UR);
    doc.appendChild(userreg);
    userreg.setAttribute(javax.xml.XMLConstants.XMLNS_ATTRIBUTE, NS_UR);
    userreg.setAttribute(A_VERSION_UR, VERSION_UR_1_0);

    Element users = doc.createElement(E_USERS_UR);
    userreg.appendChild(users);
    for (GeoServerUser userObject : helper.userMap.values()) {
        Element user = doc.createElement(E_USER_UR);
        users.appendChild(user);
        user.setAttribute(A_USER_NAME_UR, userObject.getUsername());
        if (userObject.getPassword() != null) {
            user.setAttribute(A_USER_PASSWORD_UR, userObject.getPassword());
        }
        user.setAttribute(A_USER_ENABLED_UR, String.valueOf(userObject.isEnabled()));

        for (Object key : userObject.getProperties().keySet()) {
            Element property = doc.createElement(E_PROPERTY_UR);
            user.appendChild(property);
            property.setAttribute(A_PROPERTY_NAME_UR, key.toString());
            property.setTextContent(userObject.getProperties().getProperty(key.toString()));
        }
    }

    Element groups = doc.createElement(E_GROUPS_UR);
    userreg.appendChild(groups);
    for (GeoServerUserGroup groupObject : helper.groupMap.values()) {
        Element group = doc.createElement(E_GROUP_UR);
        groups.appendChild(group);
        group.setAttribute(A_GROUP_NAME_UR, groupObject.getGroupname());
        group.setAttribute(A_GROUP_ENABLED_UR, groupObject.isEnabled() ? "true" : "false");
        SortedSet<GeoServerUser> userObjects = helper.group_userMap.get(groupObject);
        if (userObjects != null) {
            for (GeoServerUser userObject : userObjects) {
                Element member = doc.createElement(E_MEMBER_UR);
                group.appendChild(member);
                member.setAttribute(A_MEMBER_NAME_UR, userObject.getUsername());
            }
        }
    }

    // serialize the dom
    try {
        //            TODO, wait for JAVA 6
        //            if (isValidatingXMLSchema()) {
        //                XMLValidator.Singleton.validateUserGroupRegistry(doc);
        //            }            

        Transformer tx = TransformerFactory.newInstance().newTransformer();
        tx.setOutputProperty(OutputKeys.METHOD, "XML");
        tx.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tx.setOutputProperty(OutputKeys.INDENT, "yes");

        OutputStream out = new BufferedOutputStream(new FileOutputStream(userFile));
        try {
            tx.transform(new DOMSource(doc), new StreamResult(out));
            out.flush();
        } finally {
            IOUtils.closeQuietly(out);
        }
        /* standard java, but there is no possiTbility to set 
         * the number of chars to indent, each line is starting at 
         * column 0            
        Source source = new DOMSource(doc);
        Result result = new StreamResult(
            new OutputStreamWriter(new FileOutputStream(userFile),"UTF-8"));
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);
        */

    } catch (Exception e) {
        throw new IOException(e);
    }

}

From source file:org.gephi.desktop.preview.PresetUtils.java

private void writeXML(Document doc, PreviewPreset preset) {
    Element presetE = doc.createElement("previewpreset");
    presetE.setAttribute("name", preset.getName());
    presetE.setAttribute("version", "0.8.1");

    for (Entry<String, Object> entry : preset.getProperties().entrySet()) {
        String propertyName = entry.getKey();
        try {/*from  w  w  w  . j  ava2s  .com*/
            Object propertyValue = entry.getValue();
            if (propertyValue != null) {
                String serialized = PreviewProperties.getValueAsText(propertyValue);
                if (serialized != null) {
                    Element propertyE = doc.createElement("previewproperty");
                    propertyE.setAttribute("name", propertyName);
                    propertyE.setAttribute("class", propertyValue.getClass().getName());
                    propertyE.setTextContent(serialized);
                    presetE.appendChild(propertyE);
                }
            }
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    doc.appendChild(presetE);
}

From source file:org.glom.app.libglom.Document.java

private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) {
    String str = "";

    switch (type) {
    case TYPE_BOOLEAN: {
        str = value.getBoolean() ? "true" : "false";
        break;//from   w  w w  .  j  a va  2s  .c  om
    }
    case TYPE_DATE: {
        // TODO: This is not really the format used by the Glom document:
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        str = dateFormat.format(value.getDate());
        break;
    }
    case TYPE_IMAGE: {
        str = ""; // TODO
        break;
    }
    case TYPE_NUMERIC: {
        str = getStringForDecimal(value.getNumber());
        break;
    }
    case TYPE_TEXT:
        str = value.getText();
        break;
    case TYPE_TIME:
        str = ""; // TODO
        break;
    default:
        Log.e("android-glom", documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT);
    element.setTextContent(escaped);
}

From source file:org.glom.libglom.Document.java

private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) {
    String str = "";

    switch (type) {
    case TYPE_BOOLEAN: {
        str = value.getBoolean() ? "true" : "false";
        break;/*from w  w w.j a va 2 s .  c o  m*/
    }
    case TYPE_DATE: {
        // TODO: This is not really the format used by the Glom document:
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        str = dateFormat.format(value.getDate());
        break;
    }
    case TYPE_IMAGE: {
        str = ""; // TODO
        break;
    }
    case TYPE_NUMERIC: {
        str = getStringForDecimal(value.getNumber());
        break;
    }
    case TYPE_TEXT:
        str = value.getText();
        break;
    case TYPE_TIME:
        str = ""; // TODO
        break;
    default:
        Logger.log(documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT);
    element.setTextContent(escaped);
}

From source file:org.glom.web.server.libglom.Document.java

private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) {
    String str = "";

    switch (type) {
    case TYPE_BOOLEAN: {
        str = value.getBoolean() ? "true" : "false";
        break;/* w  w  w . j  a va  2s  .  c o  m*/
    }
    case TYPE_DATE: {
        // TODO: This is not really the format used by the Glom document:
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
        str = dateFormat.format(value.getDate());
        break;
    }
    case TYPE_IMAGE: {
        str = ""; // TODO
        break;
    }
    case TYPE_NUMERIC: {
        str = getStringForDecimal(value.getNumber());
        break;
    }
    case TYPE_TEXT:
        str = value.getText();
        break;
    case TYPE_TIME:
        str = ""; // TODO
        break;
    default:
        Log.error(documentID, "setNodeTextChildAsValue(): unexpected or invalid field type.");
        break;
    }

    final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT);
    element.setTextContent(escaped);
}