Example usage for org.w3c.dom Node setTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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:com.mirth.connect.model.util.ImportConverter.java

/**
 * Update the child property elements of a properties element
 * //from   w  w  w .  jav a 2 s.c  o m
 * @param document
 *            The document to use to generate new Elements.
 * @param properties
 *            The properties element to be modified.
 * @param defaultProperties
 *            Properties to be added only if they are missing.
 * @param changeProperties
 *            Properties to be added if missing, or changed if already
 *            present.
 */
private static void updateProperties(Document document, Element properties,
        Map<String, String> defaultProperties, Map<String, String> changeProperties) throws Exception {
    // Make a working copy of the properies so we can remove existing
    // properties
    Map<String, String> missingProperties = new HashMap<String, String>();
    missingProperties.putAll(defaultProperties);
    missingProperties.putAll(changeProperties);

    // Removes all existing properties from the working copy, and changes
    // the value of any
    // change properties
    NodeList existingProperties = properties.getElementsByTagName("property");
    for (int i = 0; i < existingProperties.getLength(); i++) {

        Node existingProperty = existingProperties.item(i);
        Node existingPropertyNameAttribute = existingProperty.getAttributes().getNamedItem("name");
        String existingPropertyName = existingPropertyNameAttribute.getNodeValue();
        if (missingProperties.containsKey(existingPropertyName)) {
            if (changeProperties.containsKey(existingPropertyName)) {
                existingProperty.setTextContent(changeProperties.get(existingPropertyName));
            }
            missingProperties.remove(existingPropertyName);
        }
    }

    // And any remaining default or change properties
    for (Map.Entry<String, String> thisEntry : missingProperties.entrySet()) {
        Element newProperty = document.createElement("property");
        newProperty.setAttribute("name", thisEntry.getKey());
        newProperty.setTextContent(thisEntry.getValue());
        properties.appendChild(newProperty);
    }
}

From source file:org.apereo.lap.services.pipeline.KettleBasePipelineProcessor.java

/**
 * Dynamically change the file path to the Weka Scoring model file
 * //from  www  .j a va 2s. c o  m
 * @param file the transformation file
 */
protected void updateWekaScoringModel(File file) {
    assert file != null;

    try {
        // read the XML file
        Document document = parseXmlDocument(file);

        // get the "step" nodes
        NodeList steps = document.getElementsByTagName("step");
        for (int i = 0; i < steps.getLength(); i++) {
            Node node = steps.item(i);
            NodeList stepNodes = node.getChildNodes();

            // iterate over each child node, only if the node is a Weka Scoring node
            for (int j = 0; j < stepNodes.getLength(); j++) {
                Node stepNode = stepNodes.item(j);
                if (StringUtils.equalsIgnoreCase(stepNode.getNodeName(), "name")) {
                    if (!StringUtils.equalsIgnoreCase(stepNode.getTextContent(), WEKA_SCORING_STEP_NAME)) {
                        break;
                    } else {
                        continue;
                    }
                } else if (StringUtils.equalsIgnoreCase(stepNode.getNodeName(), WEKA_SCORING_TAG_NAME)) {
                    NodeList wekaScoringNodeList = stepNode.getChildNodes();

                    // iterate over the Weka Scoring child nodes
                    for (int k = 0; k < wekaScoringNodeList.getLength(); k++) {
                        Node wekaScoringNode = wekaScoringNodeList.item(k);

                        // update the file path to the appropriate file on the classpath
                        if (StringUtils.equalsIgnoreCase(wekaScoringNode.getNodeName(),
                                WEKA_SCORING_MODEL_FILE_TAG_NAME)) {
                            File scoringModelFile = getFile(makeFilePath(SCORING_MODEL_FILE_NAME));
                            logger.info("Updated Weka Scoring Model file path from '"
                                    + wekaScoringNode.getTextContent() + "' to '"
                                    + scoringModelFile.getAbsolutePath() + "'");
                            wekaScoringNode.setTextContent(scoringModelFile.getAbsolutePath());
                            isWekaScoringFileUpdated = true;

                            break;
                        }
                    }

                    // if Weka Scoring model file updated, no need to continue processing
                    if (isWekaScoringFileUpdated) {
                        break;
                    }
                }
            }

            // if Weka Scoring model file updated, no need to continue processing
            if (isWekaScoringFileUpdated) {
                break;
            }
        }

        // write the XML document to a file on the file system
        writeXmlDocument(document, file);
    } catch (Exception e) {
        throw new RuntimeException("Error updating Weka Scoring model file path transformation XML file: "
                + file.getAbsoluteFile(), e);
    }
}

From source file:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

@Override
public String newEmptyObject(String pid, List<String> oldIDs, List<String> collections, String logMessage)
        throws BackendMethodFailedException, BackendInvalidCredsException {
    InputStream emptyObjectStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("EmptyObject.xml");
    Document emptyObject = DOM.streamToDOM(emptyObjectStream, true);

    XPathSelector xpath = DOM.createXPathSelector("foxml", Constants.NAMESPACE_FOXML, "rdf",
            Constants.NAMESPACE_RDF, "d", Constants.NAMESPACE_RELATIONS, "dc", Constants.NAMESPACE_DC, "oai_dc",
            Constants.NAMESPACE_OAIDC);/*  ww  w  .  j a  v  a 2  s  .c  o m*/
    //Set pid
    Node pidNode = xpath.selectNode(emptyObject, "/foxml:digitalObject/@PID");
    pidNode.setNodeValue(pid);

    Node rdfNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/@rdf:about");
    rdfNode.setNodeValue("info:fedora/" + pid);

    //add Old Identifiers to DC
    Node dcIdentifierNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc/dc:identifier");
    dcIdentifierNode.setTextContent(pid);
    Node parent = dcIdentifierNode.getParentNode();
    for (String oldID : oldIDs) {
        Node clone = dcIdentifierNode.cloneNode(true);
        clone.setTextContent(oldID);
        parent.appendChild(clone);
    }

    Node collectionRelationNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/d:isPartOfCollection");

    parent = collectionRelationNode.getParentNode();
    //remove the placeholder relationNode
    parent.removeChild(collectionRelationNode);

    for (String collection : collections) {
        Node clone = collectionRelationNode.cloneNode(true);
        clone.getAttributes().getNamedItem("rdf:resource").setNodeValue("info:fedora/" + collection);
        parent.appendChild(clone);
    }

    String emptyObjectAsString;
    try {
        emptyObjectAsString = DOM.domToString(emptyObject);
    } catch (TransformerException e) {
        //TODO This is not really a backend exception
        throw new BackendMethodFailedException("Failed to convert DC back to string", e);
    }
    WebResource.Builder request = restApi.path("/").path(urlEncode(pid)).queryParam("state", "I")
            .type(MediaType.TEXT_XML_TYPE);
    int tries = 0;
    while (true) {
        tries++;
        try {
            return request.post(String.class, emptyObjectAsString);
        } catch (UniformInterfaceException e) {
            try {
                handleResponseException(pid, tries, maxTriesPost, e);
            } catch (BackendInvalidResourceException e1) {
                //Ignore, never happens
                throw new RuntimeException(e1);
            }
        }
    }
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToForms.java

/**
 * Gets DOM section for the form model choice, whether multiple or single, inline or select.
 * //from   ww  w .  j a  v  a2  s . c  o m
 * @param formInstance
 *            the form instance
 * @param formElement
 *            the form element
 * @param associations
 *            the associations
 * @param modelChoice
 *            the model choice
 * @param initParams
 *            the init parameters, restricted to the model choice
 * @param formIsReadOnly
 * 
 * @return the form model choice
 * @throws ServletException
 */
private void getFormModelChoice(AlfrescoTransaction transaction, Map<String, GenericClass> alfrescoNodes,
        Document formInstance, Element formElement, List<GenericAssociation> associations,
        ModelChoiceType modelChoice, Map<String, String> initParams, boolean formIsReadOnly)
        throws ServletException {
    Element modelChoiceReference = formInstance.createElement(modelChoice.getUniqueName());
    int maxBound = modelChoice.getMaxBound();
    if (maxBound != 1) {
        modelChoiceReference.setAttribute("bound", "" + maxBound);
    }
    boolean extended = isExtendedWidget(modelChoice);
    String widget = "select";
    if (isInline(modelChoice)) {
        widget = "inline";
    } else {
        if (extended) {
            widget = "extended";
        }
    }
    modelChoiceReference.setAttribute("widget", widget); // for debugging purposes

    // the list of associated items that will appear in the instance
    List<GenericAssociation> matched;

    // #1193: overriding of existing objects' values
    String initIds = initParams.get("id"); // <-- multiple targets are allowed, if
    // comma-separated
    if (initIds != null) {
        // CAUTION: if overriding, targets from the repository are ignored
        matched = overrideAssociations(transaction, modelChoice, initIds);
        initParams.remove("id");
    } else {
        String alfrescoName = modelChoice.getAlfrescoName();
        matched = getAssociationAndRemove(alfrescoName, associations);
    }

    if (extended || isInline(modelChoice)) {
        for (GenericAssociation association : matched) {
            GenericClassReference target = association.getTarget();
            getModelChoiceItem(transaction, alfrescoNodes, formInstance, modelChoiceReference, modelChoice,
                    target, initParams, formIsReadOnly);
        }
        // add one for xforms if : not even one is present or cardinality is multiple
        if (matched.size() == 0 || modelChoice.getMaxBound() != 1) {
            newFormModelChoiceItem(formInstance, modelChoice, modelChoiceReference, transaction, alfrescoNodes,
                    initParams, formIsReadOnly, false);
        }
    } else {
        // plain select widget applies only when the field is: not inline and not extended
        String ids = "";
        boolean first = true;
        for (GenericAssociation asso : matched) {
            if (!first) {
                ids += " ";
            }
            ids = asso.getTarget().getValue();
        }
        Node node = formInstance.createElement(MsgId.INT_INSTANCE_ASSOCIATION_ITEM.getText());
        node.setTextContent(ids);
        modelChoiceReference.appendChild(node);
    }
    formElement.appendChild(modelChoiceReference);
}

From source file:com.crawljax.plugins.errorreport.ErrorReport.java

private Document addMarker(String id, Document doc, String xpath) {
    try {//from w w  w . j  a  v  a  2s.c o m

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }
        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:com.collabnet.tracker.core.PTrackerWebServicesClient.java

/**
 * This is a check to ensure that invalid next page calls are not sent to the server.
 * @param pageInfo/*ww w.j a va  2s  . c  o  m*/
 * @throws Exception
 */
public void validateNextPage(Node pageInfo, String altQueryRef) throws Exception {
    Node child = pageInfo.getFirstChild();
    String msg = "Next page does not have a valid query reference";
    String name, value;
    while (child != null) {
        name = child.getNodeName();
        value = child.getTextContent();
        if (name.contains("queryReference")) {
            if (value == null || value.length() < 1) {
                if (altQueryRef == null)
                    throw new Exception(msg);
                child.setTextContent(altQueryRef);
            }
            return;
        }
        child = child.getNextSibling();
    }
    throw new Exception(msg);
}

From source file:at.ait.dme.yuma.server.map.KMLConverterServlet.java

private Document convert(Document kml, AffineTransformation interpolator) {
    // Get all 'coordinates' nodes
    NodeList coordNodes = kml.getElementsByTagName("coordinates");

    StringBuffer sb;//from www. j a v a2  s.  co  m
    String[] coords;
    String[] lonlat;
    TransformationResult ir;
    for (int i = 0; i < coordNodes.getLength(); i++) {
        // Construct result coordinate string
        sb = new StringBuffer();

        // Original WGS84 coordinate set: 'lon,lat,alt lon,lat,alt lon,lat,alt ...'
        Node n = coordNodes.item(i);

        // Split into individual WGS84 coordinates: 'lon,lat,alt'
        coords = n.getTextContent().trim().split(" ");

        int lastX = 0;
        int lastY = 0;
        double dist = 0;
        for (int j = 0; j < coords.length; j++) {
            // Split into coordinate values
            lonlat = coords[j].split(",");
            if (lonlat.length > 1) {
                try {
                    // Interpolate
                    ir = interpolator.getXYFromKnownLatLon(
                            new WGS84Coordinate(Double.parseDouble(lonlat[1]), Double.parseDouble(lonlat[0])));

                    // Threshold check: does the distance between this point and 
                    // the last one exceed the threshold? --> Outlier! Don't add
                    dist = Math.sqrt(Math.pow((ir.xy.x - lastX), 2) + Math.pow((ir.xy.y - lastY), 2));
                    if ((j == 0) || (dist < outlierThreshold)) {
                        sb.append(ir.xy.x + "," + ir.xy.y + "\n");
                        lastX = ir.xy.x;
                        lastY = ir.xy.y;
                    }
                } catch (TransformationException e) {
                    // Cannot happen unless interpolator is invalid
                    throw new RuntimeException(e);
                }
            }
        }

        // Replace node
        n.setTextContent(sb.toString());
    }
    return kml;
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

private void storeConfigObj(List<Configuration> configs, File featureManifestXmlFile, File featureSqlDir,
        String environmentName) throws PhrescoException {
    try {//w w w.  j av  a2s .  com
        if (!featureManifestXmlFile.isFile()) {
            throw new PhrescoException("manifest file is not available");
        }

        // Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(featureManifestXmlFile);
        doc.getDocumentElement().normalize();

        // xpath
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPathInstance = factory.newXPath();

        for (Configuration configuration : configs) {
            Properties properties = configuration.getProperties();
            Enumeration em = properties.keys();
            while (em.hasMoreElements()) {
                String insertQuery = "";
                String insertFieldQuery = "";

                String deleteQuery = "";
                String deleteFieldQuery = "";

                String tableName = "";
                String variableName = "";
                String defaultValue = "";

                String constructedQuery = "";
                String key = (String) em.nextElement();
                Object object = properties.get(key);

                // get config object for this key
                String xPathQuery = CONFIG_XPATH + key + CONFIG_XPATH_END_TAG;
                XPathExpression xPathExpression = xPathInstance.compile(xPathQuery);
                //evalute the xpath query in the entire xml document and define the return type
                Object results = xPathExpression.evaluate(doc, XPathConstants.NODESET);
                NodeList nList = (NodeList) results;

                // config objects
                for (int i = 0; i < nList.getLength(); i++) {
                    Node nNode = nList.item(i);
                    // get config object values
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        // getting child nodes to construct query
                        NodeList childNodes = nNode.getChildNodes();
                        for (int temp1 = 0; temp1 < childNodes.getLength(); temp1++) {
                            Node childNode = childNodes.item(temp1);
                            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (TABLE_NAME.equals(childNode.getNodeName())) {
                                    tableName = childNode.getTextContent();
                                    if (!VARIABLE_FIELD.equals(tableName)) {
                                        return;
                                    }
                                    deleteQuery = deleteQuery + DELETE_FROM + childNode.getTextContent() + WHERE
                                            + NAME_FIELD + EQUAL;
                                    insertQuery = insertQuery + INSERT_INTO + childNode.getTextContent()
                                            + VARIABLE_START_TAG + NAME_FIELD + SQL_VARIABLE_SEP + VALUE_FIELD
                                            + VARIABLE_END_TAG + VALUES_START_TAG;
                                } else if (VARIABLE_NAME.equals(childNode.getNodeName())) {
                                    variableName = childNode.getTextContent();
                                    deleteFieldQuery = SINGLE_QUOTE + childNode.getTextContent() + SINGLE_QUOTE
                                            + SEMI_COLON + LINE_BREAK;
                                } else if (CURRENT_VALUE.equals(childNode.getNodeName())) {
                                    childNode.setTextContent(object.toString());
                                }
                                defaultValue = object.toString();
                                insertFieldQuery = variableName + SQL_VALUE_SEP + defaultValue + VALUES_END_TAG;
                            }
                        }
                    }
                }

                constructedQuery = deleteQuery + deleteFieldQuery + insertQuery + insertFieldQuery;

                List<File> sqlFolders = getSqlFolders(featureSqlDir);
                for (File sqlFolder : sqlFolders) {
                    replaceSqlBlock(sqlFolder, CONFIGURATION + environmentName + DOT_SQL, key,
                            constructedQuery);
                }
            }
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(featureManifestXmlFile.getPath()));
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
}

From source file:com.mirth.connect.model.util.ImportConverter.java

/** Convert a single source or destination connector from pre-1.8 to 1.8 */
private static void convertOneConnectorFor1_8(Document document, Element connectorRoot) throws Exception {

    Node transportNode = getConnectorTransportNode(connectorRoot);
    String transportNameText = transportNode.getTextContent();

    Element propertiesElement = getPropertiesElement(connectorRoot);

    // Properties to be added if they're missing.
    Map<String, String> propertyDefaults = new HashMap<String, String>();
    propertyDefaults.put("charsetEncoding", "DEFAULT_ENCODING");
    propertyDefaults.put("FTPAnonymous", "1");
    propertyDefaults.put("outputAppend", "0");
    propertyDefaults.put("passive", "1");
    propertyDefaults.put("password", "anonymous");
    propertyDefaults.put("username", "anonymous");
    propertyDefaults.put("validateConnections", "1");

    // Properties to be added if missing, or reset if present
    Map<String, String> propertyChanges = new HashMap<String, String>();

    if (transportNameText.equals("File Reader")) {

        propertyDefaults.put("scheme", "file");
        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    } else if (transportNameText.equals("File Writer")) {

        propertyDefaults.put("scheme", "file");
        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    } else if (transportNameText.equals("FTP Reader")) {

        transportNode.setTextContent("File Reader");

        propertyDefaults.put("scheme", "ftp");
        propertyChanges.put("DataType", "File Reader");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    } else if (transportNameText.equals("FTP Writer")) {

        transportNode.setTextContent("File Writer");

        propertyDefaults.put("scheme", "ftp");
        propertyChanges.put("DataType", "File Writer");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    } else if (transportNameText.equals("SFTP Reader")) {

        transportNode.setTextContent("File Reader");

        propertyDefaults.put("scheme", "sftp");
        propertyDefaults.put("FTPAnonymous", "0");
        propertyChanges.put("DataType", "File Reader");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    } else if (transportNameText.equals("SFTP Writer")) {

        transportNode.setTextContent("File Writer");

        propertyDefaults.put("scheme", "sftp");
        propertyDefaults.put("FTPAnonymous", "0");
        propertyChanges.put("DataType", "File Writer");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    }//ww  w .j  a v a 2 s .  com
}

From source file:com.photon.phresco.framework.rest.api.ProjectService.java

private void setVersionInArtifactItem(List<org.w3c.dom.Element> elements, String version) {
    for (org.w3c.dom.Element element : elements) {
        if ("artifactItems".equals(element.getTagName())) {
            NodeList artifactItem = element.getElementsByTagName("artifactItem");
            for (int i = 0; i < artifactItem.getLength(); i++) {
                Node artifactItemNode = artifactItem.item(i);
                boolean check = false;
                NodeList childNodes = artifactItemNode.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node childNode = childNodes.item(j);
                    if ("artifactId".equals(childNode.getNodeName())
                            && childNode.getTextContent().equalsIgnoreCase("selenium-server-standalone")) {
                        check = true;//from   w w w . java 2s .co m
                    }
                    if (check && "version".equals(childNode.getNodeName())) {
                        childNode.setTextContent(version);
                        break;
                    }
                }
            }
        }
    }
}