001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.management.mbean;
018
019import java.io.InputStream;
020import java.util.Stack;
021
022import javax.xml.XMLConstants;
023import javax.xml.parsers.DocumentBuilder;
024import javax.xml.parsers.DocumentBuilderFactory;
025import javax.xml.parsers.SAXParser;
026import javax.xml.parsers.SAXParserFactory;
027
028import org.w3c.dom.Document;
029import org.w3c.dom.Element;
030import org.w3c.dom.Node;
031
032import org.xml.sax.Attributes;
033import org.xml.sax.Locator;
034import org.xml.sax.SAXException;
035import org.xml.sax.helpers.DefaultHandler;
036
037import org.apache.camel.CamelContext;
038import org.apache.camel.api.management.ManagedCamelContext;
039import org.apache.camel.api.management.mbean.ManagedProcessorMBean;
040import org.apache.camel.api.management.mbean.ManagedRouteMBean;
041
042/**
043 * An XML parser that uses SAX to enrich route stats in the route dump.
044 * <p/>
045 * The coverage details:
046 * <ul>
047 * <li>exchangesTotal - Total number of exchanges</li>
048 * <li>totalProcessingTime - Total processing time in millis</li>
049 * </ul>
050 * Is included as attributes on the route nodes.
051 */
052public final class RouteCoverageXmlParser {
053
054    private RouteCoverageXmlParser() {
055    }
056
057    /**
058     * Parses the XML.
059     *
060     * @param  camelContext the CamelContext
061     * @param  is           the XML content as an input stream
062     * @return              the DOM model of the routes with coverage information stored as attributes
063     * @throws Exception    is thrown if error parsing
064     */
065    public static Document parseXml(final CamelContext camelContext, final InputStream is) throws Exception {
066        final SAXParserFactory factory = SAXParserFactory.newInstance();
067        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
068        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
069        factory.setFeature("http://xml.org/sax/features/namespaces", false);
070        factory.setFeature("http://xml.org/sax/features/validation", false);
071        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
072        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
073        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
074        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
075        final SAXParser parser = factory.newSAXParser();
076        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
077        dbf.setValidating(false);
078        dbf.setNamespaceAware(true);
079        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
080        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
081        dbf.setFeature("http://xml.org/sax/features/namespaces", false);
082        dbf.setFeature("http://xml.org/sax/features/validation", false);
083        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
084        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
085        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
086        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
087        dbf.setXIncludeAware(false);
088        dbf.setExpandEntityReferences(false);
089        final DocumentBuilder docBuilder = dbf.newDocumentBuilder();
090        final Document doc = docBuilder.newDocument();
091
092        final Stack<Element> elementStack = new Stack<>();
093        final StringBuilder textBuffer = new StringBuilder();
094        final DefaultHandler handler = new DefaultHandler() {
095
096            @Override
097            public void setDocumentLocator(final Locator locator) {
098                // noop
099            }
100
101            @Override
102            public void startElement(final String uri, final String localName, final String qName, final Attributes attributes)
103                    throws SAXException {
104                addTextIfNeeded();
105
106                final Element el = doc.createElement(qName);
107                // add other elements
108                for (int i = 0; i < attributes.getLength(); i++) {
109                    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
110                }
111
112                String id = el.getAttribute("id");
113                if (id != null) {
114                    try {
115                        if ("route".equals(qName)) {
116                            ManagedRouteMBean route = camelContext.getExtension(ManagedCamelContext.class).getManagedRoute(id);
117                            if (route != null) {
118                                long total = route.getExchangesTotal();
119                                el.setAttribute("exchangesTotal", "" + total);
120                                long totalTime = route.getTotalProcessingTime();
121                                el.setAttribute("totalProcessingTime", "" + totalTime);
122                            }
123                        } else if ("from".equals(qName)) {
124                            // grab statistics from the parent route as from would be the same
125                            Element parent = elementStack.peek();
126                            if (parent != null) {
127                                String routeId = parent.getAttribute("id");
128                                ManagedRouteMBean route
129                                        = camelContext.getExtension(ManagedCamelContext.class).getManagedRoute(routeId);
130                                if (route != null) {
131                                    long total = route.getExchangesTotal();
132                                    el.setAttribute("exchangesTotal", "" + total);
133                                    long totalTime = route.getTotalProcessingTime();
134                                    el.setAttribute("totalProcessingTime", "" + totalTime);
135                                    // from is index-0
136                                    el.setAttribute("index", "0");
137                                }
138                            }
139                        } else {
140                            ManagedProcessorMBean processor
141                                    = camelContext.getExtension(ManagedCamelContext.class).getManagedProcessor(id);
142                            if (processor != null) {
143                                long total = processor.getExchangesTotal();
144                                el.setAttribute("exchangesTotal", "" + total);
145                                long totalTime = processor.getTotalProcessingTime();
146                                el.setAttribute("totalProcessingTime", "" + totalTime);
147                                int index = processor.getIndex();
148                                el.setAttribute("index", "" + index);
149                            }
150                        }
151                    } catch (Exception e) {
152                        // ignore
153                    }
154                }
155
156                // we do not want customId in output of the EIPs
157                if (!"route".equals(qName)) {
158                    el.removeAttribute("customId");
159                }
160
161                elementStack.push(el);
162            }
163
164            @Override
165            public void endElement(final String uri, final String localName, final String qName) {
166                addTextIfNeeded();
167                final Element closedEl = elementStack.pop();
168                if (elementStack.isEmpty()) {
169                    // is this the root element?
170                    doc.appendChild(closedEl);
171                } else {
172                    final Element parentEl = elementStack.peek();
173                    parentEl.appendChild(closedEl);
174                }
175            }
176
177            @Override
178            public void characters(final char[] ch, final int start, final int length) throws SAXException {
179                textBuffer.append(ch, start, length);
180            }
181
182            /**
183             * outputs text accumulated under the current node
184             */
185            private void addTextIfNeeded() {
186                if (textBuffer.length() > 0) {
187                    final Element el = elementStack.peek();
188                    final Node textNode = doc.createTextNode(textBuffer.toString());
189                    el.appendChild(textNode);
190                    textBuffer.delete(0, textBuffer.length());
191                }
192            }
193        };
194        parser.parse(is, handler);
195
196        return doc;
197    }
198}