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