Refactored the main class to several task class and use the main class to bootstrap each task.

git-svn-id: https://svn.apache.org/repos/asf/incubator/activemq/trunk@368560 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Adrian T. Co 2006-01-13 02:52:57 +00:00
parent 7a7496c841
commit 70c2d886d1
10 changed files with 1168 additions and 1018 deletions

View File

@ -0,0 +1,95 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import java.util.List;
import java.net.MalformedURLException;
import java.io.IOException;
public abstract class AbstractJmxTask extends AbstractTask {
public static final String DEFAULT_JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi";
private JMXServiceURL jmxServiceUrl;
private JMXConnector jmxConnector;
protected JMXServiceURL getJmxServiceUrl() throws Exception {
return jmxServiceUrl;
}
protected void setJmxServiceUrl(JMXServiceURL jmxServiceUrl) {
this.jmxServiceUrl = jmxServiceUrl;
}
protected void setJmxServiceUrl(String jmxServiceUrl) throws Exception {
setJmxServiceUrl(new JMXServiceURL(jmxServiceUrl));
}
protected JMXConnector createJmxConnector() throws Exception {
// Reuse the previous connection
if (jmxConnector != null) {
jmxConnector.connect();
return jmxConnector;
}
// Create a new JMX connector
if (getJmxServiceUrl() == null) {
setJmxServiceUrl(DEFAULT_JMX_URL);
}
jmxConnector = JMXConnectorFactory.connect(getJmxServiceUrl());
return jmxConnector;
}
protected void closeJmxConnector() {
try {
if (jmxConnector != null) {
jmxConnector.close();
jmxConnector = null;
}
} catch (IOException e) {
}
}
protected void handleOption(String token, List tokens) throws Exception {
// Try to handle the options first
if (token.equals("--jmxurl")) {
// If no jmx url specified, or next token is a new option
if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
printError("JMX URL not specified.");
}
// If jmx url already specified
if (getJmxServiceUrl() != null) {
printError("Multiple JMX URL cannot be specified.");
tokens.clear();
}
String strJmxUrl = (String)tokens.remove(0);
try {
this.setJmxServiceUrl(new JMXServiceURL(strJmxUrl));
} catch (MalformedURLException e) {
printError("Invalid JMX URL format: " + strJmxUrl);
tokens.clear();
}
} else {
// Let the super class handle the option
super.handleOption(token, tokens);
}
}
}

View File

@ -0,0 +1,99 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import org.apache.activemq.ActiveMQConnectionMetaData;
import java.util.List;
public abstract class AbstractTask implements Task {
private boolean isPrintHelp = false;
private boolean isPrintVersion = false;
public void runTask(List tokens) throws Exception {
parseOptions(tokens);
if (isPrintHelp) {
printHelp();
} else if (isPrintVersion) {
printVersion();
} else {
startTask(tokens);
}
}
protected void parseOptions(List tokens) throws Exception {
while (!tokens.isEmpty()) {
String token = (String)tokens.remove(0);
if (token.startsWith("-")) {
// Token is an option
handleOption(token, tokens);
} else {
// Push back to list of tokens
tokens.add(0, token);
return;
}
}
}
protected void handleOption(String token, List tokens) throws Exception {
// If token is a help option
if (token.equals("-h") || token.equals("-?") || token.equals("--help")) {
isPrintHelp = true;
tokens.clear();
// If token is a version option
} else if (token.equals("--version")) {
isPrintVersion = true;
tokens.clear();
}
// If token is a system property define option
else if (token.startsWith("-D")) {
String key = token.substring(2);
String value = "";
int pos = key.indexOf("=");
if (pos >= 0) {
value = key.substring(pos + 1);
key = key.substring(0, pos);
}
System.setProperty(key, value);
}
// Token is unrecognized
else {
System.out.println("Ignoring unrecognized option: " + token);
}
}
protected void printVersion() {
System.out.println();
System.out.println("ActiveMQ " + ActiveMQConnectionMetaData.PROVIDER_VERSION);
System.out.println("For help or more information please see: http://www.logicblaze.com");
System.out.println();
}
protected void printError(String message) {
isPrintHelp = true;
System.out.println(message);
System.out.println();
}
abstract protected void startTask(List tokens) throws Exception;
abstract protected void printHelp();
}

View File

@ -0,0 +1,283 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.MBeanAttributeInfo;
import javax.management.ObjectInstance;
import java.util.Set;
import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class AmqJmxSupport {
public static final String DEFAULT_JMX_DOMAIN = "org.apache.activemq";
public static Set getAllBrokers(MBeanServerConnection server) throws Exception {
return queryMBeans(server, new ObjectName(DEFAULT_JMX_DOMAIN + ":Type=Broker,*"));
}
public static Set getBrokers(MBeanServerConnection server, String brokerName) throws Exception {
return queryMBeans(server, "Type=Broker,BrokerName=" + brokerName + ",*");
}
public static Set queryMBeans(MBeanServerConnection server, List queryList) throws Exception {
Set mbeans;
// If there is no query defined get all mbeans
if (queryList==null || queryList.size()==0) {
ObjectName queryName = new ObjectName(DEFAULT_JMX_DOMAIN + ":*");
mbeans = queryMBeans(server, queryName);
// Parse through all the query strings
} else {
mbeans = new HashSet();
for (Iterator i=queryList.iterator(); i.hasNext();) {
String queryStr = (String)i.next();
mbeans.addAll(queryMBeans(server, queryStr));
}
}
return mbeans;
}
public static Set queryMBeans(MBeanServerConnection server, String queryString) throws Exception {
// Transform string to support regex filtering
List regexProp = new ArrayList();
queryString = transformWildcardQueryToObjectName(queryString, regexProp);
ObjectName queryName = new ObjectName(DEFAULT_JMX_DOMAIN + ":" + queryString);
return filterUsingRegEx(queryMBeans(server, queryName), regexProp);
}
public static Set queryMBeans(MBeanServerConnection server, ObjectName objName) throws Exception {
return server.queryMBeans(objName, null);
}
public static Map queryMBeanAttrs(MBeanServerConnection server, ObjectName mbeanObjName, List attrView) throws Exception {
Map attr = new HashMap();
MBeanAttributeInfo[] attrs = server.getMBeanInfo(mbeanObjName).getAttributes();
// If the mbean has no attribute, print a no attribute message
if (attrs.length == 0) {
return null;
}
// If there is no view specified, get all attributes
if (attrView == null || attrView.isEmpty()) {
for (int i=0; i<attrs.length; i++) {
Object attrVal = server.getAttribute(mbeanObjName, attrs[i].getName());
attr.put(attrs[i].getName(), attrVal);
}
return attr;
}
// Get attributes specified by view
for (int i=0; i<attrs.length; i++) {
if (attrView.contains(attrs[i].getName())) {
Object attrVal = server.getAttribute(mbeanObjName, attrs[i].getName());
attr.put(attrs[i].getName(), attrVal);
}
}
return attr;
}
public static String createQueryString(String query, String param) {
return query.replaceAll("%1", param);
}
public static String createQueryString(String query, List params) {
int count = 1;
for (Iterator i=params.iterator();i.hasNext();) {
query.replaceAll("%" + count++, i.next().toString());
}
return query;
}
public static void printBrokerList(Set brokerList) {
Object[] brokerArray = brokerList.toArray();
System.out.println("List of available brokers:");
for (int i=0; i<brokerArray.length; i++) {
String brokerName = ((ObjectInstance)brokerArray[i]).getObjectName().getKeyProperty("BrokerName");
System.out.println(" " + (i+1) + ".) " + brokerName);
}
}
public static void printMBeanProp(ObjectInstance mbean, List propView) {
// Filter properties to print
if (propView != null && !propView.isEmpty()) {
Map mbeanProps = mbean.getObjectName().getKeyPropertyList();
for (Iterator i=propView.iterator(); i.hasNext();) {
Object key = i.next();
Object val = mbeanProps.get(key);
if (val != null) {
System.out.println("MBean " + key + ": " + val);
}
}
// Print all properties
} else {
Map mbeanProps = mbean.getObjectName().getKeyPropertyList();
for (Iterator i=mbeanProps.keySet().iterator(); i.hasNext();) {
Object key = i.next();
Object val = mbeanProps.get(key);
System.out.println("MBean " + key + ": " + val);
}
}
}
public static void printMBeanAttr(MBeanServerConnection server, ObjectInstance mbean, List attrView) {
try {
Map attrList = queryMBeanAttrs(server, mbean.getObjectName(), attrView);
// If the mbean has no attribute, print a no attribute message
if (attrList == null) {
System.out.println(" MBean has no attributes.");
System.out.println();
return;
}
// If the mbean's attributes did not match any of the view, display a message
if (attrList.isEmpty()) {
System.out.println(" View did not match any of the mbean's attributes.");
System.out.println("");
return;
}
// Display mbean attributes
// If attrView is available, use it. This allows control over the display order
if (attrView != null && !attrView.isEmpty()) {
for (Iterator i=attrView.iterator(); i.hasNext();) {
Object key = i.next();
Object val = attrList.get(key);
if (val != null) {
System.out.println(" " + key + " = " + attrList.get(key));
}
}
// If attrView is not available, print all attributes
} else {
for (Iterator i=attrList.keySet().iterator(); i.hasNext();) {
Object key = i.next();
System.out.println(" " + key + " = " + attrList.get(key));
}
}
System.out.println("");
} catch (Exception e) {
System.out.println("Failed to print mbean attributes. Reason: " + e.getMessage());
}
}
private static String transformWildcardQueryToObjectName(String query, List regExMap) throws Exception {
if (regExMap==null) {
regExMap = new ArrayList();
}
StringBuffer newQueryStr = new StringBuffer();
for (StringTokenizer tokenizer = new StringTokenizer(query, ","); tokenizer.hasMoreTokens();) {
String token = tokenizer.nextToken();
// Get key value pair
String key = token;
String value = "";
int pos = key.indexOf("=");
if (pos >= 0) {
value = key.substring(pos + 1);
key = key.substring(0, pos);
}
// Check if value is a wildcard query
if ((value.indexOf("*") >= 0) || (value.indexOf("?") >= 0)) {
// If value is a wildcard query, convert to regex
// and remove the object name query to ensure it selects all
regExMap.add(Pattern.compile("(.*)(" + key + "=)(" + transformWildcardQueryToRegEx(value) + ")(,)(.*)"));
// Re-add valid key value pair. Remove all * property and just add one at the end.
} else if ((key != "") && (value != "")) {
newQueryStr.append(key + "=" + value + ",");
}
}
newQueryStr.append("*");
return newQueryStr.toString();
}
private static String transformWildcardQueryToRegEx(String query) {
query = query.replaceAll("[.]", "\\\\."); // Escape all dot characters. From (.) to (\.)
query = query.replaceAll("[?]", ".");
query = query.replaceAll("[*]", ".*?"); // Use reluctant quantifier
return query;
}
private static Set filterUsingRegEx(Set mbeans, List regexProp) {
// No regular expressions filtering needed
if (regexProp==null || regexProp.isEmpty()) {
return mbeans;
}
Set filteredMbeans = new HashSet();
// Get each bean to filter
for (Iterator i=mbeans.iterator(); i.hasNext();) {
ObjectInstance mbeanInstance = (ObjectInstance)i.next();
String mbeanName = mbeanInstance.getObjectName().getKeyPropertyListString();
// Ensure name ends with ,* to guarantee correct parsing behavior
if (!mbeanName.endsWith(",*")) {
mbeanName = mbeanName + ",*";
}
boolean match = true;
// Match the object name to each regex
for (Iterator j=regexProp.iterator(); j.hasNext();) {
Pattern p = (Pattern)j.next();
if (!p.matcher(mbeanName).matches()) {
match = false;
break;
}
}
// If name of mbean matches all regex pattern, add it
if (match) {
filteredMbeans.add(mbeanInstance);
}
}
return filteredMbeans;
}
}

View File

@ -0,0 +1,40 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
public class DefaultTask extends StartTask {
protected void printHelp() {
System.out.println("Usage: Main [task] [--extdir <dir>] [task-options] [task data]");
System.out.println("");
System.out.println("Tasks (default task is start):");
System.out.println(" start - Creates and starts a broker using a configuration file, or a broker URI.");
System.out.println(" stop - Stops a running broker specified by the broker name.");
System.out.println(" list - Lists all available brokers in the specified JMX context.");
System.out.println(" query - Display selected broker component's attributes and statistics.");
System.out.println(" --extdir <dir> - Add the jar files in the directory to the classpath.");
System.out.println(" --version - Display the version information.");
System.out.println(" -h,-?,--help - Display this help information. To display task specific help, use Main [task] -h,-?,--help");
System.out.println("");
System.out.println("Task Options:");
System.out.println(" - Properties specific to each task.");
System.out.println("");
System.out.println("Task Data:");
System.out.println(" - Information needed by each specific task.");
System.out.println("");
}
}

View File

@ -0,0 +1,43 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import java.util.List;
public class ListTask extends AbstractJmxTask {
protected void startTask(List tokens) {
try {
AmqJmxSupport.printBrokerList(AmqJmxSupport.getAllBrokers(createJmxConnector().getMBeanServerConnection()));
closeJmxConnector();
} catch (Throwable e) {
System.out.println("Failed to execute list task. Reason: " + e);
}
}
protected void printHelp() {
System.out.println("Task Usage: Main list [list-options]");
System.out.println("Description: Lists all available broker in the specified JMX context.");
System.out.println("");
System.out.println("List Options:");
System.out.println(" --jmxurl <url> Set the JMX URL to connect to.");
System.out.println(" --version Display the version information.");
System.out.println(" -h,-?,--help Display the stop broker help information.");
System.out.println("");
}
}

View File

@ -0,0 +1,206 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import javax.management.remote.JMXConnector;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import java.util.List;
import java.util.Properties;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Set;
import java.util.Iterator;
public class QueryTask extends AbstractJmxTask {
// Predefined type=identifier query
private static final Properties PREDEFINED_OBJNAME_QUERY = new Properties();
static {
PREDEFINED_OBJNAME_QUERY.setProperty("Broker", "Type=Broker,BrokerName=%1,*");
PREDEFINED_OBJNAME_QUERY.setProperty("Connection", "Type=Connection,Connection=%1,*");
PREDEFINED_OBJNAME_QUERY.setProperty("Connector", "Type=Connector,ConnectorName=%1,*");
PREDEFINED_OBJNAME_QUERY.setProperty("NetworkConnector", "Type=NetworkConnector,BrokerName=%1,*");
PREDEFINED_OBJNAME_QUERY.setProperty("Queue", "Type=Queue,Destination=%1,*");
PREDEFINED_OBJNAME_QUERY.setProperty("Topic", "Type=Topic,Destination=%1,*");
};
private final List queryAddObjects = new ArrayList(10);
private final List querySubObjects = new ArrayList(10);
private final List queryViews = new ArrayList(10);
protected void startTask(List tokens) {
try {
// Connect to jmx server
JMXConnector jmxConnector = createJmxConnector();
MBeanServerConnection server = jmxConnector.getMBeanServerConnection();
// Query for the mbeans to add
Set addMBeans = AmqJmxSupport.queryMBeans(server, queryAddObjects);
// Query for the mbeans to sub
if (querySubObjects.size() > 0) {
Set subMBeans = AmqJmxSupport.queryMBeans(server, querySubObjects);
addMBeans.removeAll(subMBeans);
}
for (Iterator i=addMBeans.iterator(); i.hasNext();) {
ObjectInstance mbean = (ObjectInstance)i.next();
AmqJmxSupport.printMBeanProp(mbean, null);
AmqJmxSupport.printMBeanAttr(server, mbean, queryViews);
}
closeJmxConnector();
} catch (Throwable e) {
System.out.println("Failed to execute query task. Reason: " + e);
}
}
protected void handleOption(String token, List tokens) throws Exception {
// If token is a additive predefined query define option
if (token.startsWith("-Q")) {
String key = token.substring(2);
String value = "";
int pos = key.indexOf("=");
if (pos >= 0) {
value = key.substring(pos + 1);
key = key.substring(0, pos);
}
// If additive query
String predefQuery = PREDEFINED_OBJNAME_QUERY.getProperty(key);
if (predefQuery == null) {
printError("Unknown query object type: " + key);
return;
}
String queryStr = AmqJmxSupport.createQueryString(predefQuery, value);
queryAddObjects.add(queryStr);
}
// If token is a substractive predefined query define option
else if (token.startsWith("-xQ")) {
String key = token.substring(3);
String value = "";
int pos = key.indexOf("=");
if (pos >= 0) {
value = key.substring(pos + 1);
key = key.substring(0, pos);
}
// If subtractive query
String predefQuery = PREDEFINED_OBJNAME_QUERY.getProperty(key);
if (predefQuery == null) {
printError("Unknown query object type: " + key);
return;
}
String queryStr = AmqJmxSupport.createQueryString(predefQuery, value);
querySubObjects.add(queryStr);
}
// If token is an additive object name query option
else if (token.startsWith("--objname")) {
// If no object name query is specified, or next token is a new option
if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
printError("Object name query not specified");
return;
}
String queryString = (String)tokens.remove(0);
queryAddObjects.add(queryString);
}
// If token is a substractive object name query option
else if (token.startsWith("--xobjname")) {
// If no object name query is specified, or next token is a new option
if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
printError("Object name query not specified");
return;
}
String queryString = (String)tokens.remove(0);
querySubObjects.add(queryString);
}
// If token is a view option
else if (token.startsWith("--view")) {
// If no view specified, or next token is a new option
if (tokens.isEmpty() || ((String)tokens.get(0)).startsWith("-")) {
printError("Attributes to view not specified");
return;
}
// Add the attributes to view
Enumeration viewTokens = new StringTokenizer((String)tokens.remove(0), ",", false);
while (viewTokens.hasMoreElements()) {
queryViews.add(viewTokens.nextElement());
}
}
// Let super class handle unknown option
else {
super.handleOption(token, tokens);
}
}
protected void printHelp() {
System.out.println("Task Usage: Main query [query-options]");
System.out.println("Description: Display selected broker component's attributes and statistics.");
System.out.println("");
System.out.println("Query Options:");
System.out.println(" -Q<type>=<name> Add to the search list the specific object type matched by the defined object identifier.");
System.out.println(" -xQ<type>=<name> Remove from the search list the specific object type matched by the object identifier.");
System.out.println(" --objname <query> Add to the search list objects matched by the query similar to the JMX object name format.");
System.out.println(" --xobjname <query> Remove from the search list objects matched by the query similar to the JMX object name format.");
System.out.println(" --view <attr1>,<attr2>,... Select the specific attribute of the object to view. By default all attributes will be displayed.");
System.out.println(" --jmxurl <url> Set the JMX URL to connect to.");
System.out.println(" --version Display the version information.");
System.out.println(" -h,-?,--help Display the query broker help information.");
System.out.println("");
System.out.println("Examples:");
System.out.println(" Main query");
System.out.println(" - Print all the attributes of all registered objects (queues, topics, connections, etc).");
System.out.println("");
System.out.println(" Main query -QQueue=TEST.FOO");
System.out.println(" - Print all the attributes of the queue with destination name TEST.FOO.");
System.out.println("");
System.out.println(" Main query -QTopic=*");
System.out.println(" - Print all the attributes of all registered topics.");
System.out.println("");
System.out.println(" Main query --view EnqueueCount,DequeueCount");
System.out.println(" - Print the attributes EnqueueCount and DequeueCount of all registered objects.");
System.out.println("");
System.out.println(" Main -QTopic=* --view EnqueueCount,DequeueCount");
System.out.println(" - Print the attributes EnqueueCount and DequeueCount of all registered topics.");
System.out.println("");
System.out.println(" Main -QTopic=* -QQueue=* --view EnqueueCount,DequeueCount");
System.out.println(" - Print the attributes EnqueueCount and DequeueCount of all registered topics and queues.");
System.out.println("");
System.out.println(" Main -QTopic=* -xQTopic=ActiveMQ.Advisory.*");
System.out.println(" - Print all attributes of all topics except those that has a name that begins with \"ActiveMQ.Advisory\".");
System.out.println("");
System.out.println(" Main --objname Type=*Connect*,BrokerName=local* -xQNetworkConnector=*");
System.out.println(" - Print all attributes of all connectors, connections excluding network connectors that belongs to the broker that begins with local.");
System.out.println("");
System.out.println(" Main -QQueue=* -xQQueue=????");
System.out.println(" - Print all attributes of all queues except those that are 4 letters long.");
System.out.println("");
}
}

View File

@ -0,0 +1,132 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.ObjectInstance;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import java.util.HashSet;
public class ShutdownTask extends AbstractJmxTask {
private boolean isStopAllBrokers = false;
protected void startTask(List brokerNames) {
try {
Set mbeans = new HashSet();
MBeanServerConnection server = createJmxConnector().getMBeanServerConnection();
// Stop all brokers
if (isStopAllBrokers) {
mbeans = AmqJmxSupport.getAllBrokers(server);
brokerNames.clear();
}
// Stop the default broker
else if (brokerNames.isEmpty()) {
mbeans = AmqJmxSupport.getAllBrokers(server);
// If there is no broker to stop
if (mbeans.isEmpty()) {
System.out.println("There are no brokers to stop.");
return;
// There should only be one broker to stop
} else if (mbeans.size() > 1) {
System.out.println("There are multiple brokers to stop. Please select the broker(s) to stop or use --all to stop all brokers.");
System.out.println();
AmqJmxSupport.printBrokerList(mbeans);
return;
// Get the first broker only
} else {
Object firstBroker = mbeans.iterator().next();
mbeans.clear();
mbeans.add(firstBroker);
}
}
// Stop each specified broker
else {
String brokerName;
while (!brokerNames.isEmpty()) {
brokerName = (String)brokerNames.remove(0);
Set matchedBrokers = AmqJmxSupport.getBrokers(server, brokerName);
if (matchedBrokers.isEmpty()) {
System.out.println(brokerName + " did not match any running brokers.");
} else {
mbeans.addAll(matchedBrokers);
}
}
}
// Stop all brokers in set
stopBrokers(server, mbeans);
closeJmxConnector();
} catch (Throwable e) {
System.out.println("Failed to execute stop task. Reason: " + e);
}
}
protected void stopBrokers(MBeanServerConnection server, Set brokerBeans) throws Exception {
ObjectName brokerObjName;
for (Iterator i=brokerBeans.iterator(); i.hasNext();) {
brokerObjName = ((ObjectInstance)i.next()).getObjectName();
String brokerName = brokerObjName.getKeyProperty("BrokerName");
System.out.println("Stopping broker: " + brokerName);
try {
server.invoke(brokerObjName, "terminateJVM", new Object[] {new Integer(0)}, new String[] {"int"});
System.out.println("Succesfully stopped broker: " + brokerName);
} catch (Exception e) {
// TODO: Check exceptions throwned
//System.out.println("Failed to stop broker: [ " + brokerName + " ]. Reason: " + e.getMessage());
}
}
}
protected void printHelp() {
System.out.println("Task Usage: Main stop [stop-options] [broker-name1] [broker-name2] ...");
System.out.println("Description: Stops a running broker.");
System.out.println("");
System.out.println("Stop Options:");
System.out.println(" --jmxurl <url> Set the JMX URL to connect to.");
System.out.println(" --all Stop all brokers.");
System.out.println(" --version Display the version information.");
System.out.println(" -h,-?,--help Display the stop broker help information.");
System.out.println("");
System.out.println("Broker Names:");
System.out.println(" Name of the brokers that will be stopped.");
System.out.println(" If omitted, it is assumed that there is only one broker running, and it will be stopped.");
System.out.println(" Use -all to stop all running brokers.");
System.out.println("");
}
protected void handleOption(String token, List tokens) throws Exception {
// Try to handle the options first
if (token.equals("--all")) {
isStopAllBrokers = true;
} else {
// Let the super class handle the option
super.handleOption(token, tokens);
}
}
}

View File

@ -0,0 +1,163 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.net.URI;
import java.net.URISyntaxException;
public class StartTask extends AbstractTask {
public static final String DEFAULT_CONFIG_URI = "xbean:activemq.xml";
private URI configURI;
private List brokers = new ArrayList(5);
/**
* The default task to start a broker or a group of brokers
* @param brokerURIs
*/
protected void startTask(List brokerURIs) {
try {
// If no config uri, use default setting
if (brokerURIs.isEmpty()) {
setConfigUri(new URI(DEFAULT_CONFIG_URI));
startBroker(getConfigUri());
// Set configuration data, if available, which in this case would be the config URI
} else {
String strConfigURI;
while (!brokerURIs.isEmpty()) {
strConfigURI = (String)brokerURIs.remove(0);
try {
setConfigUri(new URI(strConfigURI));
} catch (URISyntaxException e) {
printError("Invalid broker configuration URI: " + strConfigURI + ", reason: " + e.getMessage());
return;
}
startBroker(getConfigUri());
}
}
// Prevent the main thread from exiting unless it is terminated elsewhere
waitForShutdown();
} catch (Throwable e) {
System.out.println("Failed to execute start task. Reason: " + e);
}
}
/**
* Create and run a broker specified by the given configuration URI
* @param configURI
* @throws Exception
*/
public void startBroker(URI configURI) throws Exception {
System.out.println("Loading message broker from: " + configURI);
BrokerService broker = BrokerFactory.createBroker(configURI);
brokers.add(broker);
broker.start();
}
/**
* Wait for a shutdown invocation elsewhere
* @throws Exception
*/
protected void waitForShutdown() throws Exception {
final boolean[] shutdown = new boolean[] {false};
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
synchronized(shutdown) {
shutdown[0]=true;
shutdown.notify();
}
}
});
// Wait for any shutdown event
synchronized(shutdown) {
while( !shutdown[0] ) {
try {
shutdown.wait();
} catch (InterruptedException e) {
}
}
}
// Stop each broker
for (Iterator i=brokers.iterator(); i.hasNext();) {
BrokerService broker = (BrokerService)i.next();
broker.stop();
}
}
/**
* Prints the help for the start broker task
*/
protected void printHelp() {
System.out.println("Task Usage: Main start [start-options] [uri]");
System.out.println("Description: Creates and starts a broker using a configuration file, or a broker URI.");
System.out.println("");
System.out.println("Start Options:");
System.out.println(" --extdir <dir> Add the jar files in the directory to the classpath.");
System.out.println(" -D<name>=<value> Define a system property.");
System.out.println(" --version Display the version information.");
System.out.println(" -h,-?,--help Display the start broker help information.");
System.out.println("");
System.out.println("URI:");
System.out.println("");
System.out.println(" XBean based broker configuration:");
System.out.println("");
System.out.println(" Example: Main xbean:file:activemq.xml");
System.out.println(" Loads the xbean configuration file from the current working directory");
System.out.println(" Example: Main xbean:activemq.xml");
System.out.println(" Loads the xbean configuration file from the classpath");
System.out.println("");
System.out.println(" URI Parameter based broker configuration:");
System.out.println("");
System.out.println(" Example: Main broker:(tcp://localhost:61616, tcp://localhost:5000)?useJmx=true");
System.out.println(" Configures the broker with 2 transport connectors and jmx enabled");
System.out.println(" Example: Main broker:(tcp://localhost:61616, network:tcp://localhost:5000)?persistent=false");
System.out.println(" Configures the broker with 1 transport connector, and 1 network connector and persistence disabled");
System.out.println("");
}
/**
* Sets the current configuration URI used by the start task
* @param uri
*/
public void setConfigUri(URI uri) {
configURI = uri;
}
/**
* Gets the current configuration URI used by the start task
* @return current configuration URI
*/
public URI getConfigUri() {
return configURI;
}
}

View File

@ -0,0 +1,24 @@
/**
*
* Copyright 2005-2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.console;
import java.util.List;
public interface Task {
public void runTask(List tokens) throws Exception;
}