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        final SAXParser parser = factory.newSAXParser();
069        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
070        docBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
071        final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
072        final Document doc = docBuilder.newDocument();
073
074        final Stack<Element> elementStack = new Stack<>();
075        final StringBuilder textBuffer = new StringBuilder();
076        final DefaultHandler handler = new DefaultHandler() {
077
078            @Override
079            public void setDocumentLocator(final Locator locator) {
080                // noop
081            }
082
083            @Override
084            public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
085                addTextIfNeeded();
086
087                final Element el = doc.createElement(qName);
088                // add other elements
089                for (int i = 0; i < attributes.getLength(); i++) {
090                    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
091                }
092
093                String id = el.getAttribute("id");
094                if (id != null) {
095                    try {
096                        if ("route".equals(qName)) {
097                            ManagedRouteMBean route = camelContext.getExtension(ManagedCamelContext.class).getManagedRoute(id);
098                            if (route != null) {
099                                long total = route.getExchangesTotal();
100                                el.setAttribute("exchangesTotal", "" + total);
101                                long totalTime = route.getTotalProcessingTime();
102                                el.setAttribute("totalProcessingTime", "" + totalTime);
103                            }
104                        } else if ("from".equals(qName)) {
105                            // grab statistics from the parent route as from would be the same
106                            Element parent = elementStack.peek();
107                            if (parent != null) {
108                                String routeId = parent.getAttribute("id");
109                                ManagedRouteMBean route = camelContext.getExtension(ManagedCamelContext.class).getManagedRoute(routeId);
110                                if (route != null) {
111                                    long total = route.getExchangesTotal();
112                                    el.setAttribute("exchangesTotal", "" + total);
113                                    long totalTime = route.getTotalProcessingTime();
114                                    el.setAttribute("totalProcessingTime", "" + totalTime);
115                                    // from is index-0
116                                    el.setAttribute("index", "0");
117                                }
118                            }
119                        } else {
120                            ManagedProcessorMBean processor = camelContext.getExtension(ManagedCamelContext.class).getManagedProcessor(id);
121                            if (processor != null) {
122                                long total = processor.getExchangesTotal();
123                                el.setAttribute("exchangesTotal", "" + total);
124                                long totalTime = processor.getTotalProcessingTime();
125                                el.setAttribute("totalProcessingTime", "" + totalTime);
126                                int index = processor.getIndex();
127                                el.setAttribute("index", "" + index);
128                            }
129                        }
130                    } catch (Exception e) {
131                        // ignore
132                    }
133                }
134
135                // we do not want customId in output of the EIPs
136                if (!"route".equals(qName)) {
137                    el.removeAttribute("customId");
138                }
139
140                elementStack.push(el);
141            }
142
143            @Override
144            public void endElement(final String uri, final String localName, final String qName) {
145                addTextIfNeeded();
146                final Element closedEl = elementStack.pop();
147                if (elementStack.isEmpty()) {
148                    // is this the root element?
149                    doc.appendChild(closedEl);
150                } else {
151                    final Element parentEl = elementStack.peek();
152                    parentEl.appendChild(closedEl);
153                }
154            }
155
156            @Override
157            public void characters(final char[] ch, final int start, final int length) throws SAXException {
158                textBuffer.append(ch, start, length);
159            }
160
161            /**
162             * outputs text accumulated under the current node
163             */
164            private void addTextIfNeeded() {
165                if (textBuffer.length() > 0) {
166                    final Element el = elementStack.peek();
167                    final Node textNode = doc.createTextNode(textBuffer.toString());
168                    el.appendChild(textNode);
169                    textBuffer.delete(0, textBuffer.length());
170                }
171            }
172        };
173        parser.parse(is, handler);
174
175        return doc;
176    }
177}