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.activemq.console.command;
018
019import java.util.ArrayList;
020import java.util.HashSet;
021import java.util.Iterator;
022import java.util.List;
023import java.util.Set;
024import java.util.StringTokenizer;
025
026import javax.management.ObjectInstance;
027
028import org.apache.activemq.console.util.AmqMessagesUtil;
029import org.apache.activemq.console.util.JmxMBeansUtil;
030
031public class BrowseCommand extends AbstractJmxCommand {
032
033    public static final String QUEUE_PREFIX = "queue:";
034    public static final String TOPIC_PREFIX = "topic:";
035
036    public static final String VIEW_GROUP_HEADER = "header:";
037    public static final String VIEW_GROUP_CUSTOM = "custom:";
038    public static final String VIEW_GROUP_BODY = "body:";
039
040    protected String[] helpFile = new String[] {
041        "Task Usage: Main browse [browse-options] <destinations>", "Description: Display selected destination's messages.", 
042        "", 
043        "Browse Options:",
044        "    --msgsel <msgsel1,msglsel2>   Add to the search list messages matched by the query similar to", 
045        "                                  the messages selector format.",
046        "    -V<header|custom|body>        Predefined view that allows you to view the message header, custom", 
047        "                                  message header, or the message body.",
048        "    --view <attr1>,<attr2>,...    Select the specific attribute of the message to view.", 
049        "    --jmxurl <url>                Set the JMX URL to connect to.",
050        "    --pid <pid>                   Set the pid to connect to (only on Sun JVM).",            
051        "    --jmxuser <user>              Set the JMX user used for authenticating.",
052        "    --jmxpassword <password>      Set the JMX password used for authenticating.",
053        "    --jmxlocal                    Use the local JMX server instead of a remote one.",
054        "    --version                     Display the version information.",
055        "    -h,-?,--help                  Display the browse broker help information.", 
056        "", 
057        "Examples:",
058        "    Main browse FOO.BAR", 
059        "        - Print the message header, custom message header, and message body of all messages in the", 
060        "          queue FOO.BAR",
061        "",
062        "    Main browse -Vheader,body queue:FOO.BAR",
063        "        - Print only the message header and message body of all messages in the queue FOO.BAR",
064        "",
065        "    Main browse -Vheader --view custom:MyField queue:FOO.BAR",
066        "        - Print the message header and the custom field 'MyField' of all messages in the queue FOO.BAR",
067        "",
068        "    Main browse --msgsel \"JMSMessageID='*:10',JMSPriority>5\" FOO.BAR", 
069        "        - Print all the message fields that has a JMSMessageID in the header field that matches the",
070        "          wildcard *:10, and has a JMSPriority field > 5 in the queue FOO.BAR.", 
071        "          SLQ92 syntax is also supported.",
072        "        * To use wildcard queries, the field must be a string and the query enclosed in ''", 
073        "          Use double quotes \"\" around the entire message selector string.",
074        ""
075    };
076
077    private final List<String> queryAddObjects = new ArrayList<String>(10);
078    private final List<String> querySubObjects = new ArrayList<String>(10);
079    private final Set<String> groupViews = new HashSet<String>(10);
080    private final Set queryViews = new HashSet(10);
081
082    /**
083     * Execute the browse command, which allows you to browse the messages in a
084     * given JMS destination
085     * 
086     * @param tokens - command arguments
087     * @throws Exception
088     */
089    protected void runTask(List<String> tokens) throws Exception {
090        try {
091            // If there is no queue name specified, let's select all
092            if (tokens.isEmpty()) {
093                tokens.add("*");
094            }
095
096            // Iterate through the queue names
097            for (Iterator<String> i = tokens.iterator(); i.hasNext();) {
098                List queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "Type=Queue,Destination=" + i.next() + ",*");
099
100                // Iterate through the queue result
101                for (Iterator j = queueList.iterator(); j.hasNext();) {
102                    List messages = JmxMBeansUtil.createMessageQueryFilter(createJmxConnection(), ((ObjectInstance)j.next()).getObjectName()).query(queryAddObjects);
103                    context.printMessage(JmxMBeansUtil.filterMessagesView(messages, groupViews, queryViews));
104                }
105            }
106        } catch (Exception e) {
107            context.printException(new RuntimeException("Failed to execute browse task. Reason: " + e));
108            throw new Exception(e);
109        }
110    }
111
112    /**
113     * Handle the --msgsel, --xmsgsel, --view, -V options.
114     * 
115     * @param token - option token to handle
116     * @param tokens - succeeding command arguments
117     * @throws Exception
118     */
119    protected void handleOption(String token, List<String> tokens) throws Exception {
120
121        // If token is an additive message selector option
122        if (token.startsWith("--msgsel")) {
123
124            // If no message selector is specified, or next token is a new
125            // option
126            if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
127                context.printException(new IllegalArgumentException("Message selector not specified"));
128                return;
129            }
130
131            StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
132            while (queryTokens.hasMoreTokens()) {
133                queryAddObjects.add(queryTokens.nextToken());
134            }
135        } else if (token.startsWith("--xmsgsel")) {
136            // If token is a substractive message selector option
137
138            // If no message selector is specified, or next token is a new
139            // option
140            if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
141                context.printException(new IllegalArgumentException("Message selector not specified"));
142                return;
143            }
144
145            StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
146            while (queryTokens.hasMoreTokens()) {
147                querySubObjects.add(queryTokens.nextToken());
148            }
149
150        } else if (token.startsWith("--view")) {
151            // If token is a view option
152
153            // If no view specified, or next token is a new option
154            if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
155                context.printException(new IllegalArgumentException("Attributes to view not specified"));
156                return;
157            }
158
159            // Add the attributes to view
160            StringTokenizer viewTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
161            while (viewTokens.hasMoreTokens()) {
162                String viewToken = viewTokens.nextToken();
163
164                // If view is explicitly specified to belong to the JMS header
165                if (viewToken.equals(VIEW_GROUP_HEADER)) {
166                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_HEADER_PREFIX + viewToken.substring(VIEW_GROUP_HEADER.length()));
167
168                    // If view is explicitly specified to belong to the JMS
169                    // custom header
170                } else if (viewToken.equals(VIEW_GROUP_CUSTOM)) {
171                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_CUSTOM_PREFIX + viewToken.substring(VIEW_GROUP_CUSTOM.length()));
172
173                    // If view is explicitly specified to belong to the JMS body
174                } else if (viewToken.equals(VIEW_GROUP_BODY)) {
175                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_BODY_PREFIX + viewToken.substring(VIEW_GROUP_BODY.length()));
176
177                    // If no view explicitly specified, let's check the view for
178                    // each group
179                } else {
180                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_HEADER_PREFIX + viewToken);
181                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_CUSTOM_PREFIX + viewToken);
182                    queryViews.add(AmqMessagesUtil.JMS_MESSAGE_BODY_PREFIX + viewToken);
183                }
184            }
185        } else if (token.startsWith("-V")) {
186            // If token is a predefined group view option
187            String viewGroup = token.substring(2);
188            // If option is a header group view
189            if (viewGroup.equals("header")) {
190                groupViews.add(AmqMessagesUtil.JMS_MESSAGE_HEADER_PREFIX);
191
192                // If option is a custom header group view
193            } else if (viewGroup.equals("custom")) {
194                groupViews.add(AmqMessagesUtil.JMS_MESSAGE_CUSTOM_PREFIX);
195
196                // If option is a body group view
197            } else if (viewGroup.equals("body")) {
198                groupViews.add(AmqMessagesUtil.JMS_MESSAGE_BODY_PREFIX);
199
200                // Unknown group view
201            } else {
202                context.printInfo("Unknown group view: " + viewGroup + ". Ignoring group view option.");
203            }
204        } else {
205            // Let super class handle unknown option
206            super.handleOption(token, tokens);
207        }
208    }
209
210    /**
211     * Print the help messages for the browse command
212     */
213    protected void printHelp() {
214        context.printHelp(helpFile);
215    }
216
217}