Java/J2EE/JMX — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:49, 1 июня 2010
Содержание
- 1 Create the Hello MBean and QueueSampler MXBean, register them in the platform MBean server
- 2 how failure to supply an appropriate authentication mechanism results in a failure to create an initial context
- 3 JMX client
- 4 JMX client that interacts with the JMX agent
- 5 JMX (Java Management Extensions): scan directory
- 6 List JMX destination
- 7 MQ log
Create the Hello MBean and QueueSampler MXBean, register them in the platform MBean server
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Main.java - main class for the Hello MBean and QueueSampler MXBean example.
* Create the Hello MBean and QueueSampler MXBean, register them in the platform
* MBean server, then wait forever (or until the program is interrupted).
*/
import java.beans.ConstructorProperties;
import java.lang.management.ManagementFactory;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
public class Main {
/*
* For simplicity, we declare "throws Exception". Real programs will usually
* want finer-grained exception handling.
*/
public static void main(String[] args) throws Exception {
// Get the Platform MBean Server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Construct the ObjectName for the Hello MBean we will register
ObjectName mbeanName = new ObjectName("com.example:type=Hello");
// Create the Hello World MBean
Hello mbean = new Hello();
// Register the Hello World MBean
mbs.registerMBean(mbean, mbeanName);
// Construct the ObjectName for the QueueSampler MXBean we will register
ObjectName mxbeanName = new ObjectName("com.example:type=QueueSampler");
// Create the Queue Sampler MXBean
Queue<String> queue = new ArrayBlockingQueue<String>(10);
queue.add("Request-1");
queue.add("Request-2");
queue.add("Request-3");
QueueSampler mxbean = new QueueSampler(queue);
// Register the Queue Sampler MXBean
mbs.registerMBean(mxbean, mxbeanName);
// Wait forever
System.out.println("Waiting for incoming requests...");
Thread.sleep(Long.MAX_VALUE);
}
}
/*
* QueueSample.java - Java type representing a snapshot of a given queue. It
* bundles together the instant time the snapshot was taken, the queue size and
* the queue head.
*/
interface QueueSamplerMXBean {
public QueueSample getQueueSample();
public void clearQueue();
}
class QueueSample {
private final Date date;
private final int size;
private final String head;
@ConstructorProperties( { "date", "size", "head" })
public QueueSample(Date date, int size, String head) {
this.date = date;
this.size = size;
this.head = head;
}
public Date getDate() {
return date;
}
public int getSize() {
return size;
}
public String getHead() {
return head;
}
}
/*
* Hello.java - MBean implementation for the Hello MBean. This class must
* implement all the Java methods declared in the HelloMBean interface, with the
* appropriate behavior for each one.
*/
class QueueSampler implements QueueSamplerMXBean {
private Queue<String> queue;
public QueueSampler(Queue<String> queue) {
this.queue = queue;
}
public QueueSample getQueueSample() {
synchronized (queue) {
return new QueueSample(new Date(), queue.size(), queue.peek());
}
}
public void clearQueue() {
synchronized (queue) {
queue.clear();
}
}
}/*
* HelloMBean.java - MBean interface describing the management operations and
* attributes for the Hello World MBean. In this case there are two
* operations, "sayHello" and "add", and two attributes, "Name" and
* "CacheSize".
*/
interface HelloMBean {
// -----------
// operations
// -----------
public void sayHello();
public int add(int x, int y);
// -----------
// attributes
// -----------
// a read-only attribute called Name of type String
public String getName();
// a read-write attribute called CacheSize of type int
public int getCacheSize();
public void setCacheSize(int size);
}
class Hello extends NotificationBroadcasterSupport implements HelloMBean {
public void sayHello() {
System.out.println("hello, world");
}
public int add(int x, int y) {
return x + y;
}
/*
* Getter for the Name attribute. The pattern shown here is frequent: the
* getter returns a private field representing the attribute value. In our
* case, the attribute value never changes, but for other attributes it might
* change as the application runs. Consider an attribute representing
* statistics such as uptime or memory usage, for example. Being read-only
* just means that it can"t be changed through the management interface.
*/
public String getName() {
return this.name;
}
/*
* Getter for the CacheSize attribute. The pattern shown here is frequent: the
* getter returns a private field representing the attribute value, and the
* setter changes that field.
*/
public int getCacheSize() {
return this.cacheSize;
}
/*
* Setter for the CacheSize attribute. To avoid problems with stale values in
* multithreaded situations, it is a good idea for setters to be synchronized.
*/
public synchronized void setCacheSize(int size) {
int oldSize = this.cacheSize;
this.cacheSize = size;
/*
* In a real application, changing the attribute would typically have
* effects beyond just modifying the cacheSize field. For example, resizing
* the cache might mean discarding entries or allocating new ones. The logic
* for these effects would be here.
*/
System.out.println("Cache size now " + this.cacheSize);
/*
* Construct a notification that describes the change. The "source" of a
* notification is the ObjectName of the MBean that emitted it. But an MBean
* can put a reference to itself ("this") in the source, and the MBean
* server will replace this with the ObjectName before sending the
* notification on to its clients.
*
* For good measure, we maintain a sequence number for each notification
* emitted by this MBean.
*
* The oldValue and newValue parameters to the constructor are of type
* Object, so we are relying on Tiger"s autoboxing here.
*/
Notification n = new AttributeChangeNotification(this, sequenceNumber++,
System.currentTimeMillis(), "CacheSize changed", "CacheSize", "int",
oldSize, this.cacheSize);
/*
* Now send the notification using the sendNotification method inherited
* from the parent class NotificationBroadcasterSupport.
*/
sendNotification(n);
}
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
String[] types = new String[] { AttributeChangeNotification.ATTRIBUTE_CHANGE };
String name = AttributeChangeNotification.class.getName();
String description = "An attribute of this MBean has changed";
MBeanNotificationInfo info = new MBeanNotificationInfo(types, name,
description);
return new MBeanNotificationInfo[] { info };
}
private final String name = "Reginald";
private int cacheSize = DEFAULT_CACHE_SIZE;
private static final int DEFAULT_CACHE_SIZE = 200;
private long sequenceNumber = 1;
}
how failure to supply an appropriate authentication mechanism results in a failure to create an initial context
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* Demonstrates how failure to supply an appropriate authentication mechanism
* results in a failure to create an initial context
*
* usage: java BadAuth
*/
class BadAuth {
public static void main(String[] args) {
// Set up environment for creating initial context
Hashtable<String, Object> env = new Hashtable<String, Object>(11);
env
.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "custom");
env.put(Context.SECURITY_PRINCIPAL,
"cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
System.out.println(ctx.lookup("ou=NewHires"));
// do something useful with ctx
// Close the context when we"re done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
JMX client
/*
* @(#)SimpleClient.java 1.2 05/08/08
*
* Copyright (c) 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import javax.management.*;
import javax.management.remote.*;
import com.sun.messaging.AdminConnectionFactory;
import com.sun.messaging.jms.management.server.MQObjectName;
import com.sun.messaging.jms.management.server.BrokerAttributes;
public class SimpleClient {
public static void main(String[] args) {
try {
AdminConnectionFactory acf;
/*
* Create admin connection factory and connect to JMX Connector
* server using administrator username/password.
* A JMX connector client object is obtained from this.
*/
acf = new AdminConnectionFactory();
JMXConnector jmxc = acf.createConnection("admin","admin");
/*
* Get MBeanServer interface.
*/
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
/*
* Create object name of broker config MBean.
*/
ObjectName objName
= new ObjectName(MQObjectName.BROKER_MONITOR_MBEAN_NAME);
/*
* Get attributes:
* InstanceName
* Version
*/
System.out.println("Broker Instance Name = " +
mbsc.getAttribute(objName, BrokerAttributes.INSTANCE_NAME));
System.out.println("Broker Version = " +
mbsc.getAttribute(objName, BrokerAttributes.VERSION));
jmxc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JMX client that interacts with the JMX agent
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Client.java - JMX client that interacts with the JMX agent. It gets
* attributes and performs operations on the Hello MBean and the QueueSampler
* MXBean example. It also listens for Hello MBean notifications.
*/
import java.beans.ConstructorProperties;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import javax.management.AttributeChangeNotification;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class Client {
/**
* Inner class that will handle the notifications.
*/
public static class ClientListener implements NotificationListener {
public void handleNotification(Notification notification, Object handback) {
echo("\nReceived notification:");
echo("\tClassName: " + notification.getClass().getName());
echo("\tSource: " + notification.getSource());
echo("\tType: " + notification.getType());
echo("\tMessage: " + notification.getMessage());
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification acn = (AttributeChangeNotification) notification;
echo("\tAttributeName: " + acn.getAttributeName());
echo("\tAttributeType: " + acn.getAttributeType());
echo("\tNewValue: " + acn.getNewValue());
echo("\tOldValue: " + acn.getOldValue());
}
}
}
/*
* For simplicity, we declare "throws Exception". Real programs will usually
* want finer-grained exception handling.
*/
public static void main(String[] args) throws Exception {
// Create an RMI connector client and
// connect it to the RMI connector server
//
echo("\nCreate an RMI connector client and "
+ "connect it to the RMI connector server");
JMXServiceURL url = new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
// Create listener
//
ClientListener listener = new ClientListener();
// Get an MBeanServerConnection
//
echo("\nGet an MBeanServerConnection");
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
waitForEnterPressed();
// Get domains from MBeanServer
//
echo("\nDomains:");
String domains[] = mbsc.getDomains();
Arrays.sort(domains);
for (String domain : domains) {
echo("\tDomain = " + domain);
}
waitForEnterPressed();
// Get MBeanServer"s default domain
//
echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());
// Get MBean count
//
echo("\nMBean count = " + mbsc.getMBeanCount());
// Query MBean names
//
echo("\nQuery MBeanServer MBeans:");
Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
for (ObjectName name : names) {
echo("\tObjectName = " + name);
}
waitForEnterPressed();
// ----------------------
// Manage the Hello MBean
// ----------------------
echo("\n>>> Perform operations on Hello MBean <<<");
// Construct the ObjectName for the Hello MBean
//
ObjectName mbeanName = new ObjectName("com.example:type=Hello");
// Create a dedicated proxy for the MBean instead of
// going directly through the MBean server connection
//
HelloMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName,
HelloMBean.class, true);
// Add notification listener on Hello MBean
//
echo("\nAdd notification listener...");
mbsc.addNotificationListener(mbeanName, listener, null, null);
// Get CacheSize attribute in Hello MBean
//
echo("\nCacheSize = " + mbeanProxy.getCacheSize());
// Set CacheSize attribute in Hello MBean
// Calling "reset" makes the Hello MBean emit a
// notification that will be received by the registered
// ClientListener.
//
mbeanProxy.setCacheSize(150);
// Sleep for 2 seconds to have time to receive the notification
//
echo("\nWaiting for notification...");
sleep(2000);
// Get CacheSize attribute in Hello MBean
//
echo("\nCacheSize = " + mbeanProxy.getCacheSize());
// Invoke "sayHello" in Hello MBean
//
echo("\nInvoke sayHello() in Hello MBean...");
mbeanProxy.sayHello();
// Invoke "add" in Hello MBean
//
echo("\nInvoke add(2, 3) in Hello MBean...");
echo("\nadd(2, 3) = " + mbeanProxy.add(2, 3));
waitForEnterPressed();
// ------------------------------
// Manage the QueueSampler MXBean
// ------------------------------
echo("\n>>> Perform operations on QueueSampler MXBean <<<");
// Construct the ObjectName for the QueueSampler MXBean
//
ObjectName mxbeanName = new ObjectName("com.example:type=QueueSampler");
// Create a dedicated proxy for the MXBean instead of
// going directly through the MBean server connection
//
QueueSamplerMXBean mxbeanProxy = JMX.newMXBeanProxy(mbsc, mxbeanName,
QueueSamplerMXBean.class);
// Get QueueSample attribute in QueueSampler MXBean
//
QueueSample queue1 = mxbeanProxy.getQueueSample();
echo("\nQueueSample.Date = " + queue1.getDate());
echo("QueueSample.Head = " + queue1.getHead());
echo("QueueSample.Size = " + queue1.getSize());
// Invoke "clearQueue" in QueueSampler MXBean
//
echo("\nInvoke clearQueue() in QueueSampler MXBean...");
mxbeanProxy.clearQueue();
// Get QueueSample attribute in QueueSampler MXBean
//
QueueSample queue2 = mxbeanProxy.getQueueSample();
echo("\nQueueSample.Date = " + queue2.getDate());
echo("QueueSample.Head = " + queue2.getHead());
echo("QueueSample.Size = " + queue2.getSize());
waitForEnterPressed();
// Close MBeanServer connection
//
echo("\nClose the connection to the server");
jmxc.close();
echo("\nBye! Bye!");
}
private static void echo(String msg) {
System.out.println(msg);
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void waitForEnterPressed() {
try {
echo("\nPress <Enter> to continue...");
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* HelloMBean.java - MBean interface describing the management operations and
* attributes for the Hello World MBean. In this case there are two operations,
* "sayHello" and "add", and two attributes, "Name" and "CacheSize".
*/
interface HelloMBean {
// -----------
// operations
// -----------
public void sayHello();
public int add(int x, int y);
// -----------
// attributes
// -----------
// a read-only attribute called Name of type String
public String getName();
// a read-write attribute called CacheSize of type int
public int getCacheSize();
public void setCacheSize(int size);
}
/*
* QueueSample.java - Java type representing a snapshot of a given queue. It
* bundles together the instant time the snapshot was taken, the queue size and
* the queue head.
*/
interface QueueSamplerMXBean {
public QueueSample getQueueSample();
public void clearQueue();
}
class QueueSample {
private final Date date;
private final int size;
private final String head;
@ConstructorProperties( { "date", "size", "head" })
public QueueSample(Date date, int size, String head) {
this.date = date;
this.size = size;
this.head = head;
}
public Date getDate() {
return date;
}
public int getSize() {
return size;
}
public String getHead() {
return head;
}
}
JMX (Java Management Extensions): scan directory
List JMX destination
/*
* @(#)ListDestinations.java 1.5 05/08/23
*
* Copyright (c) 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import javax.management.*;
import javax.management.remote.*;
import com.sun.messaging.AdminConnectionFactory;
import com.sun.messaging.jms.management.server.MQObjectName;
import com.sun.messaging.jms.management.server.DestinationAttributes;
import com.sun.messaging.jms.management.server.DestinationOperations;
public class ListDestinations {
public static void main(String[] args) {
try {
AdminConnectionFactory acf;
/*
* Create admin connection factory and connect to JMX Connector
* server using administrator username/password.
* A JMX connector client object is obtained from this.
*/
acf = new AdminConnectionFactory();
JMXConnector jmxc = acf.createConnection("admin", "admin");
/*
* Get MBeanServer interface.
*/
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
/*
* Create object name of destination monitor mgr MBean.
*/
ObjectName objName
= new ObjectName(MQObjectName.DESTINATION_MANAGER_MONITOR_MBEAN_NAME);
ObjectName destinationObjNames[] =
(ObjectName[])mbsc.invoke(objName, DestinationOperations.GET_DESTINATIONS, null, null);
System.out.println("Listing destinations:" );
for (int i = 0; i < destinationObjNames.length; ++i) {
ObjectName oneDestObjName = destinationObjNames[i];
System.out.println("\tName: " +
mbsc.getAttribute(oneDestObjName, DestinationAttributes.NAME));
System.out.println("\tType: " +
mbsc.getAttribute(oneDestObjName, DestinationAttributes.TYPE));
System.out.println("\tState: " +
mbsc.getAttribute(oneDestObjName, DestinationAttributes.STATE_LABEL));
System.out.println("");
}
jmxc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
MQ log
/*
* @(#)MQLogViewer.java 1.4 05/08/08
*
* Copyright (c) 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
import javax.management.*;
import javax.management.remote.*;
import com.sun.messaging.AdminConnectionFactory;
import com.sun.messaging.AdminConnectionConfiguration;
import com.sun.messaging.jms.management.server.*;
public class MQLogViewer implements ActionListener,
NotificationListener {
JFrame f;
MQConnectDialog connectDialog = null;
JMenuItem exit, connect, disconnect, clearLog;
JCheckBoxMenuItem info, warning, error;
JTextArea logMsgArea, statusTextArea;
JLabel brokerAddress;
String address = null, adminUser = "admin", adminPasswd = "admin";
String logLevelStrings[] = { LogLevel.INFO,
LogLevel.WARNING,
LogLevel.ERROR };
AdminConnectionFactory acf;
JMXConnector jmxc;
MBeanServerConnection mbsc;
ObjectName logCfg = null;
NotificationFilterSupport myFilter = null;
public MQLogViewer(JFrame f, String address,
String adminUser, String adminPasswd) {
this.f = f;
this.address = address;
this.adminUser = adminUser;
this.adminPasswd = adminPasswd;
try {
logCfg = new ObjectName(MQObjectName.LOG_MONITOR_MBEAN_NAME);
} catch (Exception e) {
addStatusText("Caught exception while creating Log MBean ObjectName: " + e);
}
initGUI();
if ((address != null) && (adminUser != null) && (adminPasswd != null)) {
doConnect();
}
}
private void initGUI() {
JMenuBar menubar = createMenubar();
JComponent toolbar = createToolBar();
JPanel mainPanel = createMainPanel();
JPanel statusArea = createStatusArea();
f.setJMenuBar(menubar);
f.getContentPane().add(toolbar, BorderLayout.NORTH);
f.getContentPane().add(mainPanel, BorderLayout.CENTER);
f.getContentPane().add(statusArea, BorderLayout.SOUTH);
}
public void logMessage(LogNotification n) {
logMsgArea.append(n.getMessage());
logMsgArea.setCaretPosition(logMsgArea.getText().length());
}
public void clearLogArea() {
logMsgArea.setText("");
}
public void addStatusText(String statusText) {
statusTextArea.append(statusText);
statusTextArea.setCaretPosition(statusTextArea.getText().length());
statusTextArea.append("\n");
}
public void clearStatus() {
statusTextArea.setText("");
}
public void doConnect() {
try {
acf = new AdminConnectionFactory();
if (address != null) {
acf.setProperty(AdminConnectionConfiguration.imqAddress,
address);
}
jmxc = acf.createConnection(adminUser, adminPasswd);
jmxc.addConnectionNotificationListener(this, null, null);
mbsc = jmxc.getMBeanServerConnection();
addStatusText("Connected to broker at: "
+ acf.getProperty(AdminConnectionConfiguration.imqAddress));
brokerAddress.setText(
acf.getProperty(AdminConnectionConfiguration.imqAddress));
logOn();
connect.setEnabled(false);
disconnect.setEnabled(true);
} catch (Exception e) {
addStatusText("Caught exception while connecting: " + e);
}
}
public void doDisconnect() {
try {
logOff();
addStatusText("Disconnecting from broker at: "
+ acf.getProperty(AdminConnectionConfiguration.imqAddress));
brokerAddress.setText("<none>");
if (jmxc != null) {
jmxc.close();
}
jmxc = null;
mbsc = null;
acf = null;
connect.setEnabled(true);
disconnect.setEnabled(false);
clearLogArea();
} catch (Exception e) {
addStatusText("Caught exception while disconnecting: " + e);
}
}
public void logOff() {
if (myFilter != null) {
try {
if (mbsc != null) {
mbsc.removeNotificationListener(logCfg, this, myFilter, null);
}
myFilter = null;
addStatusText("Unregistered log listener");
} catch(Exception e) {
addStatusText("Caught exception while removing log listener: " + e);
}
}
}
public void logOn() {
String logLevels = getLogLevel();
logOff();
if (logLevels.equals("")) {
addStatusText("No log levels selected.");
return;
}
myFilter = new NotificationFilterSupport();
StringTokenizer st = new StringTokenizer(logLevels, "|");
while (st.hasMoreTokens()) {
String oneLevel = st.nextToken();
myFilter.enableType(LogNotification.LOG_LEVEL_PREFIX + oneLevel);
}
try {
mbsc.addNotificationListener(logCfg, this, myFilter, null);
addStatusText("Registered listener at log levels: " + logLevels);
} catch(Exception e) {
addStatusText("Caught exception while addind log listener: " + e);
}
}
public String getLogLevel() {
String s = null;
if (info.getState()) {
s = info.getText();
}
if (warning.getState()) {
if (s == null) {
s = warning.getText();
} else {
s = s + "|" + warning.getText();
}
}
if (error.getState()) {
if (s == null) {
s = error.getText();
} else {
s = s + "|" + error.getText();
}
}
if (s == null) {
return ("");
}
return (s);
}
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof LogNotification) {
logMessage((LogNotification)notification);
} else if (notification instanceof JMXConnectionNotification) {
JMXConnectionNotification jcn = (JMXConnectionNotification)notification;
/*
* TBD: handle server shutdown
*/
if (jcn.getType().equals(JMXConnectionNotification.CLOSED) ||
jcn.getType().equals(JMXConnectionNotification.FAILED)) {
}
}
}
private JMenuBar createMenubar() {
JMenuBar menubar;
JMenu menu, logLevelMenu;
menubar = new JMenuBar();
menu = new JMenu("LogViewer");
logLevelMenu = new JMenu("Log Levels");
menubar.add(menu);
menubar.add(logLevelMenu);
connect = new JMenuItem("Connect");
connect.addActionListener(this);
menu.add(connect);
disconnect = new JMenuItem("Disconnect");
disconnect.addActionListener(this);
disconnect.setEnabled(false);
menu.add(disconnect);
menu.addSeparator();
clearLog = new JMenuItem("Clear Log Display");
clearLog.addActionListener(this);
menu.add(clearLog);
menu.addSeparator();
exit = new JMenuItem("Exit");
exit.addActionListener(this);
menu.add(exit);
info = new JCheckBoxMenuItem(LogLevel.INFO);
info.addActionListener(this);
info.setState(true);
logLevelMenu.add(info);
warning = new JCheckBoxMenuItem(LogLevel.WARNING);
warning.addActionListener(this);
warning.setState(true);
logLevelMenu.add(warning);
error = new JCheckBoxMenuItem(LogLevel.ERROR);
error.addActionListener(this);
error.setState(true);
logLevelMenu.add(error);
return (menubar);
}
private JPanel createMainPanel() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
logMsgArea = new JTextArea(12, 80);
logMsgArea.setEditable(false);
JScrollPane tablePane = new JScrollPane(logMsgArea);
p.add(BorderLayout.CENTER, tablePane);
return (p);
}
private JComponent createToolBar() {
JPanel p = new JPanel();
JLabel l;
p.setLayout(new FlowLayout(FlowLayout.LEFT));
l = new JLabel("Log messages for broker at address: ");
p.add(l);
brokerAddress = new JLabel("<none>");
p.add(brokerAddress);
return (p);
}
private JPanel createStatusArea() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
statusTextArea = new JTextArea(3, 80);
statusTextArea.setLineWrap(true);
statusTextArea.setEditable(false);
JScrollPane statusTextPane = new JScrollPane(statusTextArea);
p.add(statusTextPane, BorderLayout.CENTER);
return (p);
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src instanceof JCheckBoxMenuItem) {
JCheckBoxMenuItem cb = (JCheckBoxMenuItem)src;
if (src == info) {
logOn();
} else if (src == warning) {
logOn();
} else if (src == error) {
logOn();
}
} else if (src instanceof JMenuItem) {
JMenuItem mi = (JMenuItem)src;
if (src == exit) {
System.exit(0);
} else if (src == connect) {
showConnectDialog();
} else if (src == disconnect) {
doDisconnect();
} else if (src == clearLog) {
clearLogArea();
}
} else if (src instanceof JButton) {
address = connectDialog.getAddress();
adminUser = connectDialog.getUserName();
adminPasswd = connectDialog.getPassword();
doConnect();
}
}
private void showConnectDialog() {
if (connectDialog == null) {
connectDialog = new MQConnectDialog(f, "Connect to Broker", this);
connectDialog.setAddress((address == null) ?
getDefaultAddress() : address);
connectDialog.setUserName((adminUser == null) ?
getDefaultUserName() : adminUser);
connectDialog.setPassword((adminPasswd == null) ?
getDefaultPassword() : adminPasswd);
}
connectDialog.setLocationRelativeTo(f);
connectDialog.setVisible(true);
}
private static void doExit() {
System.exit(0);
}
private String getDefaultUserName() {
AdminConnectionFactory acf = new AdminConnectionFactory();
String addr;
try {
addr = acf.getProperty(AdminConnectionConfiguration.imqDefaultAdminUsername);
} catch(Exception e) {
addr = null;
}
return (addr);
}
private String getDefaultPassword() {
AdminConnectionFactory acf = new AdminConnectionFactory();
String addr;
try {
addr = acf.getProperty(AdminConnectionConfiguration.imqDefaultAdminPassword);
} catch(Exception e) {
addr = null;
}
return (addr);
}
private String getDefaultAddress() {
/*
AdminConnectionFactory acf = new AdminConnectionFactory();
String addr;
try {
addr = acf.getProperty(AdminConnectionConfiguration.imqAddress);
} catch(Exception e) {
addr = null;
}
return (addr);
*/
return ("localhost:7676");
}
public static void main(String[] args) {
JFrame frame;
MQLogViewer s;
String address = null, adminUser = null, adminPasswd = null,
secondStr = null;
long seconds = 5;
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-b")) {
if (++i >= args.length) {
usage();
}
address = args[i];
} else if (args[i].equals("-u")) {
if (++i >= args.length) {
usage();
}
adminUser = args[i];
} else if (args[i].equals("-p")) {
if (++i >= args.length) {
usage();
}
adminPasswd = args[i];
} else {
usage();
}
}
frame = new JFrame("MQ Log Viewer");
s = new MQLogViewer(frame, address, adminUser, adminPasswd);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
doExit();
}
});
frame.pack();
frame.setVisible(true);
}
public static void usage() {
usage(null);
}
public static void usage(String msg) {
if (msg != null) {
System.err.println(msg);
}
System.err.println("java MQLogViewer"
+ "[-b <host:port>] [-u <admin user name>] [-p <admin password>]");
doExit();
}
}
/*
* @(#)MQConnectDialog.java 1.1 05/06/06
*
* Copyright (c) 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MQConnectDialog extends JDialog
implements ActionListener {
JButton apply, cancel;
JTextField address, username;
JPasswordField password;
private boolean applyHit = false;
private ActionListener applyListener = null;
public MQConnectDialog(Frame parent, String title,
ActionListener applyListener) {
super(parent, title, true);
this.applyListener = applyListener;
initContentPane();
pack();
}
public boolean applyDone() {
return (applyHit);
}
private void initContentPane() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
/*
* Create "work" panel
*/
JPanel workPanel = createWorkPanel();
/*
* Create button panel
*/
JPanel buttonPanel = createButtonPanel();
panel.add(workPanel, "Center");
panel.add(buttonPanel, "South");
getContentPane().add(panel);
}
private JPanel createWorkPanel() {
JPanel workPanel = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JLabel l;
workPanel.setLayout(gridbag);
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(2, 2, 2, 2);
c.ipadx = 0;
c.ipady = 0;
c.weightx = 1.0;
c.gridx = 0;
c.gridy = 0;
l = new JLabel("Address:");
gridbag.setConstraints(l,c);
workPanel.add(l);
c.gridx = 1;
c.gridy = 0;
address = new JTextField(20);
gridbag.setConstraints(address,c);
workPanel.add(address);
c.gridx = 0;
c.gridy = 1;
l = new JLabel("Name:");
gridbag.setConstraints(l,c);
workPanel.add(l);
c.gridx = 1;
c.gridy = 1;
username = new JTextField(20);
gridbag.setConstraints(username, c);
workPanel.add(username);
c.gridx = 0;
c.gridy = 2;
l = new JLabel("Password:");
gridbag.setConstraints(l,c);
workPanel.add(l);
c.gridx = 1;
c.gridy = 2;
password = new JPasswordField(20);
gridbag.setConstraints(password, c);
workPanel.add(password);
return (workPanel);
}
public void setAddress(String s) {
address.setText(s);
}
public String getAddress() {
return (address.getText());
}
public void setUserName(String s) {
username.setText(s);
}
public String getUserName() {
return (username.getText());
}
public void setPassword(String s) {
password.setText(s);
}
public String getPassword() {
return (new String(password.getPassword()));
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
apply = new JButton("Apply");
apply.addActionListener(this);
if (applyListener != null) {
apply.addActionListener(applyListener);
}
buttonPanel.add(apply);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
buttonPanel.add(cancel);
return (buttonPanel);
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == apply) {
applyHit = true;
setVisible(false);
} else if (src == cancel) {
applyHit = false;
setVisible(false);
}
}
}