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:ml.shifu.shifu.core.pmml.PMMLTranslator.java

/**
 * Create @DerivedField for categorical variable
 * @param config - ColumnConfig for categorical variable
 * @param cutoff - cutoff for normalization
 * @return DerivedField for variable/*from w  w w. j  a v a  2s. c  om*/
 */
private DerivedField createCategoricalDerivedField(ColumnConfig config, double cutoff) {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        LOG.error("Fail to create document node.", e);
        throw new RuntimeException("Fail to create document node.", e);
    }

    String defaultValue = "0.0";
    String missingValue = "0.0";

    InlineTable inlineTable = new InlineTable();
    for (int i = 0; i < config.getBinCategory().size(); i++) {
        String cval = config.getBinCategory().get(i);
        String dval = Normalizer.normalize(config, cval, cutoff).toString();

        Element out = document.createElementNS(NAME_SPACE_URI, ELEMENT_OUT);
        out.setTextContent(dval);

        Element origin = document.createElementNS(NAME_SPACE_URI, ELEMENT_ORIGIN);
        origin.setTextContent(cval);

        inlineTable.withRows(new Row().withContent(origin).withContent(out));
        if (StringUtils.isBlank(cval)) {
            missingValue = dval;
        }
    }

    MapValues mapValues = new MapValues("out").withDataType(DataType.DOUBLE).withDefaultValue(defaultValue)
            .withFieldColumnPairs(new FieldColumnPair(new FieldName(config.getColumnName()), ELEMENT_ORIGIN))
            .withInlineTable(inlineTable).withMapMissingTo(missingValue);

    return new DerivedField(OpType.CONTINUOUS, DataType.DOUBLE)
            .withName(FieldName.create(config.getColumnName() + ZSCORE_POSTFIX)).withExpression(mapValues);
}

From source file:org.apache.streams.gnip.powertrack.ActivityXMLActivitySerializer.java

private String setContentIfEmpty(String xml) throws Exception {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = docBuilder.parse(is);
    doc.getDocumentElement().normalize();
    Element base = (Element) doc.getElementsByTagName("entry").item(0);
    NodeList nodeList = base.getChildNodes();
    //        for(int i=0; i < nodeList.getLength(); ++i) {
    //            System.out.println(nodeList.item(i).getNodeName());
    //        }//from   w w  w  .  j  a v  a2  s  . c o  m
    Element obj = (Element) base.getElementsByTagName("activity:object").item(0);
    Element content = (Element) obj.getElementsByTagName("content").item(0);
    //        System.out.println("Number of child nodes : "+content.getChildNodes().getLength());
    //        System.out.println("Text content before : "+content.getTextContent());
    if (content.getTextContent() == null || content.getTextContent().equals("")) {
        content.setTextContent(" ");
    }
    //        System.out.println("Number of child nodes after : "+content.getChildNodes().getLength());
    //        System.out.println("Text content after : "+content.getTextContent());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
    //        System.out.println(output);
    //        System.out.println(output);
    //        System.out.println(content);
    return output;
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateAlertTable() {
    Logger logger = Logger.getLogger(getClass());
    PreparedStatement statement = null;
    ResultSet results = null;/*w  w  w  .j  ava 2 s  .co  m*/

    try {
        Map<String, List<String>> alertEmails = new HashMap<String, List<String>>();
        Map<String, List<String>> alertChannels = new HashMap<String, List<String>>();

        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        // Build a list of emails for each alert
        statement = connection.prepareStatement("SELECT ALERT_ID, EMAIL FROM OLD_ALERT_EMAIL");
        results = statement.executeQuery();

        while (results.next()) {
            String alertId = results.getString(1);
            String email = results.getString(2);

            List<String> emailSet = alertEmails.get(alertId);

            if (emailSet == null) {
                emailSet = new ArrayList<String>();
                alertEmails.put(alertId, emailSet);
            }

            emailSet.add(email);
        }

        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);

        // Build a list of applied channels for each alert
        statement = connection.prepareStatement("SELECT CHANNEL_ID, ALERT_ID FROM OLD_CHANNEL_ALERT");
        results = statement.executeQuery();

        while (results.next()) {
            String channelId = results.getString(1);
            String alertId = results.getString(2);

            List<String> channelSet = alertChannels.get(alertId);

            if (channelSet == null) {
                channelSet = new ArrayList<String>();
                alertChannels.put(alertId, channelSet);
            }

            channelSet.add(channelId);
        }

        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);

        statement = connection
                .prepareStatement("SELECT ID, NAME, IS_ENABLED, EXPRESSION, TEMPLATE, SUBJECT FROM OLD_ALERT");
        results = statement.executeQuery();

        while (results.next()) {
            String alertId = "";

            try {
                alertId = results.getString(1);
                String name = results.getString(2);
                boolean enabled = results.getBoolean(3);
                String expression = results.getString(4);
                String template = results.getString(5);
                String subject = results.getString(6);

                /*
                 * Create a new document with alertModel as the root node
                 */
                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element alertNode = document.createElement("alert");
                document.appendChild(alertNode);

                Element node = document.createElement("id");
                node.setTextContent(alertId);
                alertNode.appendChild(node);

                node = document.createElement("name");
                node.setTextContent(name);
                alertNode.appendChild(node);

                node = document.createElement("expression");
                node.setTextContent(expression);
                alertNode.appendChild(node);

                node = document.createElement("template");
                node.setTextContent(template);
                alertNode.appendChild(node);

                node = document.createElement("enabled");
                node.setTextContent(Boolean.toString(enabled));
                alertNode.appendChild(node);

                node = document.createElement("subject");
                node.setTextContent(subject);
                alertNode.appendChild(node);

                // Add each applied channel to the document
                Element channelNode = document.createElement("channels");
                alertNode.appendChild(channelNode);
                List<String> channelList = alertChannels.get(alertId);
                if (channelList != null) {
                    for (String channelId : channelList) {
                        Element stringNode = document.createElement("string");
                        stringNode.setTextContent(channelId);
                        channelNode.appendChild(stringNode);
                    }
                }

                // Add each email address to the document
                Element emailNode = document.createElement("emails");
                alertNode.appendChild(emailNode);
                List<String> emailList = alertEmails.get(alertId);
                if (emailList != null) {
                    for (String email : emailList) {
                        Element stringNode = document.createElement("string");
                        stringNode.setTextContent(email);
                        emailNode.appendChild(stringNode);
                    }
                }

                String alert = new DonkeyElement(alertNode).toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement("INSERT INTO ALERT VALUES (?, ?, ?)");
                    updateStatement.setString(1, alertId);
                    updateStatement.setString(2, name);
                    updateStatement.setString(3, alert);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating alert " + alertId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating alerts.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(statement);
    }
}

From source file:clus.statistic.RegressionStat.java

@Override
public Element getPredictElement(Document doc) {
    Element stats = doc.createElement("RegressionStat");
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));

    stats.setAttributeNode(examples);//from  w w  w . jav a2  s  . c om
    for (int i = 0; i < m_NbAttrs; i++) {
        Element attr = doc.createElement("Target");
        Attr name = doc.createAttribute("name");
        name.setValue(m_Attrs[i].getName());
        attr.setAttributeNode(name);

        double tot = getSumWeights(i);
        if (tot == 0)
            attr.setTextContent("?");
        else
            attr.setTextContent(fr.format(getSumValues(i) / tot));

        stats.appendChild(attr);
    }
    return stats;
}

From source file:clus.ext.hierarchical.WHTDStatistic.java

@Override
public Element getPredictElement(Document doc) {
    Element stats = doc.createElement("WHTDStat");
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));
    stats.setAttributeNode(examples);/*  w w  w. j a v  a 2  s. c o  m*/
    if (m_Threshold >= 0.0) {
        String pred = computePrintTuple().toStringHuman(getHier());
        Element predictions = doc.createElement("Predictions");
        stats.appendChild(predictions);
        String[] predictionS = pred.split(",");
        for (String prediction : predictionS) {
            Element attr = doc.createElement("Prediction");
            predictions.appendChild(attr);
            attr.setTextContent(prediction);
        }
    } else {
        for (int i = 0; i < m_NbAttrs; i++) {
            Element attr = doc.createElement("Target");
            Attr name = doc.createAttribute("name");
            name.setValue(m_Attrs[i].getName());
            attr.setAttributeNode(name);
            if (m_SumWeight == 0.0) {
                attr.setTextContent("?");
            } else {
                attr.setTextContent(fr.format(getMean(i)));
            }
            stats.appendChild(attr);
        }
    }
    return stats;
}

From source file:com.evolveum.midpoint.prism.parser.JaxbDomHack.java

/**
 * Serializes prism value to JAXB "any" format as returned by JAXB getAny() methods. 
 *///from   w w  w .j av a  2  s. c o m
public Object toAny(PrismValue value) throws SchemaException {
    Document document = DOMUtil.getDocument();
    if (value == null) {
        return value;
    }
    QName elementName = value.getParent().getElementName();
    Object xmlValue;
    if (value instanceof PrismPropertyValue) {
        PrismPropertyValue<Object> pval = (PrismPropertyValue) value;
        if (pval.isRaw() && (pval.getParent() == null || pval.getParent().getDefinition() == null)) {
            Object rawElement = pval.getRawElement();
            if (rawElement instanceof Element) {
                return ((Element) rawElement).cloneNode(true);
            } else if (rawElement instanceof MapXNode) {
                return domParser.serializeXMapToElement((MapXNode) rawElement, elementName);
            } else if (rawElement instanceof PrimitiveXNode<?>) {
                PrimitiveXNode<?> xprim = (PrimitiveXNode<?>) rawElement;
                String stringValue = xprim.getStringValue();
                Element element = DOMUtil.createElement(document, elementName);
                element.setTextContent(stringValue);
                DOMUtil.setNamespaceDeclarations(element, xprim.getRelevantNamespaceDeclarations());
                return element;
            } else {
                throw new IllegalArgumentException("Cannot convert raw element " + rawElement + " to xsd:any");
            }
        }
        Object realValue = pval.getValue();
        xmlValue = realValue;
        if (XmlTypeConverter.canConvert(realValue.getClass())) {
            // Always record xsi:type. This is FIXME, but should work OK for now (until we put definition into deltas)
            xmlValue = XmlTypeConverter.toXsdElement(realValue, elementName, document, true);
        }
    } else if (value instanceof PrismReferenceValue) {
        PrismReferenceValue rval = (PrismReferenceValue) value;
        xmlValue = prismContext.serializeValueToDom(rval, elementName, document);
    } else if (value instanceof PrismContainerValue<?>) {
        PrismContainerValue<?> pval = (PrismContainerValue<?>) value;
        if (pval.getParent().getCompileTimeClass() == null) {
            // This has to be runtime schema without a compile-time representation.
            // We need to convert it to DOM
            xmlValue = prismContext.serializeValueToDom(pval, elementName, document);
        } else {
            xmlValue = pval.asContainerable();
        }
    } else {
        throw new IllegalArgumentException("Unknown type " + value);
    }
    if (!(xmlValue instanceof Element) && !(xmlValue instanceof JAXBElement)) {
        xmlValue = new JAXBElement(elementName, xmlValue.getClass(), xmlValue);
    }
    return xmlValue;
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AbstractMessageMethod.java

protected Document getMessageAsXML(ClientMessage m, SendParameters sp)
        throws ParserConfigurationException, FactoryConfigurationError {
    Document doc = DOMUtils.createDoc("http://obm.aliasource.fr/xsd/messages", "messages");
    Element root = doc.getDocumentElement();
    Element me = DOMUtils.createElement(root, "m");
    Date d = m.getDate();//from ww w.  j  a v a  2 s.c  o  m
    if (d == null) {
        d = new Date();
    }
    me.setAttribute("date", "" + d.getTime());

    DOMUtils.createElementAndText(me, "subject", m.getSubject());

    if (m.getMessageId() != null) {
        DOMUtils.createElementAndText(me, "messageId", m.getMessageId().getConversationId());
    }
    Element from = DOMUtils.createElement(me, "from");
    from.setAttribute("addr", m.getSender().getEmail());
    from.setAttribute("displayName", m.getSender().getDisplay());

    Element recipients = DOMUtils.createElement(me, "to");
    List<EmailAddress> recip = m.getTo();
    addRecips(recipients, recip);
    recipients = DOMUtils.createElement(me, "cc");
    recip = m.getCc();
    addRecips(recipients, recip);
    recipients = DOMUtils.createElement(me, "bcc");
    recip = m.getBcc();
    addRecips(recipients, recip);

    Element attachements = DOMUtils.createElement(me, "attachements");
    String[] attachIds = m.getAttachments();
    for (String attach : attachIds) {
        Element ae = DOMUtils.createElement(attachements, "a");
        ae.setAttribute("id", attach);
    }

    Element body = DOMUtils.createElement(me, "body");
    body.setAttribute("type", "text/plain");

    if (sp.isSendPlainText() && m.getBody().getHtml() != null) {
        // we do this server side as firefox richtextarea::getText() seems
        // to drop carriage returns.
        body.setTextContent(new HTMLToPlainConverter().convert(m.getBody().getHtml()));
    } else {
        String plain = m.getBody().getPlain();
        StringBuilder sb = new StringBuilder();
        String[] lines = plain.split("\n");
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].startsWith("> ")) {
                sb.append(lines[i]).append("\n");
            } else {
                sb.append(WordUtils.wrap(lines[i], 80)).append("\n");
            }
        }
        body.setTextContent(sb.toString());
    }

    if (!sp.isSendPlainText()) {
        if (m.getBody().getHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getHtml());
            body.setAttribute("type", "text/html");
        }

        if (m.getBody().getCleanHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getCleanHtml());
            body.setAttribute("type", "text/cleanHtml");
        }

        if (m.getBody().getPartialCleanHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getPartialCleanHtml());
            body.setAttribute("type", "text/partialCleanHtml");
        }
    }

    return doc;
}

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

@Override
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    schemaPi = p;/*from   ww  w. jav  a2  s  .co  m*/
    schemaTargetNamespace = p.targetNamespace();

    model = m;
    options = o;
    result = r;
    diagnosticsOnly = diagOnly;

    result.addDebug(this, 1, schemaPi.name());

    if (!initialised) {
        initialised = true;

        outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory");
        if (outputDirectory == null)
            outputDirectory = options.parameter("outputDirectory");
        if (outputDirectory == null)
            outputDirectory = options.parameter(".");

        outputFilename = "schema_metadata.xml";

        // Check if we can use the output directory; create it if it
        // does not exist
        outputDirectoryFile = new File(outputDirectory);
        boolean exi = outputDirectoryFile.exists();
        if (!exi) {
            try {
                FileUtils.forceMkdir(outputDirectoryFile);
            } catch (IOException e) {
                result.addError(null, 600, e.getMessage());
                e.printStackTrace(System.err);
            }
            exi = outputDirectoryFile.exists();
        }
        boolean dir = outputDirectoryFile.isDirectory();
        boolean wrt = outputDirectoryFile.canWrite();
        boolean rea = outputDirectoryFile.canRead();
        if (!exi || !dir || !wrt || !rea) {
            result.addFatalError(null, 601, outputDirectory);
            throw new ShapeChangeAbortException();
        }

        File outputFile = new File(outputDirectoryFile, outputFilename);

        // check if output file already exists - if so, attempt to delete it
        exi = outputFile.exists();
        if (exi) {

            result.addInfo(this, 3, outputFilename, outputDirectory);

            try {
                FileUtils.forceDelete(outputFile);
                result.addInfo(this, 4);
            } catch (IOException e) {
                result.addInfo(null, 600, e.getMessage());
                e.printStackTrace(System.err);
            }
        }

        // identify map entries defined in the target configuration
        List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries();

        if (mapEntries != null) {

            for (ProcessMapEntry pme : mapEntries) {
                mapEntryByType.put(pme.getType(), pme);
            }
        }

        // reset processed flags on all classes in the schema
        for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) {
            ClassInfo ci = k.next();
            ci.processed(getTargetID(), false);
        }

        // ======================================
        // Parse configuration parameters
        // ======================================

        // nothing to do at present

        // ======================================
        // Set up the document and create root
        // ======================================

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
        DocumentBuilder db;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            result.addFatalError(null, 2);
            throw new ShapeChangeAbortException();
        }
        document = db.newDocument();

        root = document.createElementNS(NS, "ApplicationSchemaMetadata");
        document.appendChild(root);

        addAttribute(root, "xmlns", NS);

        hook = document.createComment("Created by ShapeChange - http://shapechange.net/");
        root.appendChild(hook);
    }

    // create elements documenting the application schema
    Element e_name = document.createElement("name");
    e_name.setTextContent(schemaPi.name());
    Element e_tns = document.createElement("targetNamespace");
    e_tns.setTextContent(schemaPi.targetNamespace());

    Element e_as = document.createElement("ApplicationSchema");
    e_as.appendChild(e_name);
    e_as.appendChild(e_tns);

    Element e_schema = document.createElement("schema");
    e_schema.appendChild(e_as);

    root.appendChild(e_schema);

    /*
     * Now compute relevant metadata.
     */
    processMetadata(e_as);
}

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Gets the <code>entity-listener</code> xml element for
 * <code>listenerClass</code>. Creates it if not found.
 * //from w  ww  . j  a  va  2s  . c o m
 * @param document XML document instance
 * @param entityListenerElement parent XML Element
 * @param listenerClass listener class to search/create
 * @param sourceMetadataProvider metadaProviderId of listener class
 * @return Element found/created, true if element has been created
 */
private Pair<Element, Boolean> getOrCreateListenerElement(Document document, Element entityListenerElement,
        JavaType listenerClass, String sourceMetadataProvider) {

    Pair<Element, Boolean> result = getOrCreateElement(document, entityListenerElement, ENTITY_LISTENER_TAG,
            ImmutablePair.of(CLASS_ATTRIBUTE, listenerClass.getFullyQualifiedTypeName()));

    // If has not been changed
    if (!result.getRight()) {
        return result;
    }

    // Add source MetadataProviderId on description child tag
    Element element = result.getLeft();
    Element description = document.createElement("description");
    description.setTextContent(sourceMetadataProvider);
    element.appendChild(description);

    return ImmutablePair.of(element, true);
}

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

/**
 * {@inheritDoc}/*from   w  w w. j  a  va2  s.  c o  m*/
 */
public void setActiveConfiguration(String name) {

    // Get active configuration element
    Element elem = XmlUtils.findFirstElement(ACTIVE_CONFIGURATION_XPATH,
            getConfigurationDocument().getDocumentElement());
    elem.setTextContent(name);
    saveConfiguration(elem);
}