30 June 2008

Application MBean NotificationListeners

And another example from an OTN question.

http://forums.oracle.com/forums/thread.jspa?messageID=2619654&tstart=0#2619654

I'm using OC4J 10.1.3 and I see, in Oracle MBean browser, that a mbean is created and registered each time an EAR is deployed :

"oc4j:j2eeType=J2EEApplication,name=,J2EEServer=standalone"

I tried to registerer to notifications of this mbean (j2ee.state.starting and j2ee.state.stopping) using web console. It works, I can see notifications in web console.

Now, I would to like to registered to these notifications in my application. I don't find sample in oc4j documentation on how doing this.

Has anybody already use this functionality ?


Update 03-July-2008: I posted an example of this on the OC4J How-To page. The zip file is available here:
http://www.oracle.com/technology/tech/java/oc4j/10130/how_to/application-jmx-listener.zip.

The short answer is that you can register for notifications from any of the OC4J MBeans using the standard JMX API -- no worries at all.

However there are a couple of tricks to keep in mind when working with OC4J.

Trick 1 : from within OC4J, an application has restricted access to the OC4J MBean set. We provide applications with a proxy to the MBeanServer that permits access to only the MBeans that the application itselt registers. Or in other words, it prohibits applications from seeing and using the OC4J MBeans when using the MBeanServerFactory.getMBeanServer() call from within the application code. There are basically two ways to deal with this.

I. You can disable the security aspect of the proxy. This can be done by setting the Java System property "oc4j.jmx.security.proxy.off" when OC4J is launched. Beware however that this applies to the entire container, so any deployed applications will have access to the OC4J MBeans. Beware.

II. You can establish what amounts to a loopback remote connection using the JMX Remote API. When doing this, you can authenticate yourself as a user from within the oc4j-app-administrators role, and thus the proxy you receive does not have any restrictions placed on it. The downside to doing this is that the connection must be constructed using the URL and username/password of the respective user you want to connect as. Therefore you are dealing with ports and password visibility issues.

With that understood, lets assume that you now have access to the OC4J MBeans using JMXConnector.

A JMX listener is simply a class that implements the javax.management.NotificationListener interface. You create a class that implements this interface, and then you register your interest with the MBeanServer for receiving Notifications that are emitted from a specific MBean using its addNotificationListener method.

Trick 2: in order to receive Notifications from an MBean, the connection you used to register with the MBeanServer must be maintained. If the connection closes, the link between the MBean and your Listener is gone. Therefore when you are designing your application, you need to use a model that allows the connection to be maintained across requests, but at the same time, you need to do it such that the connections do not place an undue resource tax on the operation of the server. You probably don't want to store a JMXConnector in each HttpSession of each client for example.

As a demonstration of these tricks, I have pulled together a demo application to show what an example may look like.

Points of Interest:

JMXListenerBean -- this JavaBean implements the NotificationListener interface. When Notifications are received they are stored in a List maintained by the JavaBean. This enables the Notifications to be retrieved and rendered in a client of some form.

GlobalListenerMap -- the application uses one global class -- GlobalListenerMap -- to create and maintain the connection to the MBeanServer. This class is also where the individual MBean listeners are registered and stored for each client. The class is created and placed in the ServletContext by a ServletContextListener; it is also closed when the ServletContext is destroyed, where it closes its JMXConnector. When a new browser client asks to register a listener with a specific MBean, a servlet creates the actual listening class and submits it to the GlobalListenerMap to register with the MBeanServer. The GlobalListenerMap then stores the listener in List, which is then stored in a Map using the client sessionId as the key.

ServletContextListener -- a ServletContextListener is used to manage the GlobalListenerMap. When the ServletContext is created, it creates an instance of the GlobalListenerMap and places it in the ServletContext to be shared by all the artifacts of the application. When the ServletContext is destroyed, it closes down the GlobalListenerMap allowing it to close its JMXConnector. This class also implements the HttpSessionListener interface, so that as a client session ends/is invalidated, any listeners the client had previously registered are removed from the GlobalListenerMap.

Front End -- a simple front end to allow a client to register interest with an MBean is provided, and then view the notifications.

JMXListenerBean.java
package sab.demo.jmx.listener;

import java.text.DateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.management.*;

/**
* This JavaBean acts as a JMX NotificationListener. It
* gets populated with an MBean name and it can then be registered
* with a given MBeanServer. This is quick and dirty, it does no
* validate of the MBean name, etc.
*
* Any notifications this listener receives are stored in both the messages
* and notifications lists -- these can then be used on the client side as
* desired.
*
*/

public class JMXListenerBean implements NotificationListener {

Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
ArrayList<String> messages = new ArrayList<String>();
ArrayList<Notification>notifications = new ArrayList<Notification>();

private final Date created = new Date();
private String mBean = null;
private final DateFormat DF = DateFormat.getDateTimeInstance();

public JMXListenerBean() {
logger.info("JMXListenerBean: constructor");
}

/**
* Register this listener with the given MBeanServer.
*
@param mbs - MBeanServerConnection
* @throws Exception
*/
public void register(MBeanServerConnection mbs) throws Exception{
logger.info("registering mbean:" + mBean);
if("".equalsIgnoreCase(mBean) || mBean == null) {
throw new Exception("MBean name must be set before calling register");
}

try {
ObjectName on = new ObjectName(mBean);
mbs.addNotificationListener(on, this, null, null);
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}

public void unregister(MBeanServerConnection mbs) throws Exception{
logger.info("unregistering mbean:" + mBean);
if("".equalsIgnoreCase(mBean) || mBean == null) {
throw new Exception("MBean name must be set before calling register");
}

try {
ObjectName on = new ObjectName(mBean);
mbs.removeNotificationListener(on, this);
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}


/**
* This is where the notifications are delivered and handled.
*
@param notification
* @param handback
*/
public void handleNotification(Notification notification,
Object handback) {
logger.info("handleNotification");
// Add the notification to the list
notifications.add(notification);
// Make a string from the notification
messages.add(
String.format("[%s]\t%s\t%s",
DF.format(new Date(notification.getTimeStamp())),
notification.getType(),
notification.getMessage()));
}

public void setMBean(String mbean) {
this.mBean = mbean;
}

public String getMBean() {
return mBean;
}

/**
* Get the list of messages.
*
@return List of messages as Strings
*/
public ArrayList<String> getMessages() {
return messages;
}

/**
* Get the list of raw notifications
*
@return List of notifications
*/
public ArrayList<Notification> getNotifications() {
return notifications;
}

@Override
public String toString() {
return mBean;
}
}

GlobalListenerMap.java

package sab.demo.jmx.map;

import java.sql.Date;
import java.text.DateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.management.*;
import javax.management.remote.*;
import sab.demo.jmx.listener.JMXListenerBean;

/**
* This class acts as a manager for JMXListenerBeans, and the OC4J MBeanServer
* that they are registered with. It enables an application to signal interest
* for notifications from an MBean, whereupon it handles the registration of the
* listener with the MBean. It maintains the JMXConnection while the class is
* in use, providing a route for the MBeanServer to get the notifications from
* the MBean to the listener.
*
*/

public class GlobalListenerMap {

private Date created = null;

private HashMap<String, List<JMXListenerBean>> sessionListenerList = new HashMap<String, List<JMXListenerBean>>();
private JMXConnector jmxConnector= null;
private Object MUTEX = new Object();
private boolean eagerCloseConnection = true;

private static final String URL = "service:jmx:rmi://localhost:23791";
private static final String USERNAME = "oc4jadmin";
private static final String PASSWORD = "welcome1";
private final Logger logger = Logger.getLogger(this.getClass().getName());

public GlobalListenerMap() {
this(true);
}

public GlobalListenerMap(boolean eagerCloseConnection) {
this.eagerCloseConnection = eagerCloseConnection;
created = new Date(System.currentTimeMillis());
}

public synchronized void addListenerForSession(String sessionId, String mbeanName) throws Exception {
JMXListenerBean listener = new JMXListenerBean();
listener.setMBean(mbeanName);
addListenerForSession(sessionId, listener);
}

public synchronized void addListenerForSession(String sessionId, JMXListenerBean listener) throws Exception {
List<JMXListenerBean> listeners = sessionListenerList.get(sessionId);
if(listeners == null) {
listeners = new ArrayList<JMXListenerBean>();
}
if(jmxConnector == null) {
jmxConnector = getJMXConnector();
}
MBeanServerConnection mbs = jmxConnector.getMBeanServerConnection();
listener.register(mbs);
listeners.add(listener);
sessionListenerList.put(sessionId, listeners);
}

public List<JMXListenerBean>getListenerListForSession(String sessionId) {
return sessionListenerList.get(sessionId);
}

public synchronized void removeListenerListForSession(String sessionId) {
List<JMXListenerBean> listeners = sessionListenerList.get(sessionId);
// Unregister any listeners this session had established
try {
for(JMXListenerBean listener: listeners) {
listener.unregister(jmxConnector.getMBeanServerConnection());
}
} catch(Exception e) {
// TODO: handle unregister errors gracefully, ignore for now
}

// Now remove the session from the list
sessionListenerList.remove(sessionId);

// Eaglerly close the connection if configured to do so
if(eagerCloseConnection && sessionListenerList.size()==0) {
try {
close(true);
} catch (Exception ex) {
// Ignore the still registered error
}
}
}

/**
* Performs a shutdown on the listener map, will throw an exception if there
* are listeners still registered.
*
@throws Exception
*/
public void shutdown() throws Exception {
// care
close(true);
}

public void shutdownDontCare() throws Exception {
// don't care
close(false);
}

/**
* Close the GlobalMapListener down.
*
@param care -- whether to care if there are still registered listeners.
* @throws Exception
*/
private synchronized void close(boolean care) throws Exception {
if(care) {
if (sessionListenerList.size() != 0) {
throw new Exception("Can't close myself as listeners are still registered");
}
}
sessionListenerList.clear();
if (jmxConnector != null) {
jmxConnector.close();
jmxConnector = null;
}
}

/**
* Get a JMXConnector using the hardcoded URL, USERNAME, PASSWORD
*
@return
* @throws Exception
*/
private JMXConnector getJMXConnector() throws Exception {
return getJMXConnector(URL, USERNAME, PASSWORD);
}

/**
* Get a JMXConnector using the supplied parameters.
*
@param url
* @param username
* @param password
* @return JMXConnector
* @throws Exception
*/
private JMXConnector getJMXConnector(String url, String username,
String password) throws Exception {
JMXConnector jmxcon = null;

// If not, create one and store it for future use.
JMXServiceURL jmxurl = new JMXServiceURL(url);
Hashtable credentials = new Hashtable();
credentials.put("login", username);
credentials.put("password", password);

// Properties required to use the OC4J ORMI protocol
Hashtable env = new Hashtable();
env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "oracle.oc4j.admin.jmx.remote");
env.put(JMXConnector.CREDENTIALS, credentials);

// Get a connection
jmxcon = JMXConnectorFactory.newJMXConnector(jmxurl, env);
jmxcon.connect();
return jmxcon;
}

/**
* Just print out some debug messages
*/

public void debug() {
logger.fine("GlobalListenerMap: created " +
DateFormat.getDateTimeInstance().format(created));
logger.fine("Sessions in use: " + sessionListenerList.keySet().size());
for(String sessionid: sessionListenerList.keySet()) {
logger.fine("[" + sessionid + "]");
for(JMXListenerBean listener: sessionListenerList.get(sessionid)) {
logger.fine(listener.getMBean() + ", has received [" +
listener.getNotifications().size() +
"] notifications" );
}
}
}

/**
* Quick and dirty query to get the list of mbean names for the deployed
* applications.
*
@return Set of Stringified ObjectNames
*/
public Set<String> getJ2EEApplicationNameList() {
logger.info("entering");
SortedSet<String> appnames = new TreeSet<String>();
Set<ObjectName>mbeans = null;
try {
if(jmxConnector == null) {
jmxConnector = getJMXConnector();
}
ObjectName query = new ObjectName("*:j2eeType=J2EEApplication,*");
mbeans = (Set<ObjectName>)
jmxConnector.getMBeanServerConnection().queryNames(query, null);
for(ObjectName mbean: mbeans) {
appnames.add(mbean.getCanonicalName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return appnames;
}

}
ServletContextListener

package sab.demo.jmx.listener;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import sab.demo.jmx.map.GlobalListenerMap;


public class ServletContextListener implements javax.servlet.ServletContextListener,
HttpSessionListener {
private static final String GLM_KEY = "GlobalListenerMap";
private ServletContext context = null;
private HttpSession session = null;
private final Logger logger = Logger.getLogger(this.getClass().getName());

/**
* Create a new GlobalListenerMap and put it in the context for use by
* the application artifacts.
*
@param event
*/
public void contextInitialized(ServletContextEvent event) {
logger.fine("contextInitialized");
context = event.getServletContext();
GlobalListenerMap glm = new GlobalListenerMap();
context.setAttribute(GLM_KEY, glm);

}

/**
* When the application is being shutdown, close the GlobalListenerMap so
* that the JMXConnector is closed.
*
@param event
*/
public void contextDestroyed(ServletContextEvent event) {
context = event.getServletContext();
logger.info("Closing GlobalListenerMap");
GlobalListenerMap glm = (GlobalListenerMap)context.getAttribute(GLM_KEY);
try {
if(glm!=null) {
glm.shutdownDontCare();
}
} catch(Exception e) {
e.printStackTrace();
}
}

/**
* When a new session is created ... don't really do anything.
*
@param event
*/
public void sessionCreated(HttpSessionEvent event) {
session = event.getSession();
ServletContext context = event.getSession().getServletContext();
GlobalListenerMap glm = (GlobalListenerMap)context.getAttribute(GLM_KEY);
// Could proactively create a session list here if we wanted
if(glm == null && logger.isLoggable(Level.SEVERE)) {
logger.severe("GlobalListenerMap in ServletContext is null");
}

}

/**
* When a specific user session is closed, remove any listeners that may
* have been registered by them from the GlobalListenerMap.
*
@param event
*/
public void sessionDestroyed(HttpSessionEvent event) {
session = event.getSession();
logger.info("Removing listeners for session: " + session.getId());
// Clean up ..
ServletContext context = event.getSession().getServletContext();
GlobalListenerMap glm = (GlobalListenerMap)context.getAttribute(GLM_KEY);
if(glm!=null) {
glm.removeListenerListForSession(session.getId());
}
}
}
RegistrationServlet

package sab.demo.jmx.web;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.HashSet;
import java.util.Hashtable;


import java.util.List;
import java.util.logging.Logger;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import javax.servlet.*;
import javax.servlet.http.*;

import sab.demo.jmx.map.GlobalListenerMap;
import sab.demo.jmx.listener.JMXListenerBean;

public class RegistrationServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

private final Logger logger = Logger.getLogger(this.getClass().getName());
private ServletConfig config = null;

public void init(ServletConfig config) throws ServletException {
super.init(config);
this.config = config;
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);

try {
// Get the MBean name parameter
String mbean = request.getParameter("mbean");
if(mbean==null || "".equalsIgnoreCase(mbean)) {
throw new ServletException("MBean parameter was not provided.");
}
logger.info("Request for registering MBean: " + mbean);

ServletContext ctx = config.getServletContext();
GlobalListenerMap glm = (GlobalListenerMap) ctx.getAttribute("GlobalListenerMap");

// Create a new listener bean and add it to the global list
JMXListenerBean listener = new JMXListenerBean();
listener.setMBean(mbean);
glm.addListenerForSession(request.getSession().getId(), listener);

// Tack on some debug information to the output
if(request.getParameterMap().containsKey("debug")) {
glm.debug();
}
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("javax.servlet.jsp.jspException", ex);
request.getRequestDispatcher("error.jsp").forward(request, response);
} finally {
}

request.getRequestDispatcher("listnotifications.jsp").forward(request, response);
}

public void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
listnotifications.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="sab.demo.jmx.listener.*"%>
<%@ page import="sab.demo.jmx.map.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.management.*"%>
<%@ page import="java.text.DateFormat"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>Index</title>
<STYLE TYPE="text/css">
td, body{font-family: Arial; font-size: 10pt;}
span.listener { color: #FF1111; font-weight: bold;}
td.state { text-transform: uppercase;}
</STYLE>
</head>
<body>
<a href="registerlistener.jsp">Register a Listener</a>
&nbsp;&nbsp;
<a href="listnotifications.jsp">Reload Page</a>
<h3>Registered Listeners</h3>

<%
DateFormat DF = DateFormat.getDateTimeInstance();
ServletContext ctx = config.getServletContext();
GlobalListenerMap glm = (GlobalListenerMap)ctx.getAttribute("GlobalListenerMap");
List<JMXListenerBean> listeners = glm.getListenerListForSession(session.getId());


if(listeners!=null) {
for (JMXListenerBean listener: listeners) {
out.println("<p><span class=\"listener\">" + listener.getMBean() + "</span></p>");
out.println("<table>");
for(Notification notification: listener.getNotifications()) {
String line = String.format("<tr font=\"arial\"><td>[%s]</td><td class=\"state\">%s</b></td><td>%s</td></tr>",
DF.format(new Date(notification.getTimeStamp())),
notification.getType(),
notification.getMessage());
out.println(line);
}
out.println("</table>");
}
}
%>
</body>
</html>
addregistration.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="sab.demo.jmx.map.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>Index</title>
<STYLE TYPE="text/css">
TD, BODY {font-family: Arial; font-size: 10pt;}
</STYLE>
</head>
<body>
<a href="listnotifications.jsp">Cancel</a>
<h3>Register MBean Listener</h3>
<form action="registrationservlet" method="post">
<p>
<table>
<tr>
<td>MBean Name:</td>
</tr>
<tr>
<td>
<select name="mbean">
<%
ServletContext ctx = config.getServletContext();
GlobalListenerMap glm = (GlobalListenerMap)ctx.getAttribute("GlobalListenerMap");
if(glm==null) System.out.println("glm was null");
for(String mbean: glm.getJ2EEApplicationNameList()) {
%>
<option><%=mbean%></option>
<%
}
%>


</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit"/>
</td>
</tr>
</table>
</p>
</form>
</font>
</body>
</html>

----------------
Listening to: The Stone Roses - She Bangs The Drums

26 June 2008

Configuring OC4J log handler to log in plain text format

The default log file format for the OC4J generated logs in the 10.1.3.x release is to use an XML formatted log entry, where a single log entry spans many lines.

As with all things XML this enables the logs to be readily read, queried, etc. with any utility that is compatible with the ODL log format. The ASC log viewer is an example of this -- it renders the log files in a pretty easy to view form, and provides convenience functions such as searching, correlation, etc.

However, for us mere humans, all those extra tags tend to make the log files pretty verbose and difficult to read in realtime using a command like tail.

The ODL logging handler that OC4J uses luckily has an option that causes it to generate into a plain text form instead of the default XML form.

To configure it, you simply need to specify an additional property named "format" and set it to a value of "ODL-Text".

Here's an example of defining a new log_handler and directing it to log to the log.txt file, in text form, maintaining a max file size of 10MB:
<log_handler name="my-text-handler" class="oracle.core.ojdl.logging.ODLHandlerFactory">
<property name="format" value="ODL-Text"/>
<property name="path" value="../log/oc4j/log.txt"/>
<property name="maxFileSize" value="10485760"/>
<property name="maxLogSize" value="104857600"/>
<property name="encoding" value="UTF-8"/>
<property name="supplementalAttributes" value="J2EE_APP.name,J2EE_MODULE.name,WEBSERVICE.name,WEBSERVICE_PORT.name"/>
</log_handler>
With the handler in place, you can then configure a logger to use your new handler as follows:
<logger name="oracle" level="finer">
<handler name="my-text-handler"/>
</logger>
At runtime the log.txt file will contain single line, plain text entries of the form:
[2008-06-26T11:40:59.343+09:30] [classloader] [TRACE] [] [] [tid: 10] [ecid: 10.187.112.202:83229:1214446259343:0,0] Ign
oring in /D:/java/oc4j-10134-dev/j2ee/home/config/server.xml entry: code-source /D:/java/oc4j-10134-dev/j2ee/home/jsp/lib/taglib/ojsputil.jar (from in /D:/java/oc4j-10134-dev/j2ee/home/config/server.xml) is already visible in the search path of global.tag.libraries:1.0.

25 June 2008

Scheduling OC4J periodic tasks using java.util.concurrent

A question on OTN last week raised the issue of how to fulfill a requirement to have a task run periodically within OC4J that did some form of directory read/processing ativity.

If take out the actual tasks that need to be performed for the moment, then what we are looking to do here is to run some form of activity on a repeated basis.

One way I thought to tackle this was to make use of the new facilities provided by the java.util.concurrent package. Particularly, this package has a ScheduledExecutorService which allows for tasks to be submitted that are configured to run on a repeated basis.

The ScheduledExecutorService has a method that enables tasks to run on a repeated basis with a fixed delay:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)

This method takes in a java.lang.Runnable, which encapsulates the steps that need to be performed when the periodic task runs.

It then takes in the data for how the task should be run -- initial delay, the fixed delay and the time unit.

Armed with this, we can create our task by implementing the java.lang.Runnable interface and schedule it for running using the ScheduledExecutorService.

A trivial example of a task for the purpose of testing this could look like this.
package sab.demo.susdtest;

import java.text.DateFormat;
import java.util.Date;

public class MyScheduledTask implements Runnable {

private DateFormat DF = DateFormat.getDateTimeInstance();

public MyScheduledTask() {
}

public void run() {
// Do some long winded thing to simulate "processing and
// provide a place to issue a ctrl+c and show what happens
System.out.printf("[%s] MyTask awake, doing something ....\n", DF.format(new Date()));
String ret = "";
int j=0;
for (int i=0;i<15000;i++) {
ret = ret + Integer.valueOf(i).toString();
j=i;
}
System.out.printf("[%s] MyTask finished processing [%s]....\n",
DF.format(new Date()),
j);
}
}
If we now consider that our task may be performing operations that have open handles to resources that will need to be handled carefully, the ScheduledExecutorService also has a method called shutdown() which will nicely shutdown the ScheduledExecutorService by cancelling all the pending tasks and ultimately calling interrupt on any currently executing task.

Now to wire this into OC4J so that the ScheduledExecutorService is created/started when OC4J starts and it shuts down when OC4J itself is stipped, then one readily apparent place to start is the use of the OC4JStartup and OC4JShutdown classes.

Using the OC4JStartup interface, a class can be created that performs the steps needed to create/start/schedule the task. The ScheduledExecutorService is bound into the Context provided to the class so that it can be accessed in other startup and shutdown classes that are called.
package sab.demo.susdtest;

import oracle.j2ee.server.OC4JStartup;
import java.util.Hashtable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;

public class Startup implements OC4JStartup {
private static final int INITIAL_DELAY = 10;
private static final int DELAY = 15;

public Startup() {
}

public String preDeploy(Hashtable hashtable,
Context context) throws Exception {

// Create a ScheduledExecutorService, schedule the task we want to
// regularly run and then bind it into context so it can be accessed
// by other OC4JStartup or OC4JShutdown classes. The delay parameters
// could be provided as config parameters and extracted from the
// hashtable
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(
new MyScheduledTask(), INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
context.bind("task", executor);
return null;
}

public String postDeploy(Hashtable hashtable,
Context context) throws Exception {
return null;
}
}
The OC4JShutdown class implementation class needs to extract the ScheduledExecutorService from the context, issue the shutdown call on it and wait for the service to terminate.
package sab.demo.susdtest;

import java.text.DateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;
import oracle.j2ee.server.OC4JShutdown;

public class Shutdown implements OC4JShutdown {

private static final int MAX_DELAY = 60;

DateFormat DF = DateFormat.getDateTimeInstance();

public Shutdown() {
}

public String preUndeploy(Hashtable hashtable,
Context context) throws Exception {

// Extract the ScheduledExecutorService from the context and ask it to
// shutdown, waiting for a max of 60 seconds for it to complete its task
ScheduledExecutorService executor =
(ScheduledExecutorService)context.lookup("task");

if(executor != null ) {
System.out.printf("[%s] Calling executor service shutdown\n", now());
executor.shutdown();
// The max wait time could be obtained as a parameter via the hashtable
System.out.printf("[%s] Waiting on executor service shutdown\n", now());
executor.awaitTermination(MAX_DELAY, TimeUnit.SECONDS);
System.out.printf("[%s] Done with executor service shutdown \n", now());
} else {
System.out.printf("[%s] No executor service found in context, " +
"no shutdown performed....\n", now());
}
return null;
}

public String postUndeploy(Hashtable hashtable,
Context context) throws Exception {
return null;
}

private String now() {
return DF.format(new Date());
}
}
With those classes created, compiled and packaged into a JAR file, you then configure OC4J to make use of them by adding entries into its server.xml file.
        <init-library path="D:\java\jdev-10133\jdev\mywork\susd-test\test\deploy\susdtest.jar" />
<startup-classes>
<startup-class classname="sab.demo.susdtest.Startup" failure-is-fatal="true" >
<execution-order>0</execution-order>
</startup-class>
</startup-classes>
<shutdown-classes>
<shutdown-class classname="sab.demo.susdtest.Shutdown" >
<execution-order>0</execution-order>
</shutdown-class>
</shutdown-classes>
Once all that has been completed, it's time to give it a field test.

Here we start OC4J, wait until the task begins its execution then shutdown OC4J. Note how the container waits for the task to complete before it completes its shutdown fully.
D:\java\oc4j-10133-prod\j2ee\home>java -jar oc4j.jar
08/06/25 11:42:15 Oracle Containers for J2EE 10g (10.1.3.3.0) initialized
[25/06/2008 11:42:21] MyTask awake, doing something ....
Shutting down OC4J...
[25/06/2008 11:42:32] Calling executor service shutdown
[25/06/2008 11:42:32] Waiting on executor service shutdown
[25/06/2008 11:42:35] MyTask finished processing [14999]....
[25/06/2008 11:42:35] Done with executor service shutdown
Here we start OC4J, allow the task to begin and complete, then signal OC4J to shutdown. Since there are no running tasks, the shutdown completes almost immediately and OC4J completes its full shutdown likewise.

D:\java\oc4j-10133-prod\j2ee\home>java -jar oc4j.jar
08/06/25 11:43:16 Oracle Containers for J2EE 10g (10.1.3.3.0) initialized
08/06/25 11:43:22 [25/06/2008 11:43:22] MyTask awake, doing something ....
[25/06/2008 11:43:37] MyTask finished processing [14999]....
Shutting down OC4J...
[25/06/2008 11:43:40] Calling executor service shutdown
[25/06/2008 11:43:40] Waiting on executor service shutdown
[25/06/2008 11:43:40] Done with executor service shutdown

12 June 2008

mod_weblogic

Well it had to happen eventually -- welcome to Weblogic Server :-)

Thought I'd walk through how to configure Apache as the front end server for a Weblogic Server.

Turns out, it's as easy as the proverbial:
  1. Install WLS, create a domain, start it up
  2. Download and install Apache (I used 2.2)
  3. Copy the corresponding Apache module (for 2.2 I used mod_wl_22.so) from the WLS installation into $APACHE_HOME/modules directory
  4. Edit $APACHE_HOME/conf/httpd.conf and enable the mod_weblogic as follows:

    # Load BEA Module
    LoadModule weblogic_module modules/mod_wl_22.so

    # Config file for WebLogic Server that defines the parameters
    Include conf/mod_weblogic.conf

  5. Create the referenced mod_weblogic.conf file in which you place the configuration elements for mod_weblogic to use:

    # Basic config for mod_weblogic to point at my WLS instance

    WebLogicHost localhost
    WebLogicPort 7001
    Debug ON
    WLLogFile c:\temp\wlproxy.log
    WLTempDir c:\temp
    DebugConfigInfo On


    # Map the URLs to expose via Apache
    # Expose the console via Apache

    SetHandler weblogic-handler


  6. Test the config with Apache

    $APACHE_HOME\bin\httpd -t

  7. Start Apache
  8. Access the console via Apache (assuming all default ports)

    http://localhost:8080/console

And that's the basic set of steps -- you should be looking at the WLS console being serviced via Apache.

With the config above, I've enabled the DebugConfigInfo option -- which allows you to see a bunch of useful debug/usage information by entering a URL serviced by mod_weblogic and tacking on a request parameter of the form ?__WebLogicBridgeConfig.

05 June 2008

Classloader Loader Event Tracing

Classloader Event Tracing

If you are seeing classloader closed errors from time to time, then one really useful utility OC4J has is the ability to log the various events related to different aspects of the classloading mechanism.

So for example, lets say you are seeing errors occasionally containing this type of message: "This loader has been closed and should not be in use."

Then what you can do to help trace why this is occurring is to enable log tracing for the various loader events.

In the error message above, it should also explicitly provide the name of the loader that was being used, of the form appname.modulename[.module]:major.minor. For example myapp.webmodule.root:0.0

To observe classloading events relating to this specific loader, you configure OC4J to start as follows:

>java -Dclass.load.trace=loader:myapp.webmodule.* -Dclass.load.trace.level=all -jar oc4j.jar


That setup configures OC4J to output all the loader related classloading events, at the log level of ALL, where the loader name matches the pattern "myapp.webmodule.*".

In the output, you'll see entries such as:

ClassLoader created: myapp.webmodule.root:0.0.0 (instance 1cba87)
ClassLoader committed: myapp.webmodule.root:0.0.0 (instance 1cba87)
...
ClassLoader closing: myapp.webmodule..jsp13471351:0.0.0 (instance 14441b6)
...

That shows you where the loaders are being operated on, and confirms (one way or another) that the loader is actually being closed -- this may correlate with other actions you have performs -- say a redeployment operation.

Now to help further understand why/where the loader event occured, you can add an extra event filter. The "stack" event filter adds the associated stacktrace that caused the loader event to occur to the output -- thus for the loader closed events, you can trace back and identify the source of the loader close.

To add the stack event filter to the classloader tracing, simply concatentate it to the class.load.trace property:
>java -Dclass.load.trace=stack+loader:myapp.webmodule.* -Dclass.load.trace.level=all -jar oc4j.jar

That then causes a stacktrace to be appended to each event that is logged:

ClassLoader closing: myapp.webmodule:0.0.0 (instance 18aea9e)
at oracle.classloader.util.ClassLoadTracing$LoaderListener.loaderClosing(ClassLoadTracing.java:738)
at oracle.classloader.EventDispatcher.loaderClosing(EventDispatcher.java:232)
at oracle.classloader.PolicyClassLoader.close(PolicyClassLoader.java:1056)
at oracle.classloader.PolicyClassLoader.close(PolicyClassLoader.java:1041)
at com.evermind.server.http.HttpApplication.destroy(HttpApplication.java:5860)
at com.evermind.server.http.HttpApplication.stopCleanUp(HttpApplication.java:8437)
at com.evermind.server.http.HttpApplication.componentStop(HttpApplication.java:8383)
at com.evermind.server.Application.doStop(Application.java:2092)
at com.evermind.server.Application.stop(Application.java:2019)
at oracle.oc4j.admin.management.mbeans.J2EEStateManageableObjectBase.stop(J2EEStateManageableObjectBase.java:275)
at oracle.oc4j.admin.management.mbeans.J2EEApplication.stop(J2EEApplication.java:1542)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:36)
at sun.reflect.GeneratedMethodAccessor17.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:239)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1071)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:953)
at oracle.oc4j.admin.jmx.server.mbeans.model.DefaultModelMBeanImpl.invoke(DefaultModelMBeanImpl.java:700)
at com.sun.jmx.mbeanserver.DynamicMetaDataImpl.invoke(DynamicMetaDataImpl.java:213)
at com.sun.jmx.mbeanserver.MetaDataImpl.invoke(MetaDataImpl.java:220)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:815)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:784)
at oracle.oc4j.admin.jmx.server.state.ApplicationStateFilterMBeanServer.invoke(ApplicationStateFilterMBeanServer.java:572)
at oracle.oc4j.admin.jmx.shared.UserMBeanServer.invoke(UserMBeanServer.java:634)
at oracle.oc4j.admin.jmx.server.state.LocalizationFilterMBeanServer.invoke(LocalizationFilterMBeanServer.java:579)
at oracle.sysman.ias.studio.jmx.spi.JMXConnectorImpl.invoke(JMXConnectorImpl.java:389)
at oracle.sysman.ias.studio.oc4j.JMXAppAdminBean.stopApp(JMXAppAdminBean.java:276)
at oracle.sysman.ias.studio.oc4j.AppHelper.doStopAppOp(AppHelper.java:776)
at oracle.sysman.ias.studio.oc4j.AppHelper.access$600(AppHelper.java:116)
at oracle.sysman.ias.studio.oc4j.AppHelper$AppControlProcessingBean.appControlOperation(AppHelper.java:1628)
at oracle.sysman.ias.studio.oc4j.AppHelper$AppControlProcessingBean.doWork(AppHelper.java:1642)
at oracle.sysman.ias.studio.util.ProcessingBean$ProcessingThread.run(ProcessingBean.java:273)
at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
at java.lang.Thread.run(Thread.java:595)


Looking at the stacktrace for the loader closing event, you can reasonably surmise that the event was caused by the application being "stopped" from ascontrol (sysman).

Now that's a contrived example, I agree! But I hope it serves in some small way to demonstrate how you can use the classloader tracing mechanism to get a handle on the different events that happen to loaders and why they have occurred.

04 June 2008

FAQ for OC4J 10.1.3. Management

A few questions I see from time to time in the OTN OC4J Forum are covered in the OC4J 10.1.3 Management/Admin FAQ

http://www.oracle.com/technology/tech/java/oc4j/1013/whitepapers/OC4J-FAQ-MGT-10131.pdf

17 April 2008

Creating Users in OC4J Groups

Another relatively common question:

The ascontrol group page only allows creation/configuration of JMS and JDBC resources at the group level. Is it possible to create users across all the OC4J instances in Group from ascontrol?

Yes this can be done.

The solution is to use the Cluster MBean Browser provided in ascontrol and execute an operation on the J2EEApplication MBean via the desired J2EEServerGroup MBean.

Luckily its documented in the OC4J Security Guide, so I don't need to butcher the description any more!

http://download.oracle.com/docs/cd/B32110_01/web.1013/b28957/configxml.htm#sthref316