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.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * Get CXF servlet mapping element.//from  w w w. j  a  v a2 s . co m
 * 
 * @param web Document representation of web.xml
 * @return Element representation of CXF servlet mapping
 */
private Element getServletMapping(Document web) {

    // Create servlet
    Element mapping = web.createElement("servlet-mapping");

    // Create servlet name and add it to servlet
    Element name = web.createElement("servlet-name");
    name.setTextContent("CXFServlet");
    mapping.appendChild(name);

    // Create servlet url pattern and add it to servlet
    Element pattern = web.createElement("url-pattern");
    pattern.setTextContent("/services/*");
    mapping.appendChild(pattern);

    return mapping;
}

From source file:cc.siara.csv_ml_demo.MainActivity.java

/**
 * Evaluates given XPath from Input box against Document generated by
 * parsing csv_ml in input box and sets value or node list to output box.
 *///  w ww .  ja v  a  2  s .  c o m
void processXPath() {
    EditText etInput = (EditText) findViewById(R.id.etInput);
    EditText etXPath = (EditText) findViewById(R.id.etXPath);
    CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty);
    XPath xpath = XPathFactory.newInstance().newXPath();
    MultiLevelCSVParser parser = new MultiLevelCSVParser();
    Document doc = null;
    try {
        doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    if (doc == null)
        return;
    StringBuffer out_str = new StringBuffer();
    try {
        XPathExpression expr = xpath.compile(etXPath.getText().toString());
        try {
            Document outDoc = Util.parseXMLToDOM("<output></output>");
            Element rootElement = outDoc.getDocumentElement();
            NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < ret.getLength(); i++) {
                Object o = ret.item(i);
                if (o instanceof String) {
                    out_str.append(o);
                } else if (o instanceof Node) {
                    Node n = (Node) o;
                    short nt = n.getNodeType();
                    switch (nt) {
                    case Node.TEXT_NODE:
                    case Node.ATTRIBUTE_NODE:
                    case Node.CDATA_SECTION_NODE: // Only one value gets
                                                  // evaluated?
                        if (out_str.length() > 0)
                            out_str.append(',');
                        if (nt == Node.ATTRIBUTE_NODE)
                            out_str.append(n.getNodeValue());
                        else
                            out_str.append(n.getTextContent());
                        break;
                    case Node.ELEMENT_NODE:
                        rootElement.appendChild(outDoc.importNode(n, true));
                        break;
                    }
                }
            }
            if (out_str.length() > 0) {
                rootElement.setTextContent(out_str.toString());
                out_str.setLength(0);
            }
            out_str.append(Util.docToString(outDoc, true));
        } catch (Exception e) {
            // Thrown most likely because the given XPath evaluates to a
            // string
            out_str.append(expr.evaluate(doc));
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml"))
        out_str.delete(0, out_str.indexOf(">") + 1);
    EditText etOutput = (EditText) findViewById(R.id.etOutput);
    etOutput.setText(out_str.toString());
    // tfOutputSize.setText(String.valueOf(xmlString.length()));
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public String replaceOrAddNodeValueByPath(final String path, final String xmlData, final String nodeValue)
        throws SAXException, IOException, XPathExpressionException {

    Document finalDom = parse(xmlData);

    XPath xPath = getXPathInstance();
    NodeList nodeList = (NodeList) (xPath.evaluate(path, finalDom, XPathConstants.NODESET));

    int l = nodeList.getLength();

    if (l == 0) {
        Element elementStructure = createElementStructureByPath((Element) finalDom.getFirstChild(), path);

        List<String> nodeNameList = getNodeList(path);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);
        Element lastElement = finalDom.createElement(lastNodeName);
        lastElement.setTextContent(nodeValue);

        elementStructure.appendChild(lastElement);

    } else {// w w w.j a v  a2  s  . c o m
        Element currentElement = null;
        for (int i = 0; i < l; i++) {
            if (nodeList.item(i) == null)
                continue;
            currentElement = (Element) nodeList.item(i);

            currentElement.setTextContent(nodeValue);
        }
    }

    return DomUtils.elementToString(finalDom.getFirstChild());
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * Add default options section to the configuration.
 * /*from   ww w . j  a  v a  2  s  .c  om*/
 * @param pom
 * @param configuration
 */
protected void appendDefaultOptions(Document pom, Element configuration) {

    Element defaultOptions;
    defaultOptions = pom.createElement("defaultOptions");
    configuration.appendChild(defaultOptions);

    // Soap Headers.
    // execution.configuration.defaultOption.extendedSoapHeaders <-- true
    Element extendedSoapHeaders = pom.createElement("extendedSoapHeaders");
    extendedSoapHeaders.setTextContent(TRUE);
    defaultOptions.appendChild(extendedSoapHeaders);

    // AutoNameResolution to solve naming conflicts.
    // execution.configuration.defaultOption.autoNameResolution <-- true
    Element autoNameResolution = pom.createElement("autoNameResolution");
    autoNameResolution.setTextContent(TRUE);
    defaultOptions.appendChild(autoNameResolution);
}

From source file:gov.usda.DataCatalogClient.Dataset.java

private Element fieldToLegacyXML(String elementName, String elementValue, Document doc) {
    Element fieldElement = null;
    if (elementValue == null) {
        return fieldElement;
    }/*  ww w  . jav  a2 s.  c o  m*/

    fieldElement = doc.createElement(elementName);
    fieldElement.setTextContent(elementValue);
    return fieldElement;
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * Generates Element for service wsdl generation execution
 * //from   ww  w.  j av  a  2  s  .c om
 * @param pom Pom document
 * @param serviceClass to generate
 * @param addressName of the service
 * @param executionID execution identifier
 * @return
 */
private Element createJava2wsExecutionElement(Document pom, JavaType serviceClass, String addressName,
        String executionID) {

    Element serviceExecution = pom.createElement(EXECUTION);

    // execution.id
    Element id = pom.createElement("id");
    id.setTextContent(executionID);

    // execution.phase
    serviceExecution.appendChild(id);
    Element phase = pom.createElement(PHASE2);
    phase.setTextContent("test");
    serviceExecution.appendChild(phase);

    // Execution.Configuration
    Element configuration = pom.createElement(CONFIGURATION2);

    // Execution.configuration.className
    Element className = pom.createElement("className");
    className.setTextContent(serviceClass.getFullyQualifiedTypeName());

    // Excecution.configuration.outputFile
    Element outputFile = pom.createElement("outputFile");
    outputFile.setTextContent(
            "${project.basedir}/src/test/resources/generated/wsdl/".concat(addressName).concat(".wsdl"));

    // execution.configuration.genWsdl
    Element genWsdl = pom.createElement("genWsdl");
    genWsdl.setTextContent(TRUE);

    // execution.configuration.verbose
    Element verbose = pom.createElement("verbose");
    verbose.setTextContent(TRUE);

    // execution.configuration
    configuration.appendChild(className);
    configuration.appendChild(outputFile);
    configuration.appendChild(genWsdl);
    configuration.appendChild(verbose);

    // execution
    serviceExecution.appendChild(configuration);

    // Goals
    Element goals = pom.createElement(GOALS2);
    Element goal = pom.createElement(GOAL2);
    goal.setTextContent("java2ws");
    goals.appendChild(goal);

    serviceExecution.appendChild(goals);
    return serviceExecution;
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w w.  ja va 2s  . c o  m*/
 * <p>
 * Search the execution element using id defined in
 * CXF_WSDL2JAVA_EXECUTION_ID field.
 * </p>
 */
public void disableWsdlLocation() {

    // Get pom.xml
    String pomPath = getPomFilePath();
    Validate.notNull(pomPath, POM_FILE_NOT_FOUND);

    // Get a mutable pom.xml reference to modify it
    MutableFile pomMutableFile = null;
    Document pom;
    try {
        pomMutableFile = getFileManager().updateFile(pomPath);
        pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element root = pom.getDocumentElement();

    // Get plugin element
    Element codegenWsPlugin = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-codegen-plugin']",
            root);

    // If plugin element not exists, message error
    Validate.notNull(codegenWsPlugin,
            "Codegen plugin is not defined in the pom.xml, relaunch again this command.");

    // Checks if already exists the execution.
    Element oldGenerateSourcesCxfServer = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin/executions/execution[id='" + CXF_WSDL2JAVA_EXECUTION_ID + "']",
            root);

    if (oldGenerateSourcesCxfServer != null) {

        Element executionPhase = DomUtils.findFirstElementByName(PHASE2, oldGenerateSourcesCxfServer);

        if (executionPhase != null) {

            Element newPhase = pom.createElement(PHASE2);
            newPhase.setTextContent("none");

            // Remove existing wsdlOption.
            executionPhase.getParentNode().replaceChild(newPhase, executionPhase);

            // Write new XML to disk.
            XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
        }

    }

}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * Creates execution xml pom element for wsdl2java generation
 * /* w  ww  .ja va2s. c  o  m*/
 * @param pom
 * @param wsdlDocument to generate sources
 * @param wsdlLocation current wsdl location
 * @return
 */
private Element createWsdl2JavaExecutionElement(Document pom, Document wsdlDocument, String wsdlLocation) {
    Element newGenerateSourcesCxfServer = pom.createElement(EXECUTION);

    // Create name for id.
    // execution.id
    Element id = pom.createElement("id");
    id.setTextContent(CXF_WSDL2JAVA_EXECUTION_ID);
    newGenerateSourcesCxfServer.appendChild(id);

    // execution.phase
    Element phase = pom.createElement(PHASE2);
    phase.setTextContent("generate-sources");
    newGenerateSourcesCxfServer.appendChild(phase);

    // execution.goals.goal
    Element goals = pom.createElement(GOALS2);
    Element goal = pom.createElement(GOAL2);
    goal.setTextContent("wsdl2java");
    goals.appendChild(goal);
    newGenerateSourcesCxfServer.appendChild(goals);

    // execution.configuration
    Element configuration = pom.createElement(CONFIGURATION2);
    newGenerateSourcesCxfServer.appendChild(configuration);

    // execution.configuration.sourceRoo
    Element sourceRoot = pom.createElement("sourceRoot");
    sourceRoot.setTextContent("${basedir}/target/generated-sources/cxf/server");
    configuration.appendChild(sourceRoot);

    // execution.configuration.defaultOption
    appendDefaultOptions(pom, configuration);

    // execution.configuration.wsdlOptions
    Element wsdlOptions = pom.createElement("wsdlOptions");
    configuration.appendChild(wsdlOptions);

    // execution.configuration.wsdlOptions.wsdlOption
    Element wsdlOption = pom.createElement("wsdlOption");
    wsdlOptions.appendChild(wsdlOption);

    // Check URI correct format
    wsdlLocation = removeFilePrefix(wsdlLocation);

    // execution.configuration.wsdlOptions.wsdlOption.wsdl
    Element wsdl = pom.createElement("wsdl");
    wsdlOption.appendChild(wsdl);
    wsdl.setTextContent(wsdlLocation);

    // execution.configuration.wsdlOptions.wsdlOption.extraargs.extraarg <--
    // "-impl"
    Element extraArgs = pom.createElement("extraargs");
    Element extraArg = pom.createElement("extraarg");
    extraArg.setTextContent("-impl");
    extraArgs.appendChild(extraArg);
    wsdlOption.appendChild(extraArgs);

    Element rootElement = wsdlDocument.getDocumentElement();

    // Configure the packagename to generate client sources
    // execution.configuration.wsdlOptions.wsdlOption.packagenames.packagename
    Element packagenames = pom.createElement("packagenames");
    Element packagename = pom.createElement("packagename");
    String packageName = WsdlParserUtils.getTargetNamespaceRelatedPackage(rootElement);

    packageName = packageName.toLowerCase();
    packagename.setTextContent(packageName.substring(0, packageName.length() - 1));
    packagenames.appendChild(packagename);
    wsdlOption.appendChild(packagenames);

    return newGenerateSourcesCxfServer;
}

From source file:com.connectsdk.service.DLNAService.java

protected String getMessageXml(String serviceURN, String method, String instanceId,
        Map<String, String> params) {
    try {//from   w w  w .  j  a  v a  2s. c  om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        doc.setXmlStandalone(true);
        doc.setXmlVersion("1.0");

        Element root = doc.createElement("s:Envelope");
        Element bodyElement = doc.createElement("s:Body");
        Element methodElement = doc.createElementNS(serviceURN, "u:" + method);
        Element instanceElement = doc.createElement("InstanceID");

        root.setAttribute("s:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
        root.setAttribute("xmlns:s", "http://schemas.xmlsoap.org/soap/envelope/");

        doc.appendChild(root);
        root.appendChild(bodyElement);
        bodyElement.appendChild(methodElement);
        if (instanceId != null) {
            instanceElement.setTextContent(instanceId);
            methodElement.appendChild(instanceElement);
        }

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Element element = doc.createElement(key);
                element.setTextContent(value);
                methodElement.appendChild(element);
            }
        }
        return xmlToString(doc, true);
    } catch (Exception e) {
        return null;
    }
}

From source file:fi.csc.kapaVirtaAS.WSDLManipulator.java

public void generateVirtaKapaWSDL() throws Exception {
    // Fetch current WSDL-file
    File inputFile = new File("opiskelijatiedot.wsdl");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputFile);
    doc.setXmlVersion("1.0");
    doc.getDocumentElement().normalize();

    // Manipulate WSDL to meet the requirements of xroad

    // Root element <wsdl:definitions> attribute manipulations
    Element root = doc.getDocumentElement();
    root.setAttribute("xmlns:" + conf.getXroadSchemaPrefixForWSDL(), conf.getXroadSchema());
    root.setAttribute("xmlns:" + conf.getXroadIdSchemaPrefixForWSDL(), conf.getXroadIdSchema());

    root = replaceAttribute(root, "xmlns:tns", conf.getAdapterServiceSchema());
    root = replaceAttribute(root, "targetNamespace", conf.getAdapterServiceSchema());

    // Schema elements <xs:schema> attribute manipulations
    NodeList schemas = root.getElementsByTagName("xs:schema");

    for (int i = 0; i < schemas.getLength(); ++i) {
        Node schema = schemas.item(i);
        if (schema != null) {
            NamedNodeMap schemaAttributes = schema.getAttributes();
            if (schemaAttributes != null && schemaAttributes.getNamedItem("xmlns:virtaluku") != null) {
                schemaAttributes.getNamedItem("xmlns:virtaluku").setTextContent(conf.getAdapterServiceSchema());

                if (schemaAttributes != null && schemaAttributes.getNamedItem("targetNamespace") != null) {
                    schemaAttributes.getNamedItem("targetNamespace")
                            .setTextContent(conf.getAdapterServiceSchema());
                }//  w  ww  .j av  a  2s  .com

                Element el = (Element) schema.appendChild(doc.createElement("xs:import"));
                el.setAttribute("id", conf.getXroadSchemaPrefixForWSDL());
                el.setAttribute("namespace", conf.getXroadSchema());
                el.setAttribute("schemaLocation", conf.getXroadSchema());

                // Remove Request part from xs:element -elements
                NodeList elementsInSchema = schema.getChildNodes();
                for (int j = 0; j < elementsInSchema.getLength(); ++j) {
                    Element el1 = (Element) elementsInSchema.item(j);
                    if (el1.getNodeName() == "xs:element") {
                        replaceAttribute(el1, "name",
                                StringUtils.substringBefore(el1.getAttribute("name"), "Request"));
                    }
                }
            }

        }
    }

    // Append xroad request headers
    Element xroadReqHeadersElement = doc.createElement("wsdl:message");
    xroadReqHeadersElement.setAttribute("name", "requestheader");

    for (String xroadHeader : conf.getXroadHeaders()) {
        Element reqHeader = doc.createElement("wsdl:part");
        reqHeader.setAttribute("name", xroadHeader);
        reqHeader.setAttribute("element", conf.getXroadSchemaPrefixForWSDL() + ":" + xroadHeader);
        xroadReqHeadersElement.appendChild(reqHeader);
    }

    root.appendChild(xroadReqHeadersElement);

    NodeList childrenList = root.getChildNodes();
    for (int i = 0; i < childrenList.getLength(); ++i) {

        if (childrenList.item(i).getNodeName().contains(":binding")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    Element el1 = (Element) binding.item(j)
                            .appendChild(doc.createElement(conf.getXroadIdSchemaPrefixForWSDL() + ":version"));
                    el1.setTextContent(conf.getVirtaVersionForXRoad());

                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {

                        // Append xroad wsdl:binding operation headers
                        if (child.getNodeName().contains(":input") || child.getNodeName().contains(":output")) {
                            Element el = (Element) child;
                            for (String xroadHeader : conf.getXroadHeaders()) {
                                el.appendChild(soapHeader(doc.createElement("soap:header"), "tns:requestheader",
                                        xroadHeader, "literal"));
                            }
                        }

                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
            // Remove Request from wsdl:message > wsdl:part element so that can see element
        } else if (childrenList.item(i).getNodeName().contains(":message") && childrenList.item(i)
                .getAttributes().getNamedItem("name").getNodeValue().contains("Request")) {
            Element part = (Element) childrenList.item(i).getFirstChild().getNextSibling();
            replaceAttribute(part, "element",
                    StringUtils.substringBefore(part.getAttribute("element"), "Request"));
        }

        // Change wsdl input names to meet XRoad standard
        if (childrenList.item(i).getNodeName().contains(":portType")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
        }

        // Append kapaVirtaAS service address
        if (childrenList.item(i).getNodeName().contains(":service")) {
            NodeList service = childrenList.item(i).getChildNodes();
            for (int j = 0; j < service.getLength(); ++j) {
                if (service.item(j).getNodeName().contains(":port")) {
                    for (Node child = service.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":address")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "location", conf.getAdapterServiceSOAPURL());
                        }
                    }
                }
            }
        }
    }

    // Write manipulated WSDL to file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(conf.getAdapterServiceWSDLPath() + "/kapavirta_as.wsdl"));
    transformer.transform(source, result);
}