Example usage for org.w3c.dom Node TEXT_NODE

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

Introduction

In this page you can find the example usage for org.w3c.dom Node TEXT_NODE.

Prototype

short TEXT_NODE

To view the source code for org.w3c.dom Node TEXT_NODE.

Click Source Link

Document

The node is a Text node.

Usage

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }/*from   w w  w .jav  a 2  s  .com*/

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:ca.mcgill.music.ddmal.mei.MeiXmlReader.java

private MeiElement makeMeiElement(Node element) {
    // TODO: CDATA
    // Comments get a name #comment
    String nshref = element.getNamespaceURI();
    String nsprefix = element.getPrefix();
    MeiNamespace elns = new MeiNamespace(nshref, nsprefix);
    MeiElement e = new MeiElement(elns, element.getNodeName());
    if (element.getNodeType() == Node.COMMENT_NODE) {
        e.setValue(element.getNodeValue());
    }//from  w  w w .j a v a  2 s.co m

    NamedNodeMap attributes = element.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node item = attributes.item(i);
            if (XML_ID_ATTRIBUTE.equals(item.getNodeName())) {
                e.setId(item.getNodeValue());
            } else {
                String attrns = item.getNamespaceURI();
                String attrpre = item.getPrefix();
                MeiNamespace atns = new MeiNamespace(attrns, attrpre);
                MeiAttribute a = new MeiAttribute(atns, item.getNodeName(), item.getNodeValue());
                e.addAttribute(a);
            }
        }
    }

    NodeList childNodes = element.getChildNodes();
    MeiElement lastElement = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if (item.getNodeType() == Node.TEXT_NODE) {
            if (lastElement == null) {
                e.setValue(item.getNodeValue());
            } else {
                lastElement.setTail(item.getNodeValue());
            }
        } else {
            MeiElement child = makeMeiElement(item);
            e.addChild(child);
            lastElement = child;
        }
    }
    return e;
}

From source file:de.huberlin.wbi.hiway.am.dax.DaxApplicationMaster.java

@Override
public void parseWorkflow() {
    Map<Object, TaskInstance> tasks = new HashMap<>();
    System.out.println("Parsing Pegasus DAX " + getWorkflowFile());

    try {/*from ww w.j a  v  a2s.  c o  m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new File(getWorkflowFile().getLocalPath().toString()));
        NodeList jobNds = doc.getElementsByTagName("job");

        for (int i = 0; i < jobNds.getLength(); i++) {
            Element jobEl = (Element) jobNds.item(i);
            String id = jobEl.getAttribute("id");
            String taskName = jobEl.getAttribute("name");
            DaxTaskInstance task = new DaxTaskInstance(getRunId(), taskName);
            task.setRuntime(
                    jobEl.hasAttribute("runtime") ? Double.parseDouble(jobEl.getAttribute("runtime")) : 0d);
            tasks.put(id, task);

            StringBuilder arguments = new StringBuilder();
            NodeList argumentNds = jobEl.getElementsByTagName("argument");
            for (int j = 0; j < argumentNds.getLength(); j++) {
                Element argumentEl = (Element) argumentNds.item(j);

                NodeList argumentChildNds = argumentEl.getChildNodes();
                for (int k = 0; k < argumentChildNds.getLength(); k++) {
                    Node argumentChildNd = argumentChildNds.item(k);
                    String argument = "";

                    switch (argumentChildNd.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        Element argumentChildEl = (Element) argumentChildNd;
                        if (argumentChildEl.getNodeName().equals("file")) {
                            if (argumentChildEl.hasAttribute("name")) {
                                argument = argumentChildEl.getAttribute("name");
                            }
                        } else if (argumentChildEl.getNodeName().equals("filename")) {
                            if (argumentChildEl.hasAttribute("file")) {
                                argument = argumentChildEl.getAttribute("file");
                            }
                        }
                        break;
                    case Node.TEXT_NODE:
                        argument = argumentChildNd.getNodeValue().replaceAll("\\s+", " ").trim();
                        break;
                    default:
                    }

                    if (argument.length() > 0) {
                        arguments.append(" ").append(argument);
                    }
                }
            }

            NodeList usesNds = jobEl.getElementsByTagName("uses");
            for (int j = 0; j < usesNds.getLength(); j++) {
                Element usesEl = (Element) usesNds.item(j);
                String link = usesEl.getAttribute("link");
                String fileName = usesEl.getAttribute("file");
                long size = usesEl.hasAttribute("size") ? Long.parseLong(usesEl.getAttribute("size")) : 0l;
                List<String> outputs = new LinkedList<>();

                switch (link) {
                case "input":
                    if (!getFiles().containsKey(fileName)) {
                        Data data = new Data(fileName);
                        data.setInput(true);
                        getFiles().put(fileName, data);
                    }
                    Data data = getFiles().get(fileName);
                    task.addInputData(data, size);
                    break;
                case "output":
                    if (!getFiles().containsKey(fileName))
                        getFiles().put(fileName, new Data(fileName));
                    data = getFiles().get(fileName);
                    task.addOutputData(data, size);
                    data.setInput(false);
                    outputs.add(fileName);
                    break;
                default:
                }

                task.getReport()
                        .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                                task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                                JsonReportEntry.KEY_INVOC_OUTPUT, new JSONObject().put("output", outputs)));
            }

            task.setCommand(taskName + arguments.toString());
            System.out.println(
                    "Adding task " + task + ": " + task.getInputData() + " -> " + task.getOutputData());
        }

        NodeList childNds = doc.getElementsByTagName("child");
        for (int i = 0; i < childNds.getLength(); i++) {
            Element childEl = (Element) childNds.item(i);
            String childId = childEl.getAttribute("ref");
            TaskInstance child = tasks.get(childId);

            NodeList parentNds = childEl.getElementsByTagName("parent");
            for (int j = 0; j < parentNds.getLength(); j++) {
                Element parentEl = (Element) parentNds.item(j);
                String parentId = parentEl.getAttribute("ref");
                TaskInstance parent = tasks.get(parentId);

                child.addParentTask(parent);
                parent.addChildTask(child);
            }
        }

        for (TaskInstance task : tasks.values()) {
            if (task.getChildTasks().size() == 0) {
                for (Data data : task.getOutputData()) {
                    data.setOutput(true);
                }
            }

            task.getReport()
                    .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                            task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                            JsonReportEntry.KEY_INVOC_SCRIPT, task.getCommand()));
        }

    } catch (WorkflowStructureUnknownException | IOException | JSONException | ParserConfigurationException
            | SAXException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    getScheduler().addTasks(tasks.values());
}

From source file:Main.java

private static void renderNode(StringBuffer sb, Node node) {
    if (node == null) {
        sb.append("null");
        return;/*  w  ww  .  j a va  2s. co  m*/
    }
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        Node root = ((Document) node).getDocumentElement();
        renderNode(sb, root);
        break;

    case Node.ELEMENT_NODE:
        String name = getNodeNameWithNamespace(node);
        NamedNodeMap attributes = node.getAttributes();
        if (attributes.getLength() == 0) {
            sb.append("<" + name + ">");
        } else {
            sb.append("<" + name + " ");
            int attrlen = attributes.getLength();
            for (int i = 0; i < attrlen; i++) {
                Node attr = attributes.item(i);
                String attrName = getNodeNameWithNamespace(attr);
                sb.append(attrName + "=\"" + escapeChars(attr.getNodeValue()));
                if (i < attrlen - 1)
                    sb.append("\" ");
                else
                    sb.append("\">");
            }
        }
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                renderNode(sb, children.item(i));
            }
        }
        sb.append("</" + name + ">");
        break;

    case Node.TEXT_NODE:
        sb.append(escapeChars(node.getNodeValue()));
        break;

    case Node.CDATA_SECTION_NODE:
        sb.append("<![CDATA[" + node.getNodeValue() + "]]>");
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        sb.append("<?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?>");
        break;

    case Node.ENTITY_REFERENCE_NODE:
        sb.append("&" + node.getNodeName() + ";");
        break;

    case Node.DOCUMENT_TYPE_NODE:
        // Ignore document type nodes
        break;

    case Node.COMMENT_NODE:
        sb.append("<!--" + node.getNodeValue() + "-->");
        break;
    }
    return;
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.TextWriter.java

private void writeNode(Writer writer, Node node) throws IOException {
    short type = node.getNodeType();
    switch (type) {

    case Node.DOCUMENT_NODE:
        document(writer, (Document) node);
        break;//  ww w  .j  a  v  a 2 s  .co m

    case Node.DOCUMENT_FRAGMENT_NODE:
        documentFragment(writer, (DocumentFragment) node);
        break;

    case Node.DOCUMENT_TYPE_NODE:
        documentType(writer, (DocumentType) node);
        break;

    case Node.ELEMENT_NODE:
        element(writer, (Element) node);
        break;

    case Node.ATTRIBUTE_NODE:
        attribute(writer, (Attr) node);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        entityReference(writer, (EntityReference) node);
        break;

    case Node.ENTITY_NODE:
        entity(writer, (Entity) node);
        break;

    case Node.NOTATION_NODE:
        notation(writer, (Notation) node);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        procInst(writer, (ProcessingInstruction) node);
        break;

    case Node.TEXT_NODE:
        text(writer, (Text) node);
        break;

    case Node.CDATA_SECTION_NODE:
        cDataSection(writer, (CDATASection) node);
        break;

    case Node.COMMENT_NODE:
        comment(writer, (Comment) node);
        break;
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.XmlUtils.java

public static String getXmlDataSubstituteNode(Node node, String substituteWith, String substituteInWhat) {
    StringBuilder sb = new StringBuilder();
    switch (node.getNodeType()) {
    case Node.COMMENT_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
    case Node.PROCESSING_INSTRUCTION_NODE:
        break;/*from   w w  w  . j  ava2  s  . c  om*/
    case Node.DOCUMENT_NODE:
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.ELEMENT_NODE: {
        String nodeName = node.getNodeName();
        if (!substituteInWhat.equals(nodeName)) {
            sb.append("<").append(nodeName);
            StringBuilder attrs = new StringBuilder();
            StringBuilder children = new StringBuilder();
            NamedNodeMap nnm = node.getAttributes();
            if (nnm != null) {
                for (int i = 0; i < nnm.getLength(); i++) {
                    Node attr = nnm.item(i);
                    attrs.append(" ").append(getXmlDataSubstituteNode(attr, substituteWith, substituteInWhat));
                }
            }
            NodeList nl = node.getChildNodes();
            if (nl != null) {
                for (int i = 0; i < nl.getLength(); i++) {
                    Node child = nl.item(i);
                    if (child.getNodeType() == Node.ATTRIBUTE_NODE) {
                        attrs.append(" ")
                                .append(getXmlDataSubstituteNode(child, substituteWith, substituteInWhat));
                    } else {
                        children.append(getXmlDataSubstituteNode(child, substituteWith, substituteInWhat));
                    }
                }
            }
            sb.append(attrs.toString());
            if (children.length() > 0) {
                sb.append(">").append(children.toString()).append("</").append(nodeName).append(">");
            } else {
                sb.append("/>");
            }
        } else {
            sb.append(substituteWith);
        }
        break;
    }
    case Node.ATTRIBUTE_NODE: {
        sb.append(node.getNodeName()).append("=\"").append(StringEscapeUtils.escapeXml(node.getNodeValue()))
                .append("\"");
        break;
    }
    case Node.CDATA_SECTION_NODE: {
        sb.append("<![CDATA[").append(StringEscapeUtils.escapeXml(node.getNodeValue())).append("]]>");
    }
    case Node.TEXT_NODE: {
        sb.append(StringEscapeUtils.escapeXml(node.getNodeValue()));
    }
    }
    return sb.toString();
}

From source file:com.adaptris.util.text.xml.XPath.java

/**
 * returns an array of string values taken from a list of elements returned by
 * an xpath/*w ww. j a  v  a2s . c o  m*/
 *
 * @param context the node to apply the XPath to
 * @param xpath the xpath to apply
 * @return the strings extracted
 * @throws XPathExpressionException on error
 */
public String[] selectMultipleTextItems(Node context, String xpath) throws XPathExpressionException {
    NodeList list = selectNodeList(context, xpath);
    String[] retArray = new String[list.getLength()];

    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node != null) {
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                retArray[i] = node.getNodeValue();
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                retArray[i] = node.getNodeValue();
            } else {
                node.normalize();
                Node text = node.getFirstChild();
                if (text != null) {
                    retArray[i] = text.getNodeValue();
                }
            }
        }
    }
    return retArray;
}

From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java

/**
 * Load the current hibernate.cfg.xml./*from  ww  w  .jav  a 2 s. c  o  m*/
 */
public void load() {
    File configFile = new File(contextPath + configFileSufix);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = null;

    log.debug("Loading configuration from file " + configFile.getAbsolutePath());
    try {
        factory.setValidating(true);
        factory.setNamespaceAware(false);
        // BUG 1: It try to validate.
        // BUG 2: 'null', following the specification, is a valid value.
        // Unfortunately,
        // the current implementation fails on it.
        // factory.setSchema( null );
        parser = factory.newDocumentBuilder();
        //         parser.setEntityResolver(new DTDEntityResolver());
        config = parser.parse(configFile);
    } catch (Exception e) {
        log.debug("Error loading the configuration: ", e);
    }
    NodeList propertiesNodes = config.getElementsByTagName("property");
    for (int i = 0; i < propertiesNodes.getLength(); i++) {
        Node propertyNode = propertiesNodes.item(i);

        // Get the property name
        NamedNodeMap attributesNodes = propertyNode.getAttributes();
        Node attributeNode = attributesNodes.getNamedItem("name");
        String property = attributeNode.getNodeValue();

        // Get the property value
        NodeList childrenNodes = propertyNode.getChildNodes();
        String value = null;
        for (int j = 0; j < childrenNodes.getLength(); j++) {
            Node childNode = childrenNodes.item(j);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                value = childNode.getNodeValue();
                break;
            }
        }

        if (property.equals("connection.driver_class") || property.equals("connection.url")
                || property.equals("connection.username") || property.equals("connection.password")
                || property.equals("dialect") || property.equals("hibernate.connection.datasource")
                || property.equals("hibernate.connection.username")
                || property.equals("hibernate.connection.password")) {
            preferences.put(property, value);
        }
    }
}

From source file:net.mumie.coursecreator.xml.GraphXMLizer.java

public static void recodeUmlauts(Node node) {
    NodeList nl = node.getChildNodes();

    if (node instanceof Text) {
        throw new IllegalArgumentException("Whoops! using the non-Text variant for a Text node!");
    } // end of if ()

    // If 'nl' is empty, the body of the following for loop (i.e. the
    // recursion) will simply be skipped. in that case we return with
    // 'node' unchanged. 
    for (int i = 0; i < nl.getLength(); i++) {
        Node curr = nl.item(i);//from   w ww  .  j a v  a2s .com
        if (curr.getNodeType() == Node.TEXT_NODE) {
            recodeUmlauts((Text) curr);
        } // end of if (curr.getNodeType() == Node.TEXT_NODE)
        else {
            recodeUmlauts(curr);
        } // end of if (curr.getNodeType() == Node.TEXT_NODE) else

    } // end of for (int i = 0; i < nl.getLength() ; i++)
}

From source file:org.artifactory.repo.webdav.methods.PropfindMethod.java

@Override
public void handle(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException {
    // Retrieve the resources
    log.debug("Handling {}", getName());
    int depth = findDepth(request);
    List<String> properties = null;
    PropfindType propertyFindType = PropfindType.FIND_ALL_PROP;
    Node propNode = null;//from  w ww .j ava  2  s. c o m
    //get propertyNode and type
    if (request.getContentLength() > 0) {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        try {
            Document document = documentBuilder.parse(new InputSource(request.getInputStream()));
            logWebdavRequest(document);
            // Get the root element of the document
            Element rootElement = document.getDocumentElement();
            NodeList childList = rootElement.getChildNodes();

            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    propertyFindType = PropfindType.fromString(currentNode.getNodeName());
                    if (propertyFindType == PropfindType.FIND_BY_PROPERTY) {
                        propNode = currentNode;
                    }
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Webdav propfind failed.", e);
        }
    }

    if (propertyFindType == PropfindType.FIND_BY_PROPERTY) {
        properties = getPropertiesFromXml(propNode);
    }

    response.setStatus(HttpStatus.SC_MULTI_STATUS);
    response.setContentType("text/xml; charset=UTF-8");

    // Create multistatus object
    Writer writer = response.getWriter();
    if (log.isDebugEnabled()) {
        writer = new StringWriter(); // write to memory so we'll be able to log the result as string
    }
    XmlWriter generatedXml = new XmlWriter(writer);
    generatedXml.writeXMLHeader();
    generatedXml.writeElement(DEFAULT_NS_ABBRV, "multistatus", XmlWriter.OPENING, DEFAULT_NS_ABBRV,
            DEFAULT_NAMESPACE, "ns0", DEFAULT_NAMESPACE);

    RepoPath repoPath = request.getRepoPath();
    BrowsableItem rootItem = null;
    if (repoService.exists(repoPath)) {
        rootItem = repoBrowsing.getLocalRepoBrowsableItem(repoPath);
    }
    if (rootItem != null) {
        recursiveParseProperties(request, generatedXml, rootItem, propertyFindType, properties, depth);
    } else {
        log.warn("Item '" + request.getRepoPath() + "' not found.");
    }
    generatedXml.writeElement(DEFAULT_NS_ABBRV, "multistatus", XmlWriter.CLOSING);
    generatedXml.sendData();
    if (log.isDebugEnabled()) {
        log.debug("Webdav response:\n" + writer.toString());
        //response.setContentLength(writer.toString().getBytes().length);
        response.getWriter().append(writer.toString());
    }
    response.flush();
}