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.Iterator;
021 import java.util.List;
022 import java.util.StringTokenizer;
023
024 import javax.management.MBeanServerConnection;
025 import javax.management.ObjectInstance;
026 import javax.management.ObjectName;
027 import javax.management.openmbean.CompositeData;
028 import javax.management.remote.JMXConnector;
029
030 import org.apache.activemq.console.util.JmxMBeansUtil;
031
032 public class PurgeCommand extends AbstractJmxCommand {
033
034 protected String[] helpFile = new String[] {
035 "Task Usage: Main purge [browse-options] <destinations>",
036 "Description: Delete selected destination's messages that matches the message selector.",
037 "",
038 "Browse Options:",
039 " --msgsel <msgsel1,msglsel2> Add to the search list messages matched by the query similar to",
040 " the messages selector format.",
041 " --jmxurl <url> Set the JMX URL to connect to.",
042 " --version Display the version information.",
043 " -h,-?,--help Display the browse broker help information.",
044 "",
045 "Examples:",
046 " Main purge FOO.BAR",
047 " - Delete all the messages in queue FOO.BAR",
048
049 " Main purge --msgsel JMSMessageID='*:10',JMSPriority>5 FOO.*",
050 " - Delete all the messages in the destinations that matches FOO.* and has a JMSMessageID in",
051 " the header field that matches the wildcard *:10, and has a JMSPriority field > 5 in the",
052 " queue FOO.BAR",
053 " * To use wildcard queries, the field must be a string and the query enclosed in ''",
054 "",
055 };
056
057 private final List<String> queryAddObjects = new ArrayList<String>(10);
058 private final List<String> querySubObjects = new ArrayList<String>(10);
059
060 /**
061 * Execute the purge command, which allows you to purge the messages in a
062 * given JMS destination
063 *
064 * @param tokens - command arguments
065 * @throws Exception
066 */
067 protected void runTask(List<String> tokens) throws Exception {
068 try {
069 // If there is no queue name specified, let's select all
070 if (tokens.isEmpty()) {
071 tokens.add("*");
072 }
073
074 // Iterate through the queue names
075 for (Iterator<String> i = tokens.iterator(); i.hasNext();) {
076 List queueList = JmxMBeansUtil.queryMBeans(useJmxServiceUrl(), "Type=Queue,Destination=" + i.next() + ",*");
077
078 for (Iterator j = queueList.iterator(); j.hasNext();) {
079 ObjectName queueName = ((ObjectInstance)j.next()).getObjectName();
080 if (queryAddObjects.isEmpty()) {
081 purgeQueue(queueName);
082 } else {
083 List messages = JmxMBeansUtil.createMessageQueryFilter(useJmxServiceUrl(), queueName).query(queryAddObjects);
084 purgeMessages(queueName, messages);
085 }
086 }
087 }
088 } catch (Exception e) {
089 context.printException(new RuntimeException("Failed to execute purge task. Reason: " + e));
090 throw new Exception(e);
091 }
092 }
093
094 /**
095 * Purge all the messages in the queue
096 *
097 * @param queue - ObjectName of the queue to purge
098 * @throws Exception
099 */
100 public void purgeQueue(ObjectName queue) throws Exception {
101 JMXConnector conn = createJmxConnector();
102 MBeanServerConnection server = conn.getMBeanServerConnection();
103 context.printInfo("Purging all messages in queue: " + queue.getKeyProperty("Destination"));
104 server.invoke(queue, "purge", new Object[] {}, new String[] {});
105 conn.close();
106 }
107
108 /**
109 * Purge selected messages in the queue
110 *
111 * @param queue - ObjectName of the queue to purge the messages from
112 * @param messages - List of messages to purge
113 * @throws Exception
114 */
115 public void purgeMessages(ObjectName queue, List messages) throws Exception {
116 JMXConnector conn = createJmxConnector();
117 MBeanServerConnection server = conn.getMBeanServerConnection();
118
119 Object[] param = new Object[1];
120 for (Iterator i = messages.iterator(); i.hasNext();) {
121 CompositeData msg = (CompositeData)i.next();
122 param[0] = "" + msg.get("JMSMessageID");
123 context.printInfo("Removing message: " + param[0] + " from queue: " + queue.getKeyProperty("Destination"));
124 server.invoke(queue, "removeMessage", param, new String[] {
125 "java.lang.String"
126 });
127 }
128
129 conn.close();
130 }
131
132 /**
133 * Handle the --msgsel, --xmsgsel.
134 *
135 * @param token - option token to handle
136 * @param tokens - succeeding command arguments
137 * @throws Exception
138 */
139 protected void handleOption(String token, List<String> tokens) throws Exception {
140 // If token is an additive message selector option
141 if (token.startsWith("--msgsel")) {
142
143 // If no message selector is specified, or next token is a new
144 // option
145 if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
146 context.printException(new IllegalArgumentException("Message selector not specified"));
147 return;
148 }
149
150 StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
151 while (queryTokens.hasMoreTokens()) {
152 queryAddObjects.add(queryTokens.nextToken());
153 }
154 } else if (token.startsWith("--xmsgsel")) {
155 // If token is a substractive message selector option
156
157 // If no message selector is specified, or next token is a new
158 // option
159 if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
160 context.printException(new IllegalArgumentException("Message selector not specified"));
161 return;
162 }
163
164 StringTokenizer queryTokens = new StringTokenizer((String)tokens.remove(0), COMMAND_OPTION_DELIMETER);
165 while (queryTokens.hasMoreTokens()) {
166 querySubObjects.add(queryTokens.nextToken());
167 }
168
169 } else {
170 // Let super class handle unknown option
171 super.handleOption(token, tokens);
172 }
173 }
174
175 /**
176 * Print the help messages for the browse command
177 */
178 protected void printHelp() {
179 context.printHelp(helpFile);
180 }
181
182 }