Example usage for org.w3c.dom Node PROCESSING_INSTRUCTION_NODE

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

Introduction

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

Prototype

short PROCESSING_INSTRUCTION_NODE

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

Click Source Link

Document

The node is a ProcessingInstruction.

Usage

From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java

private void createSupport(InputStream input_stream)

        throws SimpleXMLParserDocumentException {
    try {//w ww .j  a  va2 s . c  o  m
        DocumentBuilderFactory dbf = getDBF();

        // Step 2: create a DocumentBuilder that satisfies the constraints
        // specified by the DocumentBuilderFactory

        DocumentBuilder db = dbf.newDocumentBuilder();

        // Set an ErrorHandler before parsing

        OutputStreamWriter errorWriter = new OutputStreamWriter(System.err);

        MyErrorHandler error_handler = new MyErrorHandler(new PrintWriter(errorWriter, true));

        db.setErrorHandler(error_handler);

        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                // System.out.println( publicId + ", " + systemId );

                // handle bad DTD external refs

                try {
                    URL url = new URL(systemId);

                    if (source_url != null) {

                        String net = AENetworkClassifier.categoriseAddress(source_url.getHost());

                        if (net != AENetworkClassifier.AT_PUBLIC) {

                            if (AENetworkClassifier.categoriseAddress(url.getHost()) != net) {

                                return new InputSource(new ByteArrayInputStream(
                                        "<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
                            }
                        }
                    }

                    String host = url.getHost();

                    InetAddress.getByName(host);

                    // try connecting too as connection-refused will also bork XML parsing

                    InputStream is = null;

                    try {
                        URLConnection con = url.openConnection();

                        con.setConnectTimeout(15 * 1000);
                        con.setReadTimeout(15 * 1000);

                        is = con.getInputStream();

                        byte[] buffer = new byte[32];

                        int pos = 0;

                        while (pos < buffer.length) {

                            int len = is.read(buffer, pos, buffer.length - pos);

                            if (len <= 0) {

                                break;
                            }

                            pos += len;
                        }

                        String str = new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                        if (!str.contains("<?xml")) {

                            // not straightforward to check for naked DTDs, could be lots of <!-- commentry preamble which of course can occur
                            // in HTML too

                            buffer = new byte[32000];

                            pos = 0;

                            while (pos < buffer.length) {

                                int len = is.read(buffer, pos, buffer.length - pos);

                                if (len <= 0) {

                                    break;
                                }

                                pos += len;
                            }

                            str += new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                            if (str.contains("<html") && str.contains("<head")) {

                                throw (new Exception("Bad DTD"));
                            }
                        }
                    } catch (Throwable e) {

                        return new InputSource(
                                new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                    } finally {

                        if (is != null) {

                            try {
                                is.close();

                            } catch (Throwable e) {

                            }
                        }
                    }
                    return (null);

                } catch (UnknownHostException e) {

                    return new InputSource(
                            new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                } catch (Throwable e) {

                    return (null);
                }
            }
        });

        // Step 3: parse the input file

        document = db.parse(input_stream);

        SimpleXMLParserDocumentNodeImpl[] root_nodes = parseNode(document, false);

        int root_node_count = 0;

        // remove any processing instructions such as <?xml-stylesheet

        for (int i = 0; i < root_nodes.length; i++) {

            SimpleXMLParserDocumentNodeImpl node = root_nodes[i];

            if (node.getNode().getNodeType() != Node.PROCESSING_INSTRUCTION_NODE) {

                root_node = node;

                root_node_count++;
            }
        }

        if (root_node_count != 1) {

            throw (new SimpleXMLParserDocumentException(
                    "invalid document - " + root_nodes.length + " root elements"));
        }

    } catch (Throwable e) {

        throw (new SimpleXMLParserDocumentException(e));
    }
}

From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java

protected SimpleXMLParserDocumentNodeImpl[] parseNode(Node node, boolean skip_this_node) {
    int type = node.getNodeType();

    if ((type == Node.ELEMENT_NODE || type == Node.PROCESSING_INSTRUCTION_NODE) && !skip_this_node) {

        return (new SimpleXMLParserDocumentNodeImpl[] { new SimpleXMLParserDocumentNodeImpl(this, node) });
    }/*from w  w w  .j a  v  a  2 s. c om*/

    Vector v = new Vector();

    for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {

        SimpleXMLParserDocumentNodeImpl[] kids = parseNode(child, false);

        for (int i = 0; i < kids.length; i++) {

            v.addElement(kids[i]);
        }
    }

    SimpleXMLParserDocumentNodeImpl[] res = new SimpleXMLParserDocumentNodeImpl[v.size()];

    v.copyInto(res);

    return (res);
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Appends a node and it's children to the given StringBuffer. Indentation is added on recursion.
 *///from  ww w. j  a  va 2s  . c  o  m
public static void appendNode(final Node node, final String indent, final StringBuffer sb) {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: {
        sb.append("<?xml version=\"1.0\"?>\n");

        final Document doc = (Document) node;
        appendNode(doc.getDocumentElement(), "", sb);

        break;
    }

    case Node.ELEMENT_NODE: {
        final String name = node.getNodeName();
        sb.append(indent + "<" + name);

        final NamedNodeMap attributes = node.getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {
            final Node current = attributes.item(i);
            sb.append(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
        }

        sb.append(">");

        // Kinder durchgehen
        final NodeList children = node.getChildNodes();

        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                appendNode(children.item(i), indent, sb);
            }
        }

        sb.append(indent + "</" + name + ">");

        break;
    }

    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE: {
        final String trimmed = node.getNodeValue().trim();

        if (!trimmed.equals("")) {
            sb.append(indent + trimmed);
        }

        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE:
        break;

    case Node.ENTITY_REFERENCE_NODE:
        break;

    case Node.DOCUMENT_TYPE_NODE:
        break;
    }
}

From source file:org.openmrs.module.formentry.PublishInfoPath.java

private static void prepareTemplate(File tempDir, String fileName, String solutionVersion, String publishUrl,
        String namespace) {//from  w  w  w . ja v  a  2  s.  c o  m
    File file = new File(tempDir, fileName);
    if (file == null) {
        log.warn("Missing file: '" + fileName + "'");
        return;
    }
    if (log.isDebugEnabled())
        log.debug("Preparing template: " + file.getAbsolutePath());
    Document doc = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(file);

        // set namespace
        String tag = "form";
        Element elem = getSingleElement(doc, tag);
        if (elem == null) {
            log.warn("Could not locate " + tag + " element in " + file.getName());
            return;
        }
        elem.setAttribute("xmlns:openmrs", namespace);

        Node root = doc.getDocumentElement().getParentNode();
        NodeList children = root.getChildNodes();
        log.debug("Scanning for processing instructions");
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE
                    && node.getNodeName().equals("mso-infoPathSolution")) {
                ProcessingInstruction pi = (ProcessingInstruction) node;
                String data = pi.getData();
                if (log.isDebugEnabled())
                    log.debug("  found: " + data);
                data = data.replaceAll("(\\bsolutionVersion\\s*=\\s*\")[^\"]+\"",
                        "$1" + solutionVersion + "\"");
                data = data.replaceAll("(\\bhref\\s*=\\s*\")[^\"]+\"", "$1" + publishUrl + "\"");
                if (log.isDebugEnabled())
                    log.debug("  replacing with: " + data);
                pi.setData(data);
            }
        }

    } catch (Exception e) {
        log.error("Trouble with file: " + fileName + " " + solutionVersion + " " + publishUrl, e);
    }
    writeXml(doc, file.getAbsolutePath());
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlUtil.java

/**
 * Get a textual representation of a Node.
 * @param node The Node//from  w  ww . ja v a 2  s  .  c  o  m
 * @return the document in a text string
 */
public static String getDOMString(Node node) {
    //String domString = "";

    StringBuilder domStringbuf = new StringBuilder();

    int type = node.getNodeType();
    switch (type) {
    // print the document element
    case Node.DOCUMENT_NODE: {
        domStringbuf.append("<?xml version=\"1.0\" ?>\n");
        domStringbuf.append(getDOMString(((Document) node).getDocumentElement()));
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        domStringbuf.append("<");
        domStringbuf.append(node.getNodeName());
        NamedNodeMap attrs = node.getAttributes();

        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            //domString += (" " + attr.getNodeName().trim() +
            //              "=\"" + attr.getNodeValue().trim() +
            //              "\"");

            domStringbuf.append((" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\""));
        }
        //domString = domStringbuf.toString();
        domStringbuf.append(">");

        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++)
                domStringbuf.append(getDOMString(children.item(i)));
        }
        domStringbuf.append("</");
        domStringbuf.append(node.getNodeName());
        domStringbuf.append(">\n");

        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        domStringbuf.append("&");
        domStringbuf.append(node.getNodeName().trim());
        domStringbuf.append(";");

        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        domStringbuf.append("");
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String val = node.getNodeValue();
        if (val == null)
            val = "";
        domStringbuf.append(val);//rshastri .trim() removed SAK-1671 
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        domStringbuf.append("");
        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        domStringbuf.append("\n");
    }

    String domString = domStringbuf.toString();
    return domString;
}