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     */
017    package org.apache.activemq.console.command;
018    
019    import java.util.ArrayList;
020    import java.util.Enumeration;
021    import java.util.HashSet;
022    import java.util.List;
023    import java.util.Properties;
024    import java.util.Set;
025    import java.util.StringTokenizer;
026    
027    import org.apache.activemq.console.util.JmxMBeansUtil;
028    
029    public class QueryCommand extends AbstractJmxCommand {
030        // Predefined type=identifier query
031        private static final Properties PREDEFINED_OBJNAME_QUERY = new Properties();
032    
033        static {
034            PREDEFINED_OBJNAME_QUERY.setProperty("Broker", "Type=Broker,BrokerName=%1,*");
035            PREDEFINED_OBJNAME_QUERY.setProperty("Connection", "Type=Connection,Connection=%1,*");
036            PREDEFINED_OBJNAME_QUERY.setProperty("Connector", "Type=Connector,ConnectorName=%1,*");
037            PREDEFINED_OBJNAME_QUERY.setProperty("NetworkConnector", "Type=NetworkConnector,BrokerName=%1,*");
038            PREDEFINED_OBJNAME_QUERY.setProperty("Queue", "Type=Queue,Destination=%1,*");
039            PREDEFINED_OBJNAME_QUERY.setProperty("Topic", "Type=Topic,Destination=%1,*");
040        };
041    
042        protected String[] helpFile = new String[] {
043            "Task Usage: Main query [query-options]",
044            "Description: Display selected broker component's attributes and statistics.",
045            "",
046            "Query Options:",
047            "    -Q<type>=<name>               Add to the search list the specific object type matched",
048            "                                  by the defined object identifier.",
049            "    -xQ<type>=<name>              Remove from the search list the specific object type",
050            "                                  matched by the object identifier.",
051            "    --objname <query>             Add to the search list objects matched by the query similar",
052            "                                  to the JMX object name format.",
053            "    --xobjname <query>            Remove from the search list objects matched by the query",
054            "                                  similar to the JMX object name format.",
055            "    --view <attr1>,<attr2>,...    Select the specific attribute of the object to view.",
056            "                                  By default all attributes will be displayed.",
057            "    --jmxurl <url>                Set the JMX URL to connect to.",
058            "    --version                     Display the version information.",
059            "    -h,-?,--help                  Display the query broker help information.",
060            "", "Examples:",
061            "    query",
062            "        - Print all the attributes of all registered objects queues, topics, connections, etc).",
063            "",
064            "    query -QQueue=TEST.FOO",
065            "        - Print all the attributes of the queue with destination name TEST.FOO.",
066            "",
067            "    query -QTopic=*",
068            "        - Print all the attributes of all registered topics.",
069            "",
070            "    query --view EnqueueCount,DequeueCount", 
071            "        - Print the attributes EnqueueCount and DequeueCount of all registered objects.",
072            "",
073            "    query -QTopic=* --view EnqueueCount,DequeueCount",
074            "        - Print the attributes EnqueueCount and DequeueCount of all registered topics.",
075            "",
076            "    query -QTopic=* -QQueue=* --view EnqueueCount,DequeueCount",
077            "        - Print the attributes EnqueueCount and DequeueCount of all registered topics and",
078            "          queues.",
079            "",
080            "    query -QTopic=* -xQTopic=ActiveMQ.Advisory.*", 
081            "        - Print all attributes of all topics except those that has a name that begins",
082            "          with \"ActiveMQ.Advisory\".",
083            "",
084            "    query --objname Type=*Connect*,BrokerName=local* -xQNetworkConnector=*",
085            "        - Print all attributes of all connectors, connections excluding network connectors",
086            "          that belongs to the broker that begins with local.", 
087            "", 
088            "    query -QQueue=* -xQQueue=????", 
089            "        - Print all attributes of all queues except those that are 4 letters long.",
090            "",
091        };
092    
093        private final List<String> queryAddObjects = new ArrayList<String>(10);
094        private final List<String> querySubObjects = new ArrayList<String>(10);
095        private final Set queryViews = new HashSet(10);
096    
097        /**
098         * Queries the mbeans registered in the specified JMX context
099         * 
100         * @param tokens - command arguments
101         * @throws Exception
102         */
103        protected void runTask(List<String> tokens) throws Exception {
104            try {
105                // Query for the mbeans to add
106                List addMBeans = JmxMBeansUtil.queryMBeans(useJmxServiceUrl(), queryAddObjects, queryViews);
107    
108                // Query for the mbeans to sub
109                if (querySubObjects.size() > 0) {
110                    List subMBeans = JmxMBeansUtil.queryMBeans(useJmxServiceUrl(), querySubObjects, queryViews);
111                    addMBeans.removeAll(subMBeans);
112                }
113    
114                context.printMBean(JmxMBeansUtil.filterMBeansView(addMBeans, queryViews));
115    
116            } catch (Exception e) {
117                context.printException(new RuntimeException("Failed to execute query task. Reason: " + e));
118                throw new Exception(e);
119            }
120        }
121    
122        /**
123         * Handle the -Q, -xQ, --objname, --xobjname, --view options.
124         * 
125         * @param token - option token to handle
126         * @param tokens - succeeding command arguments
127         * @throws Exception
128         */
129        protected void handleOption(String token, List<String> tokens) throws Exception {
130            // If token is a additive predefined query define option
131            if (token.startsWith("-Q")) {
132                String key = token.substring(2);
133                String value = "";
134                int pos = key.indexOf("=");
135                if (pos >= 0) {
136                    value = key.substring(pos + 1);
137                    key = key.substring(0, pos);
138                }
139    
140                // If additive query
141                String predefQuery = PREDEFINED_OBJNAME_QUERY.getProperty(key);
142                if (predefQuery == null) {
143                    context.printException(new IllegalArgumentException("Unknown query object type: " + key));
144                    return;
145                }
146                String queryStr = JmxMBeansUtil.createQueryString(predefQuery, value);
147                StringTokenizer queryTokens = new StringTokenizer(queryStr, COMMAND_OPTION_DELIMETER);
148                while (queryTokens.hasMoreTokens()) {
149                    queryAddObjects.add(queryTokens.nextToken());
150                }
151            } else if (token.startsWith("-xQ")) {
152                // If token is a substractive predefined query define option
153                String key = token.substring(3);
154                String value = "";
155                int pos = key.indexOf("=");
156                if (pos >= 0) {
157                    value = key.substring(pos + 1);
158                    key = key.substring(0, pos);
159                }
160    
161                // If subtractive query
162                String predefQuery = PREDEFINED_OBJNAME_QUERY.getProperty(key);
163                if (predefQuery == null) {
164                    context.printException(new IllegalArgumentException("Unknown query object type: " + key));
165                    return;
166                }
167                String queryStr = JmxMBeansUtil.createQueryString(predefQuery, value);
168                StringTokenizer queryTokens = new StringTokenizer(queryStr, COMMAND_OPTION_DELIMETER);
169                while (queryTokens.hasMoreTokens()) {
170                    querySubObjects.add(queryTokens.nextToken());
171                }
172            } else if (token.startsWith("--objname")) {
173                // If token is an additive object name query option
174    
175                // If no object name query is specified, or next token is a new
176                // option
177                if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
178                    context.printException(new IllegalArgumentException("Object name query not specified"));
179                    return;
180                }
181    
182                StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
183                while (queryTokens.hasMoreTokens()) {
184                    queryAddObjects.add(queryTokens.nextToken());
185                }
186            } else if (token.startsWith("--xobjname")) {
187                // If token is a substractive object name query option
188    
189                // If no object name query is specified, or next token is a new
190                // option
191                if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
192                    context.printException(new IllegalArgumentException("Object name query not specified"));
193                    return;
194                }
195    
196                StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
197                while (queryTokens.hasMoreTokens()) {
198                    querySubObjects.add(queryTokens.nextToken());
199                }
200            } else if (token.startsWith("--view")) {
201                // If token is a view option
202    
203                // If no view specified, or next token is a new option
204                if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
205                    context.printException(new IllegalArgumentException("Attributes to view not specified"));
206                    return;
207                }
208    
209                // Add the attributes to view
210                Enumeration viewTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
211                while (viewTokens.hasMoreElements()) {
212                    queryViews.add(viewTokens.nextElement());
213                }
214            } else {
215                // Let super class handle unknown option
216                super.handleOption(token, tokens);
217            }
218        }
219    
220        /**
221         * Print the help messages for the browse command
222         */
223        protected void printHelp() {
224            context.printHelp(helpFile);
225        }
226    
227    }