Search in sources :

Example 76 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project tomee by apache.

the class PersistenceBootstrap method collectUnits.

private static void collectUnits(final InputStream in, final Map<String, Unit> units, final Properties args) throws ParserConfigurationException, SAXException, IOException {
    final InputSource inputSource = new InputSource(in);
    final SAXParser parser = Saxs.namespaceAwareFactory().newSAXParser();
    parser.parse(inputSource, new DefaultHandler() {

        private final StringBuilder characters = new StringBuilder(100);

        private Unit unit;

        public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) {
            characters.setLength(0);
            if (localName.equals("persistence-unit")) {
                startPersistenceUnit(uri, localName, qName, attributes);
            }
        }

        public void startPersistenceUnit(final String uri, final String localName, final String qName, final Attributes attributes) {
            final String unitName = attributes.getValue("name");
            unit = new Unit(unitName);
        }

        public void characters(final char[] ch, final int start, final int length) {
            final String text = new String(ch, start, length);
            characters.append(text.trim());
        }

        public void endElement(final String uri, final String localName, final String qName) {
            if (localName.equals("persistence-unit")) {
                endPersistenceUnit(uri, localName, qName);
            } else if (localName.equals("provider")) {
                endProvider(uri, localName, qName);
            } else if (localName.equals("class")) {
                endClass(uri, localName, qName);
            }
        }

        public void endPersistenceUnit(final String uri, final String localName, final String qName) {
            if (args.getProperty(unit.name + "@skip", "false").equalsIgnoreCase("true")) {
                debug("skipping unit " + unit.name);
            } else {
                debug("adding unit " + unit.name);
                if (unit.provider == null) {
                    unit.provider = DEFAULT_PROVIDER;
                }
                final Unit u = units.get(unit.provider);
                if (u == null) {
                    units.put(unit.provider, unit);
                } else {
                    u.classes.addAll(unit.classes);
                }
            }
            unit = null;
        }

        public void endProvider(final String uri, final String localName, final String qName) {
            unit.provider = characters.toString();
        }

        public void endClass(final String uri, final String localName, final String qName) {
            unit.classes.add(characters.toString());
        }
    });
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) SAXParser(javax.xml.parsers.SAXParser) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Example 77 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project che by eclipse.

the class History method load.

private void load(InputSource inputSource) throws CoreException {
    Element root;
    try {
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        parser.setErrorHandler(new DefaultHandler());
        root = parser.parse(inputSource).getDocumentElement();
    } catch (SAXException e) {
        throw createException(e, Messages.format(CorextMessages.History_error_read, BasicElementLabels.getResourceName(fFileName)));
    } catch (ParserConfigurationException e) {
        throw createException(e, Messages.format(CorextMessages.History_error_read, BasicElementLabels.getResourceName(fFileName)));
    } catch (IOException e) {
        throw createException(e, Messages.format(CorextMessages.History_error_read, BasicElementLabels.getResourceName(fFileName)));
    }
    if (root == null)
        return;
    if (!root.getNodeName().equalsIgnoreCase(fRootNodeName)) {
        return;
    }
    NodeList list = root.getChildNodes();
    int length = list.getLength();
    for (int i = 0; i < length; ++i) {
        Node node = list.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element type = (Element) node;
            if (type.getNodeName().equalsIgnoreCase(fInfoNodeName)) {
                Object object = createFromElement(type);
                if (object != null) {
                    fHistory.put(getKey(object), object);
                }
            }
        }
    }
    rebuildPositions();
}
Also used : DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException)

Example 78 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project hive by apache.

the class JUnitReportParser method parse.

private void parse() {
    populateTestFileList(directory);
    for (File file : testOutputFiles) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new InputSource(stream), new DefaultHandler() {

                private String name;

                private boolean failedOrErrored;

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if ("testcase".equals(qName)) {
                        name = attributes.getValue("classname");
                        failedOrErrored = false;
                        if (name == null || "junit.framework.TestSuite".equals(name)) {
                            name = attributes.getValue("name");
                        } else {
                            name = name + "." + attributes.getValue("name");
                        }
                    } else if (name != null) {
                        if ("failure".equals(qName) || "error".equals(qName)) {
                            failedOrErrored = true;
                        } else if ("skipped".equals(qName)) {
                            name = null;
                        }
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) {
                    if ("testcase".equals(qName)) {
                        if (name != null) {
                            executedTests.add(name);
                            if (failedOrErrored) {
                                failedTests.add(name);
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            logger.error("Error parsing file " + file, e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    logger.warn("Error closing file " + file, e);
                }
            }
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) SAXParser(javax.xml.parsers.SAXParser) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) SAXParserFactory(javax.xml.parsers.SAXParserFactory) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Example 79 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project camel by apache.

the class XmlLineNumberParser method parseXml.

/**
     * Parses the XML.
     *
     * @param is the XML content as an input stream
     * @param rootNames one or more root names that is used as baseline for beginning the parsing, for example camelContext to start parsing
     *                  when Camel is discovered. Multiple names can be defined separated by comma
     * @param forceNamespace an optional namespace to force assign to each node. This may be needed for JAXB unmarshalling from XML -> POJO.
     * @return the DOM model
     * @throws Exception is thrown if error parsing
     */
public static Document parseXml(final InputStream is, final String rootNames, final String forceNamespace) throws Exception {
    final Document doc;
    SAXParser parser;
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    parser = factory.newSAXParser();
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // turn off validator and loading external dtd
    dbf.setValidating(false);
    dbf.setNamespaceAware(true);
    dbf.setFeature("http://xml.org/sax/features/namespaces", false);
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    final DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    doc = docBuilder.newDocument();
    final Stack<Element> elementStack = new Stack<Element>();
    final StringBuilder textBuffer = new StringBuilder();
    final DefaultHandler handler = new DefaultHandler() {

        private Locator locator;

        private boolean found;

        @Override
        public void setDocumentLocator(final Locator locator) {
            // Save the locator, so that it can be used later for line tracking when traversing nodes.
            this.locator = locator;
            this.found = rootNames == null;
        }

        private boolean isRootName(String qName) {
            for (String root : rootNames.split(",")) {
                if (qName.equals(root)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
            addTextIfNeeded();
            if (rootNames != null && !found) {
                if (isRootName(qName)) {
                    found = true;
                }
            }
            if (found) {
                Element el;
                if (forceNamespace != null) {
                    el = doc.createElementNS(forceNamespace, qName);
                } else {
                    el = doc.createElement(qName);
                }
                for (int i = 0; i < attributes.getLength(); i++) {
                    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
                }
                el.setUserData(LINE_NUMBER, String.valueOf(this.locator.getLineNumber()), null);
                el.setUserData(COLUMN_NUMBER, String.valueOf(this.locator.getColumnNumber()), null);
                elementStack.push(el);
            }
        }

        @Override
        public void endElement(final String uri, final String localName, final String qName) {
            if (!found) {
                return;
            }
            addTextIfNeeded();
            final Element closedEl = elementStack.isEmpty() ? null : elementStack.pop();
            if (closedEl != null) {
                if (elementStack.isEmpty()) {
                    // Is this the root element?
                    doc.appendChild(closedEl);
                } else {
                    final Element parentEl = elementStack.peek();
                    parentEl.appendChild(closedEl);
                }
                closedEl.setUserData(LINE_NUMBER_END, String.valueOf(this.locator.getLineNumber()), null);
                closedEl.setUserData(COLUMN_NUMBER_END, String.valueOf(this.locator.getColumnNumber()), null);
            }
        }

        @Override
        public void characters(final char[] ch, final int start, final int length) throws SAXException {
            textBuffer.append(ch, start, length);
        }

        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
            // do not resolve external dtd
            return new InputSource(new StringReader(""));
        }

        // Outputs text accumulated under the current node
        private void addTextIfNeeded() {
            if (textBuffer.length() > 0) {
                final Element el = elementStack.isEmpty() ? null : elementStack.peek();
                if (el != null) {
                    final Node textNode = doc.createTextNode(textBuffer.toString());
                    el.appendChild(textNode);
                    textBuffer.delete(0, textBuffer.length());
                }
            }
        }
    };
    parser.parse(is, handler);
    return doc;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Attributes(org.xml.sax.Attributes) Document(org.w3c.dom.Document) Stack(java.util.Stack) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Locator(org.xml.sax.Locator) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) SAXParser(javax.xml.parsers.SAXParser) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 80 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project GCViewer by chewiebug.

the class DataReaderIBM_J9_5_0 method read.

public GCModel read() throws IOException {
    if (getLogger().isLoggable(Level.INFO))
        getLogger().info("Reading IBM J9 5.0 format...");
    try (InputStream inStream = this.inputStream) {
        final GCModel model = new GCModel();
        model.setFormat(GCModel.Format.IBM_VERBOSE_GC);
        DefaultHandler handler = new IBMJ9SAXHandler(gcResource, model);
        // Use the default (non-validating) parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        javax.xml.parsers.SAXParser saxParser;
        try {
            saxParser = factory.newSAXParser();
            saxParser.parse(inStream, handler);
        } catch (ParserConfigurationException e) {
            final IOException exception = new IOException(e.toString());
            exception.initCause(e);
            throw exception;
        } catch (SAXException e) {
            // TODO: if(e.getMessage().startsWith("XML document structures must start and end within the same entity")) {
            if (e instanceof SAXParseException && ((SAXParseException) e).getColumnNumber() == 1) {
            // ignore. this just means a xml tag terminated.
            } else {
                final IOException exception = new IOException(e.toString());
                exception.initCause(e);
                throw exception;
            }
        }
        return model;
    } finally {
        if (getLogger().isLoggable(Level.INFO))
            getLogger().info("Done reading.");
    }
}
Also used : InputStream(java.io.InputStream) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) GCModel(com.tagtraum.perf.gcviewer.model.GCModel) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXParserFactory(javax.xml.parsers.SAXParserFactory) SAXException(org.xml.sax.SAXException)

Aggregations

DefaultHandler (org.xml.sax.helpers.DefaultHandler)148 InputStream (java.io.InputStream)65 Metadata (org.apache.tika.metadata.Metadata)59 ParseContext (org.apache.tika.parser.ParseContext)52 Test (org.junit.Test)44 Attributes (org.xml.sax.Attributes)41 SAXParser (javax.xml.parsers.SAXParser)40 SAXException (org.xml.sax.SAXException)39 ByteArrayInputStream (java.io.ByteArrayInputStream)32 SAXParserFactory (javax.xml.parsers.SAXParserFactory)29 IOException (java.io.IOException)26 InputSource (org.xml.sax.InputSource)23 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)22 Parser (org.apache.tika.parser.Parser)22 TikaInputStream (org.apache.tika.io.TikaInputStream)20 ContentHandler (org.xml.sax.ContentHandler)20 File (java.io.File)19 AutoDetectParser (org.apache.tika.parser.AutoDetectParser)17 BodyContentHandler (org.apache.tika.sax.BodyContentHandler)16 FileInputStream (java.io.FileInputStream)15