JMX Archive

Using JConsole to view JMX MBeans of Weblogic Server

1. Set the environment using setWLSEnv.cmd

2. Start JMX Console using the below arguments and connect to the local/remote process.

jconsole -J-Djmx.remote.protocol.provider.pkgs=weblogic.management.remote -J-Dcom.sun.tools.jconsole.mbeans.keyPropertyList=Location,type,Type,j2eeType,name,Name -debug

connect

 

3. Go to the Mbeans tab and view the Mbeans

 

Mbeans

Sample JMX Code to retrieve JDBC Connection Pool Parameter

import java.io.IOException;
import java.util.*;

import javax.management.*;
import javax.management.remote.*;

import javax.naming.Context;

import weblogic.jndi.Environment;
import weblogic.management.*;

public class JDBCConnectionPoolProperties {

	static MBeanServerConnection connection;
	static JMXConnector connector;
	static ObjectName service;

	public static void main(String[] args) {

		try {

			JMXServiceURL serviceURL = new JMXServiceURL("t3", "localhost",
					80,
					"/jndi/weblogic.management.mbeanservers.domainruntime");
			service = new ObjectName(
					"com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");

			Hashtable h = new Hashtable();
			h.put(Context.SECURITY_PRINCIPAL, "weblogic");
			h.put(Context.SECURITY_CREDENTIALS, "weblogic123");
			h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
					"weblogic.management.remote");
			connector = JMXConnectorFactory.connect(serviceURL, h);
			connection = connector.getMBeanServerConnection();

			JDBCConnectionPoolProperties jdbcConnPP = new JDBCConnectionPoolProperties();
			jdbcConnPP.getJDBCRuntime();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getJDBCRuntime() throws Exception {

		ObjectName[] serverRuntime = (ObjectName[]) connection.getAttribute(service,
				"ServerRuntimes");

		int length = (int) serverRuntime.length;

		for (int i = 0; i < length; i++) {
			String name = (String) connection.getAttribute(serverRuntime[i], "Name");
			ObjectName[] jdbcRuntime = (ObjectName[]) connection.getAttribute(new ObjectName("com.bea:Name="+name+",ServerRuntime="+name+",Location="+name+",Type=JDBCServiceRuntime"),"JDBCDataSourceRuntimeMBeans");
			int jdbcLength = (int) jdbcRuntime.length;

			for (int x = 0; x < jdbcLength; x++) {
				System.out.println("\nServer Name   " + name
						+ "   Datasource Name: "
						+ (String) connection.getAttribute(jdbcRuntime[x], "Name"));
				System.out.println("ActiveConnectionsCurrentCount    : "
						+ connection.getAttribute(jdbcRuntime[x],
								"ActiveConnectionsCurrentCount"));
				System.out.println("ActiveConnectionsAverageCount    : "
						+ connection.getAttribute(jdbcRuntime[x],
								"ActiveConnectionsAverageCount"));
				System.out.println("ActiveConnectionsAverageCount    : "
						+ connection.getAttribute(jdbcRuntime[x],
								"ActiveConnectionsAverageCount"));
				System.out.println("ConnectionsTotalCount            : "
						+ connection.getAttribute(jdbcRuntime[x],
								"ConnectionsTotalCount"));
				System.out.println("CurrCapacity                    : "
						+ connection.getAttribute(jdbcRuntime[x], "CurrCapacity"));
				System.out.println("CurrCapacityHighCount            : "
						+ connection.getAttribute(jdbcRuntime[x],
								"CurrCapacityHighCount"));
				System.out.println("HighestNumAvailable              : "
						+ connection.getAttribute(jdbcRuntime[x],
								"HighestNumAvailable"));
				System.out.println("HighestNumAvailable              : "
						+ connection.getAttribute(jdbcRuntime[x],
								"HighestNumAvailable"));
				System.out.println("LeakedConnectionCount            : "
						+ connection.getAttribute(jdbcRuntime[x],
								"LeakedConnectionCount"));
				System.out.println("WaitSecondsHighCount             : "
						+ connection.getAttribute(jdbcRuntime[x],
								"WaitSecondsHighCount"));
				System.out.println("WaitingForConnectionCurrentCount: "
						+ connection.getAttribute(jdbcRuntime[x],
								"WaitingForConnectionCurrentCount"));
				System.out.println("WaitingForConnectionFailureTotal: "
						+ connection.getAttribute(jdbcRuntime[x],
								"WaitingForConnectionFailureTotal"));
				System.out.println("WaitingForConnectionTotal        : "
						+ connection.getAttribute(jdbcRuntime[x],
								"WaitingForConnectionTotal"));
				System.out.println("WaitingForConnectionHighCount    : "
						+ connection.getAttribute(jdbcRuntime[x],
								"WaitingForConnectionHighCount"));
				String poolName = (String) connection.getAttribute(jdbcRuntime[x],
						"Name");
				ObjectName jdbcSystemResource = new ObjectName("com.bea:Name="
						+ poolName + ",Type=JDBCSystemResource");
				ObjectName jdbcDataSourceBean = (ObjectName) getObjectName(
						jdbcSystemResource, "JDBCResource");

				System.out.println("\n Connection Pool Parameters");
				ObjectName jdbcConnectionPoolParams = (ObjectName) getObjectName(
						jdbcDataSourceBean, "JDBCConnectionPoolParams");
				Integer CapacityIncrement = (Integer) getObjectName(
						jdbcConnectionPoolParams, "CapacityIncrement");
				System.out
						.println(" CapacityIncrement                      :"
								+ CapacityIncrement);

				Integer ConnectionCreationRetryFrequencySeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams,
						"ConnectionCreationRetryFrequencySeconds");
				System.out
						.println(" ConnectionCreationRetryFrequencySeconds:"
								+ ConnectionCreationRetryFrequencySeconds);

				Integer ConnectionReserveTimeoutSeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams,
						"ConnectionReserveTimeoutSeconds");
				System.out
						.println(" ConnectionReserveTimeoutSeconds        :"
								+ ConnectionReserveTimeoutSeconds);

				Integer HighestNumWaiters = (Integer) getObjectName(
						jdbcConnectionPoolParams, "HighestNumWaiters");
				System.out.println(" HighestNumWaiters                     :"
						+ HighestNumWaiters);

				Integer InactiveConnectionTimeoutSeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams,
						"InactiveConnectionTimeoutSeconds");
				System.out.println(" InactiveConnectionTimeoutSeconds      :"
						+ CapacityIncrement);

				Integer InitialCapacity = (Integer) getObjectName(
						jdbcConnectionPoolParams, "InitialCapacity");
				System.out.println(" InitialCapacity                       :"
						+ InitialCapacity);

				Integer JDBCXADebugLevel = (Integer) getObjectName(
						jdbcConnectionPoolParams, "JDBCXADebugLevel");
				System.out.println(" JDBCXADebugLevel                      :"
						+ JDBCXADebugLevel);

				Integer LoginDelaySeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams, "LoginDelaySeconds");
				System.out.println(" LoginDelaySeconds                     :"
						+ LoginDelaySeconds);

				Integer MaxCapacity = (Integer) getObjectName(
						jdbcConnectionPoolParams, "MaxCapacity");
				System.out.println(" MaxCapacity                           :"
						+ MaxCapacity);

				Integer ProfileHarvestFrequencySeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams,
						"ProfileHarvestFrequencySeconds");
				System.out.println(" ProfileHarvestFrequencySeconds        :"
						+ ProfileHarvestFrequencySeconds);

				Integer ProfileType = (Integer) getObjectName(
						jdbcConnectionPoolParams, "ProfileType");
				System.out.println(" ProfileType                           :"
						+ ProfileType);

				Integer SecondsToTrustAnIdlePoolConnection = (Integer) getObjectName(
						jdbcConnectionPoolParams,
						"SecondsToTrustAnIdlePoolConnection");
				System.out.println(" SecondsToTrustAnIdlePoolConnection    :"
						+ SecondsToTrustAnIdlePoolConnection);

				Integer ShrinkFrequencySeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams, "ShrinkFrequencySeconds");
				System.out.println(" ShrinkFrequencySeconds                :"
						+ ShrinkFrequencySeconds);

				Integer StatementTimeout = (Integer) getObjectName(
						jdbcConnectionPoolParams, "StatementTimeout");
				System.out.println(" StatementTimeout                      :"
						+ StatementTimeout);

				Integer TestFrequencySeconds = (Integer) getObjectName(
						jdbcConnectionPoolParams, "TestFrequencySeconds");
				System.out.println(" TestFrequencySeconds                  :"
						+ TestFrequencySeconds);

				String TestTableName = (String) getObjectName(
						jdbcConnectionPoolParams, "TestTableName");
				System.out.println(" TestTableName                         :"
						+ TestTableName);

				String StatementCacheType = (String) getObjectName(
						jdbcConnectionPoolParams, "StatementCacheType");
				System.out.println(" StatementCacheType                    :"
						+ StatementCacheType);

				String InitSql = (String) getObjectName(
						jdbcConnectionPoolParams, "InitSql");
				System.out.println(" InitSql                               :"
						+ InitSql);

				Boolean CredentialMappingEnabled = (Boolean) getObjectName(
						jdbcConnectionPoolParams, "CredentialMappingEnabled");
				System.out.println(" CredentialMappingEnabled              :"
						+ CredentialMappingEnabled);

				Boolean IdentityBasedConnectionPoolingEnabled = (Boolean) getObjectName(
						jdbcConnectionPoolParams,
						"IdentityBasedConnectionPoolingEnabled");
				System.out.println(" IdentityBasedConnectionPoolingEnabled :"
						+ IdentityBasedConnectionPoolingEnabled);

				Boolean IgnoreInUseConnectionsEnabled = (Boolean) getObjectName(
						jdbcConnectionPoolParams,
						"IgnoreInUseConnectionsEnabled");
				System.out.println(" IgnoreInUseConnectionsEnabled         :"
						+ IgnoreInUseConnectionsEnabled);

				Boolean PinnedToThread = (Boolean) getObjectName(
						jdbcConnectionPoolParams, "PinnedToThread");
				System.out.println(" PinnedToThread                        :"
						+ PinnedToThread);

				Boolean RemoveInfectedConnections = (Boolean) getObjectName(
						jdbcConnectionPoolParams, "RemoveInfectedConnections");
				System.out.println(" RemoveInfectedConnections             :"
						+ RemoveInfectedConnections);

				ObjectName jdbcDriverParams = (ObjectName) getObjectName(
						jdbcDataSourceBean, "JDBCDriverParams");
				ObjectName jdbcProperties = (ObjectName) getObjectName(
						jdbcDriverParams, "Properties");
				ObjectName[] jdbcPropertyBeans = (ObjectName[]) getObjectName(
						jdbcProperties, "Properties");

				for (int j = 0; j < jdbcPropertyBeans.length; j++) {
					ObjectName jdbcPropertyBean = null;
					jdbcPropertyBean = jdbcPropertyBeans[j];
					String jdbcPropertyName = (String) getObjectName(
							jdbcPropertyBean, "Name");
					String jdbcPropertyValue = (String) getObjectName(
							jdbcPropertyBean, "Value");
					System.out.println("\n Name & Value  "+ jdbcPropertyName + " " + jdbcPropertyValue);
				}

			}
		}
	}

	private Object getObjectName(ObjectName objectName, String attributeName)
			throws AttributeNotFoundException, InstanceNotFoundException,
			MBeanException, ReflectionException, IOException {
		return connection.getAttribute(objectName, attributeName);
	}
}

OUTPUT

Server Name AdminServer Datasource Name: PegaRULES
ActiveConnectionsCurrentCount : 0
ActiveConnectionsAverageCount : 0
ActiveConnectionsAverageCount : 0
ConnectionsTotalCount : 10
CurrCapacity : 2
CurrCapacityHighCount : 4
HighestNumAvailable : 5
HighestNumAvailable : 5
LeakedConnectionCount : 0
WaitSecondsHighCount : 0
WaitingForConnectionCurrentCount: 0
WaitingForConnectionFailureTotal: 0
WaitingForConnectionTotal : 0
WaitingForConnectionHighCount : 0

Connection Pool Parameters
CapacityIncrement :1
ConnectionCreationRetryFrequencySeconds:0
ConnectionReserveTimeoutSeconds :10
HighestNumWaiters :2147483647
InactiveConnectionTimeoutSeconds :1
InitialCapacity :1
JDBCXADebugLevel :10
LoginDelaySeconds :0
MaxCapacity :15
ProfileHarvestFrequencySeconds :300
ProfileType :0
SecondsToTrustAnIdlePoolConnection :10
ShrinkFrequencySeconds :900
StatementTimeout :-1
TestFrequencySeconds :120
TestTableName :SQL SELECT 1 FROM DUAL
StatementCacheType :LRU
InitSql :null
CredentialMappingEnabled :false
IdentityBasedConnectionPoolingEnabled :false
IgnoreInUseConnectionsEnabled :true
PinnedToThread :false
RemoveInfectedConnections :true

Name & Value user SYSTEM

Automating application deployment on Weblogic Server.

In this article we will demonstrate three ways of deployment and undeployment on Weblogic Server

1. Using WLST
2. Using JMX
3. Using build script.
Application Deployment using WLST


connect(‘weblogic’,’weblogic’,’t3://localhost:7001′)
edit()
startEdit()
deploy(‘CookieApp’,’D:/Replications/CookieApp’,targets=’AdminServer’)
save()
activate()
exit()

Application Undeployment using WLST

connect(‘weblogic’,’weblogic’,’t3://localhost:7001′)
edit()
startEdit()
undeploy(‘CookieApp’)
save()
activate()
exit()

Application Deployment using JMX


import java.io.*;
import weblogic.deploy.api.tools.*;
import weblogic.deploy.api.spi .*;
import weblogic.deploy.api.spi.DeploymentOptions;
import javax.enterprise.deploy.spi.TargetModuleID;
import javax.enterprise.deploy.spi.status.ProgressObject;
import javax.enterprise.deploy.spi.status.DeploymentStatus;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.spi.Target;
public class DeployUsingJMX
{
public static void main(String ar[]) throws Exception
{
String aLocation=”D:/Replications/CookieApp”;
String aName=”CookieApp”;
WebLogicDeploymentManager deployManager=SessionHelper.getRemoteDeploymentManager( “t3″,”localhost”,”7001″,”weblogic”,”weblogic”);
System.out.println(“\n\t WebLogicDeploymentManager: “+deployManager);
DeploymentOptions options = new DeploymentOptions();
System.out.println(“\n\t DeploymentOptions: “+options);
options.setName(aName);
Target targets[]=deployManager.getTargets();
int i=0;
for (i=0;i
{
System.out.println(“\n\t “+targets[i]);
}
Target deployTargets[]=new Target[1];
deployTargets[0]=targets[0];
System.out.println(“For test purpose we are deploying on Admin Server”+targets[0]);
ProgressObject processStatus=deployManager.distribute(deployTargets, new File(aLocation), null,options);
DeploymentStatus deploymentStatus=processStatus.getDeploymentStatus() ;
System.out.println(“deploymentStatus.getMessage(): “+deploymentStatus.getMessage() );
TargetModuleID[] targetModuleIDs=deployManager.getAvailableModules(ModuleType.WAR, deployTargets);
if(targetModuleIDs != null)
{
System.out.println(“\n\t targetModuleIDs [] = “+targetModuleIDs);
for (int j=0;j
{
System.out.println(“\n\t “+targetModuleIDs[j]);
deployManager.start(targetModuleIDs);
}
}
}
}

 

Application Un-Deployment using JMX

import java.io.*;
import weblogic.deploy.api.tools.*;
import weblogic.deploy.api.spi .*;
import weblogic.deploy.api.spi.DeploymentOptions;
import javax.enterprise.deploy.spi.TargetModuleID;
import javax.enterprise.deploy.spi.status.ProgressObject;
import javax.enterprise.deploy.spi.status.DeploymentStatus;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.spi.Target;
public class UndeployUsingJMX
{
public static void main(String ar[]) throws Exception
{
WebLogicDeploymentManager deployManager=SessionHelper.getRemoteDeploymentManager(“t3″,”localhost”,”7001″,”weblogic”,”weblogic”);
System.out.println(“\n\t WebLogicDeploymentManager: “+deployManager);
DeploymentOptions options = new DeploymentOptions();
System.out.println(“\n\t DeploymentOptions: “+options);
TargetModuleID[] targetModuleIDs=deployManager.getAvailableModules(ModuleType.WAR, deployManager.getTargets());
if(targetModuleIDs != null)
{
System.out.println(“targetModuleIDs length: “+targetModuleIDs.length);
for(int i=0;i
{
System.out.println(“\n undeploying targetModuleIDs[“+i+”]: “+targetModuleIDs[i]);
ProgressObject processStatus=deployManager.undeploy(new TargetModuleID[]{targetModuleIDs[i]});
DeploymentStatus deploymentStatus=processStatus.getDeploymentStatus() ;
System.out.println(“deploymentStatus.getMessage(): “+deploymentStatus.getMessage() );
}
}
}
}

Application Deployment and Undeployment using ant wldeploy task.

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

<project name=”DeploymentBuild” default=”all” basedir=”.”>

<property name=”wl.home” value=”C:/bea103/wlserver_10.3″ />
<property name=”deploy.name” value=”CookieApp” />
<property name=”deploy.source” value=”D:/Replications/CookieApp” />
<property name=”wls.username” value=”weblogic” />
<property name=”wls.password” value=”weblogic” />
<property name=”wls.hostname” value=”localhost” />
<property name=”wls.port” value=”7001″ />
<property name=”deploy.target” value=”AdminServer” />

<path id=”wlappc.classpath”>
<fileset dir=”${wl.home}/server/lib”>
<include name=”*.jar”/>
</fileset>
</path>

<taskdef name=”wldeploy” classpathref=”wlappc.classpath” classname=”weblogic.ant.taskdefs.management.WLDeploy”/>

<target name=”deploy”>
<wldeploy action=”deploy”
name=”${deploy.name}”
source=”${deploy.source}”
user=”${wls.username}”
nostage=”true”
password=”${wls.password}”
verbose=”true”
adminurl=”t3://${wls.hostname}:${wls.port}”
targets=”${deploy.target}” />
</target>

<target name=”undeploy”>
<wldeploy action=”undeploy”
name=”${deploy.name}”
user=”${wls.username}”
password=”${wls.password}”
verbose=”true”
adminurl=”t3://${wls.hostname}:${wls.port}”
targets=”${deploy.target}” />
</target>

</project><?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

<project name=”DeploymentBuild” default=”all” basedir=”.”>

<property name=”wl.home” value=”C:/bea103/wlserver_10.3″ />
<property name=”deploy.name” value=”CookieApp” />
<property name=”deploy.source” value=”D:/Replications/CookieApp” />
<property name=”wls.username” value=”weblogic” />
<property name=”wls.password” value=”weblogic” />
<property name=”wls.hostname” value=”localhost” />
<property name=”wls.port” value=”7001″ />
<property name=”deploy.target” value=”AdminServer” />

<path id=”wlappc.classpath”>
<fileset dir=”${wl.home}/server/lib”>
<include name=”*.jar”/>
</fileset>
</path>

<taskdef name=”wldeploy” classpathref=”wlappc.classpath” classname=”weblogic.ant.taskdefs.management.WLDeploy”/>

<target name=”deploy”>
<wldeploy action=”deploy”
name=”${deploy.name}”
source=”${deploy.source}”
user=”${wls.username}”
nostage=”true”
password=”${wls.password}”
verbose=”true”
adminurl=”t3://${wls.hostname}:${wls.port}”
targets=”${deploy.target}” />
</target>

<target name=”undeploy”>
<wldeploy action=”undeploy”
name=”${deploy.name}”
user=”${wls.username}”
password=”${wls.password}”
verbose=”true”
adminurl=”t3://${wls.hostname}:${wls.port}”
targets=”${deploy.target}” />
</target>

</project>

 

References:-

http://download.oracle.com/docs/cd/E13222_01/wls/docs92/config_scripting/reference.html

JMX Policy Editor to modify Deployer role

The below post describes how we can modify the default policy settings for the Deployer role users.

By default the user with Deployer role cannot start / stop the JDBC Data Source. There could be situations where you would like to provide the permissions to do so.

While trying to start/ stop a JDBC Data Source we might encounter the below errors.

Access not allowed for subject: principals=[deployer, Deployers], on Resource weblogic.management.runtime.JDBCDataSourceRuntimeMBean Operation: invoke , Target: isOperationAllowed

We can modify the default behavior by using the JMX Policy Editor to change the default JMX Policies.

Pre-requisites :

  1. An User with Deployer role privileges.

Steps to modify the default JMX Policy Editor.

1.  Enable the feature to modify the JMX Policy Editor.

a . Log into the Administration, navigate to the current security realm.  MyRealm –> Configuration Tab.

b. Enable the “Use Authorization Providers to Protect JMX Access” option.

NOTE: Re-start the Admin Server so that the changes can be consumed.

2. Select the MBean operations whose permissions need to be modified.

a.  Login into the admin console, navigate to the Security Realms –> myrealm –>  Roles and Policies Tab.

b. Click on the Realm Policies sub tab, click on the JMX Policy Editor.


c. Global Scope is enabled by default , click Next.

d. From the list of Mbeans, expand weblogic.management.runtime type Mbeans.

e. Select the ‘JDBCDataSourceRuntimeMbean’  –>  Click Next.

f.  Select the “Operations: Permission to Invoke” which define which operations permissions can be modified.

Alternatively you can provide a more granular level control on the individual operations that needs to be controlled.

3. Edit the JMX security policies.

a.  Click on  CreatePolicy  –> Add conditions.

b.  From the predicate list, you can select an User or  Groups or Roles.

c. Click Save to complete the JMX Security Policy.

4. Testing the setup.

a. Login into the Admin Console with the deployer user and navigate to the DataSource.

b. Go to the Control subtab and now you can start/ stop the datasource.

NOTE: Similarly you can modify the access permissions of different Mbeans.

References:

http://download.oracle.com/docs/cd/E13222_01/wls/docs100/ConsoleHelp/taskhelp/security/DefinePoliciesforMBeans.html

Cheers,

Wonders Team. 🙂


List Users and Groups in Weblogic using JMX

There are times when an Application Needs to interact with the Weblogic Server Embedded LDAP Server and Add/Modify/List users or groups. Weblogic Server provides UserReaderMBean, UserRemoverMBean, GroupReaderMBean, GroupRemoverMBean for this purpose.

Below you will find a sample to list users and groups present in the Embedded Ldap Server. This program will give you an idea which you can further develop on.

import javax.naming.*;
import javax.management.MBeanInfo;
import weblogic.jndi.Environment;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.security.providers.authentication.DefaultAuthenticatorMBean;
import weblogic.management.security.authentication.UserReaderMBean;
import weblogic.management.security.authentication.GroupReaderMBean;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.tools.Info;
import weblogic.management.Helper;
import weblogic.management.security.authentication.*;

public class ListUsersAndGroups
{
public static void main(String[] args)
{

MBeanHome home = null;
try
{

Environment env = new Environment();
env.setProviderUrl(“t3://localhost:7001?);
env.setSecurityPrincipal(“weblogic”);
env.setSecurityCredentials(“weblogic”);
Context ctx = env.getInitialContext();

home = (MBeanHome)ctx.lookup(“weblogic.management.adminhome”);

weblogic.management.security.RealmMBean rmBean = home.getActiveDomain().getSecurityConfiguration().getDefaultRealm();

AuthenticationProviderMBean[] authenticationBeans = rmBean.getAuthenticationProviders();
DefaultAuthenticatorMBean defaultAuthenticationMBean = (DefaultAuthenticatorMBean)authenticationBeans[0];
UserReaderMBean userReaderMBean = (UserReaderMBean)defaultAuthenticationMBean;
GroupReaderMBean groupReaderMBean = (GroupReaderMBean)defaultAuthenticationMBean;

String userCurName = userReaderMBean.listUsers(“*”, 100);

while (userReaderMBean.haveCurrent(userCurName) )
{
String user = userReaderMBean.getCurrentName(userCurName);
System.out.println(“\n User: ” + user);
userReaderMBean.advance(userCurName);
}

String cursorName = groupReaderMBean.listGroups(“*”, 100);
while (groupReaderMBean.haveCurrent(cursorName) )
{

String group = groupReaderMBean.getCurrentName(cursorName);
System.out.println(“\n Group: ” + group);
groupReaderMBean.advance(cursorName);
}

}
catch (Exception e)
{
e.printStackTrace();
}
}
}

JMS Resources using JMX

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;

import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.InitialContext;

import weblogic.j2ee.descriptor.wl.JMSBean;
import weblogic.j2ee.descriptor.wl.JMSConnectionFactoryBean;
import weblogic.j2ee.descriptor.wl.QueueBean;
import weblogic.jms.extensions.JMSModuleHelper;
import weblogic.management.configuration.JMSSystemResourceMBean;

public class JMSResource {

private static MBeanServerConnection connection;
private static JMXConnector connector;
private static ObjectName service;

static {

try {

System.out.println(“…”);
service = new ObjectName(
“com.bea:Name=RuntimeService,” +
“Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean”);
} catch (MalformedObjectNameException e) {
throw new AssertionError(e.getMessage());
}
}

public static void initConnection(String hostname, String portString,
String username, String password) throws IOException,
MalformedURLException {
String protocol = “t3”;
Integer portInteger = Integer.valueOf(portString);
int port = portInteger.intValue();
String jndiroot = “/jndi/”;
String mserver = “weblogic.management.mbeanservers.runtime”;
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port,
jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
“weblogic.management.remote”);
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
}

public static ObjectName[] getJMSServers() throws Exception {
ObjectName serverRuntime = (ObjectName) connection.getAttribute(
service, “ServerRuntime”);
ObjectName jmsRuntime = (ObjectName) connection.getAttribute(
serverRuntime, “JMSRuntime”);
ObjectName[] jmsServers = (ObjectName[]) connection.getAttribute(
jmsRuntime, “JMSServers”);
return jmsServers;
}

public static void testMethod() {

try {

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.WLInitialContextFactory”);
env.put(Context.PROVIDER_URL, “t3://localhost:7001”);
env.put(Context.SECURITY_PRINCIPAL, “weblogic”);
env.put(Context.SECURITY_CREDENTIALS, “weblogic”);
Context ctx = new InitialContext(env);

ObjectName[] serverRT = getJMSServers();
int length = (int) serverRT.length;
System.out.println(“length:::” + length);

for (int i = 0; i < length; i++) {

System.out.println(“i:::” + i);

ObjectName[] queues = (ObjectName[]) connection.getAttribute(
serverRT[i], “Destinations”);

String jmsServerName = (String) connection.getAttribute(
serverRT[i], “Name”);
System.out.println(“JMS Server name:” + jmsServerName);

int queueCount = (int) queues.length;

for (int k = 0; k < queueCount; k++) {

String queueNameWithModule = (String) connection
.getAttribute(queues[k], “Name”);

Long messagesCurrentCount = (Long) connection.getAttribute(
queues[k], “MessagesCurrentCount”);
System.out.println(“messagesCurrentCount”
+ messagesCurrentCount);

String moduleName = queueNameWithModule.substring(0,
queueNameWithModule.indexOf(“!”));
System.out.println(“JMS module Name:” + moduleName);
String resourceName = moduleName;
String queueName = queueNameWithModule
.substring(queueNameWithModule.indexOf(“!”) + 1);
System.out.println(“queueName” + queueName);

JMSSystemResourceMBean jmsSR = JMSModuleHelper
.findJMSSystemResource(ctx, resourceName);
JMSBean jmsBean = jmsSR.getJMSResource();
JMSConnectionFactoryBean[] connectionFactoryBean = jmsBean
.getConnectionFactories();

int length1 = (int) connectionFactoryBean.length;

for (int j = 0; j < length1; j++) {

JMSConnectionFactoryBean jmsFactory = connectionFactoryBean[j];
System.out.println(“jmsFactory.getJNDIName()”
+ jmsFactory.getJNDIName());

}
QueueBean[] queueBean = jmsBean.getQueues();
length = (int) queueBean.length;

for (int m = 0; m < length; m++) {

QueueBean queue = queueBean[m];

if (queueName != null
&& queueName.equals(queue.getName())) {
System.out.println(“queue.getJNDIName()”
+ queue.getJNDIName());
}
}

}
break;
}
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String[] args) throws Exception {

String hostname = “localhost”;
String portString = “7001”;
String username = “weblogic”;
String password = “weblogic”;
System.out.println(“initializing conenction….”);
initConnection(hostname, portString, username, password);
JMSResource.testMethod();
connector.close();
}

}