Introducing NIO.2 (JSR 203) Part 2: The Basics

In this part we will discuss the basic classes that we will work with them to have file system operations like copying a file, dealing with symbolic links, deleting a file, and so on. I will write a separate entry to introduce classes which are new to Java 7 for dealing with streams and file contents, watching service and directory tree walking. If you want to know what are new features in Java SE 7 for dealing with IO take a look at   Introducing NIO.2 (JSR 203) Part 1: What are new features?

Before NIO.2, dealing with file system was mainly done using the File class and no other base class was available. In NIO.2 it there are some new classes at our disposal to take advantage of their existence to do our job.

FileSystems: Everything starts with this factory class. We use this class to get an instance of the FileSystem we want to work on. The nio.2 provides a SPI to developed support for new file systems. For example an in-memory file system, a ZIP file system and so on. Following two methods are most important methods in FileSystems class.

  1. The getDefault() returns the default file system available to the JVM. Usually the operating system default files system.
  2. The getFileSystem(URI uri) returns a file system from the set of available file system providers that match the given uir schema.

Path: This is the abstract class which provides us with all File system functionalities we may need to perform over a file, a directory or a link.

FileStore: This class represents the underplaying storage. For example /dev/sda2 in *NIX machines and I think c: in windows machines. We can access the storage attributes using  FileStoreSpaceAttributes object. Available space, empty space and so on.

Following two sample codes shows how to copy a file and then how to copy it.

public class Main {

    public static void main(String[] args) {

        try {
            Path sampleFile = FileSystems.getDefault().getPath("/home/masoud/sample.txt");
            sampleFile.deleteIfExists();
            sampleFile.createFile(); // create an empty file
            sampleFile.copyTo(FileSystems.getDefault().getPath("/home/masoud/sample2.txt"), StandardCopyOption.COPY_ATTRIBUTES.REPLACE_EXISTING);
            // Creating a link
            Path dir = FileSystems.getDefault().getPath("/home/masoud/dir");
            dir.deleteIfExists();
            dir.createSymbolicLink(sampleFile);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

And the next sample shows how we can use the FileStore class. In this sample we get the underlying store for a file and examined its attributes. We can an iterator over all available storages using FileSystem.getFileStores() method and examine all of them in a loop.

 public class Main {

    public static void main(String[] args) throws IOException {
        long aMegabyte = 1024 * 1024;
        FileSystem fs = FileSystems.getDefault();
        Path sampleFile = fs.getPath("/home/masoud/sample.txt");
        FileStore fstore = sampleFile.getFileStore();
        FileStoreSpaceAttributes attrs = Attributes.readFileStoreSpaceAttributes(fstore);
        long total = attrs.totalSpace() / aMegabyte;
        long used = (attrs.totalSpace() - attrs.unallocatedSpace()) / aMegabyte;
        long avail = attrs.usableSpace() / aMegabyte;
        System.out.format("%-20s %12s %12s %12s%n", "Device", "Total Space(MiB)", "Used(MiB)", "Availabile(MiB)");
        System.out.format("%-20s %12d %12d %12d%n", fstore, total, used, avail);

            }

In next entry I will discuss how we can manage file attributes along with discussing the security features of the nio.2 file system.

Jun 1st, 2010 | Filed under How To, Java, Java SE, Learning

Introducing OpenESB from development to administration and management.

OpenESB project initiated by Sun Microsystems to develop and deliver a high performance, and feature rich implementation of Java Business Integration (JBI) under an open source friendly license. Basic task of JBI implementations is connecting different type of resources and applications together in a standard and none intrusive way. Basic building blocks of an ESB includes the Bus which is a message driven engine and transition path which deliver the required message to designated binding components. These components are the second main set of artifacts which an ESB has. The main tasks of binding components is receiving the Bus standard format messages and deliver them to other software in a format that the particular software can use. The third set of artifacts is Service engines which can relates the Bus to other types of containers like Java EE containers, transform the messages before they enter the Bus, perform routing related activities over the Bus messages.

The Main concept behind the JBI was around for quite some times but in recent years several factors helped with this concept to further evolve. First the increasing integration problems, second the SOA acceptance level between companies and finally introduction of JSR-208 specification by JCP which provides a common interfacing mechanism for JBI artifacts.

The increasing problem is nothing but the urge for integrating different software which is running in different department of the same enterprise or different partners across enterprises. An ESB implementation can be a non intrusive enabler product for integrating different software running in different department or enterprises without or with very small amount of changes in the software itself.

The concept which helped ESB to become very well known and popular is the Service Oriented Architecture (SOA) in which an ESB can play the enabler role because of its modularity and loose coupling nature.

1 Introducing OpenESB

OpenESB project located at http://open-esb.dev.java.net initiated in 2005 when Sun Microsystems released a portion of its ESB products under CDDL license. Sun Microsystems, the user community and some other third party companies are working together on OpenESB project. However, the main man power and financial support comes from Sun Microsystems.

The project goal is development and delivery of a high performance, feature rich and modular JBI compliant ESB (the runtime) and all required development phase tools which accelerates and facilitate developing applications based on OpenESB capabilities and features.

The runtime components use GlassFish application server’s components like Metro web services stack, CLI and administration console infrastructure, and so on. OpenESB uses NetBeans IDE as the foundation for providing development and design time artifacts for its it runtime components. Design time functionalities are provided in a modular manner on top of NetBeans modularity system.

1.1 Introducing JBI

The JBI defines a specification for assembling integration components to create integration solutions that enable different software (external system) to actively integrate on providing a solution based on separate capabilities which every one of that software can provide on itself. These integration components are plugged into a JBI environment and can provide or consume services messages which lead in providing or consuming a service through the shared communication channel. The shared communication channel can route messages between different components and it also can transform the messages in a pre-defined or rule based way. In addition to transformation, different other base services are provided by the JBI environment. We call the environment the Service Bus or Enterprise Service Bus.

Based on the JBI specification and architecture a component is the main part of a JBI implementation which users or developers should understand. These components can acts as consumer or producers. When a component acts as consumer it receives a message from the service bus in a normalized and standard format. Then the component delivers the message to the external system in a format that the external system understands. When a component acts as a consumer to the service bus, it receives the message in a format provided by external system and converts it to normalized XML before sending it into the service bus. We call these components as binding components because they bind a external system to the service bus.

The JBI environment

JBI defines two types of components which JBI developers can develop and plug into a JBI container. However these two types are standardized and certainly each vendor has many internal and none standard interfaces, components, and a specific component model for its internal system. These Two types of components which can be plugged into a JBI environment include:

  • Service engines provide logic in the environment, such as transformation, scripting language support, ETL and CEP support, or BPEL and so on.

Binding components are adapters which can connect an external system to the service bus. For example a JMS binding component can connect a JMS message broker to the service bus, a mail server component can bind an emailing system to the bus to make it possible for other binding components to send email or receive emails through the bus.

Figure 1 shows the overall architecture of OpenESB from the specification point of view. The architecture may differ from implementation to implementation.

Figure 1 The OpenESB architectural diagram from JBI perspective

The most important fact in the JBI environment in message delivery and content delivery usually introduces requirements like transaction support, naming support, and so on. The internal square illustrates the OpenESB overall environment while the external boxes represent systems external to the OpenESB runtime. Message format inside the square is XML while the format between the binding components and external system is external system oriented. Every component either Service engine or Binding component register the service that they provide by WSDL descriptor.

1.2 OpenESB versions and editions

OpenESB like GlassFish has several concurrent versions which are either in active development mode, stable or in maintenance mode. OpenESB version one is in maintenance mode and the only updates are possible bug fixes, no new feature will be added to this version.

OpenESB version 2 is the current active version which is under development. OpenESB version 3 named project Fuji is under active design and development. Through the project Fuji Sun Microsystems will develop the next version of OpenESB which is fully based on a modular system similar to GlassFish version 3.

Like OpenSSO and GlassFish which have which have commercially packaged version supported by Sun Microsystems, there is a commercially packaged and supported package for OpenESB named GlassFish ESB. The only different between OpenESB and GlassFish ESB is that GlassFish ESB is a package which contains stable components of the OpenESB along with Sun Microsystems support behind it.

If you are looking for latest bug fixes, latest new features and components you should go with OpenESB, if you want a stable version then you should go with GlassFish ESB. Both versions are free and you can use them commercially without paying any license fee. The difference is that Sun provides commercial level support for GlassFish ESB packages.

All versions of OpenESB including GlassFish ESB, Project Fuji, and OpenESB development builds are available at http://open-esb.dev.java.net/Downloads.html.

1.3 OpenESB Architecture

OpenESB version 2 closely follows the specification and has no extendibility or pluggibility beyond the JBI proposed components. OpenESB JBI container is tightly integrated with GlassFish application server to provide the overall running ESB. The integration between GlassFish application server and OpenESB results in integrated administration console in all 3 major administration channel including JMX and AMX, CLI and web based administration console.

The most important part of an ESB is the message broker and its Web services stack. OpenESB uses Metro Web service stack which is proven enough to be used by some other vendors as their web services stack and OpenMQ as the message broker. OpenMQ can be considered one of the top level message broking systems in term of performance and capabilities.

1.4 OpenESB supported standards and features

When it come to list an ESB features and supported protocols and format we can list them under five different categories including: The over all performance, the reliability and scalability of the system, available service engines, available binding components and finally administration and management channel effectiveness.

Certainly there are other factors which can not deeply discuss here, factors like: vendor support level, quality of available components and service engines. Providing benchmarks which shows how good the product works and so on. But, to some extent, we can discuss five primary attributes briefly.

performance

The most important part of an ESB is the messaging system; OpenESB uses OpenMQ as the underlying messaging system. In different benchmarks and uses cases OpenMQ proved to perform very well.

The other important component which affects an ESB performance is Web services stack which is used to develop the underlying WSDL-SOAP communication. The Metro framework which forms the underlying Web services stack of OpenESB is very well featured with an outstanding performance. IBM uses some part of Metro in their JDK, BEA uses Metro stack for its WebLogic application server and so on.

Available service engines

Functional feature of an ESB are directly depended on the functionality of its service engines and binding components. OpenESB has a very rich set of Service engines which are either developed directory by Sun Microsystems or one of OpenESB project partners. Table 1 shows the list of most important service engines along with a description of each service engine.

Table 1 Important service engines available through project OpenESB

Service Engine

Description

BPEL SE

A WS-BPEL 2.0 compliant engine that provides business process orchestration capabilities.

IEP SE

An engine for Complex Event Processing (CEP) and Event Stream Processing (ESP)

Java EE SE

Makes the whole EE environment available as a JBI component so that EJBs can communicate with other JBI components through the NMR and vice versa.

WLM SE

The Worklist Manager is a JBI based engine providing task management and human intervention in a business process.

Data Integrator / ETL SE

Performs extract – transform – load to build DataWarehouses, or can be used for Data Migration.

Data mashup

Provides a single view of data from heterogeneous sources, including static web pages and tabular data exposed as web services. Provides options to join/aggregate/clean data, and generate a response in a WebRowSet schema.

XSLT SE

An engine for applying XSLT transformations with basic orchestration capabilities.

All of these service engines have the runtime and design time components included. Some of them are not commercially stable enough to be included in GlassFish ESB and in case of requirement we should download and install them manually. The nightly builds are available at http://download.java.net/jbi/binaries/installers/single-component/v2/nightly/.

We will discuss BPEL SE in more details in subsequent sections.

Available binding components

Binding components provide the functionalities required to connect an external system to the service bus. We have two expressions about binding components; a binding component acts as consumer or provider. For example an email component which acts as consumer sends a message which receives through the service bus to an email address. And when it injects the incoming emails into the bus it is acting as a provider.

Table 2 lists important binding components available through the OpenESB components project. These components are either developed by Sun Microsystems or one of its partners. Each binding component has a runtime and a design time part. The runtime part should be deployed into OpenESB while the design time part is a NetBeans module which we should install.

Table 2 Important binding components available through project OpenESB

Component

Description

eMail BC

A Binding Component for sending and receiving emails

Database BC

Reads messages from and writes messages to a database over JDBC

HTTP BC

A JBI component for sending and receiving messages over HTTP

JMS BC

Receives messages from and sends messages to a remote service through JMS

LDAP BC

Reads messages from and writes messages to an LDAP server

SAP BC

Provides functionality for interacting with a SAP R/3 system within a JBI environment.

SIP BC

Integrates media capabilities from communications networks using the SIP protocol (Session Initiation Protocol)

FTP

BC Polls for files on an FTP server, and provides for uploading files to an FTP server

File

BC Polls for files on the file system, and provides for writing files to the file system

 

Number of Binding components reaches 30 and covers variety of standards and protocols. Table 2 lists the most widely used binding components regardless of either it are in beta or stable state. You can find a list of all components at https://open-esb.dev.java.net/Components.html. The list contains all necessary information like states, in maintenance mode or deprecated components and so on.

Administration and management

One important feature of a middleware is the possibility to administrate, monitor, and manage the middleware in ac effective and preferment way. OpenESB follows the same path that GlassFish does and provides very profound administration functionalities including a CLI and web based administration. Administration console provides monitoring information for service engines and binding components and deployed artifact.

2 Getting OpenESB running

Every big software need some sort of manual for installing and running the application, the manual includes information about compatible architecture, operating systems and runtime platforms. In our case we can install OpenESB on any operating system which there is a Java 5 runtime environment available for it. The supported platforms include Windows, Linux flavors, Solaris flavors, and Mac OSX flavors.

2.1 Downloading and installing

OpenESB is based on GlassFish and therefore it has the same packaging policy and schema for different operating systems. In our exploration we will use GlassFish ESB version 2 which is available at https://open-esb.dev.java.net/Downloads.html. Make sure that you select the right version for your operating system and underlying architecture.

GlassFish ESB bundle contains the runtime bits which is consisting of JBI components and service engines along with the JBI container itself. The distribution package also contains the development time components which include NetBeans IDE and additional modules for supporting bundler JBI runtime components.

The installation process is quite simple; the installer asks for installation path and configuration information like GlassFish instance port, administration credentials and so on. By now you should be very good with the installation process. Before starting the installation process, ensure that you have something around 600MB of free space in the partition that you want to install the package.

Installing both GlassFish ESB runtime and NetBeans IDE inside one parent directory is a good practice as we have all development related artifacts in the same place.

2.2 Getting familiar with GlassFish ESB

I assume that we installed GlassFish ESB in a folder named glassfishesb_home, content of this folder is shown in figure 2

 

Figure 2 GlassFish ESB installation directory’s content

The content is very straight forward and cleans for such a massive development and deployment system. The glassfish folder includes GlassFish version 2ur2 along with stable versions of OpenESB container and components while the netbeans directory contains NetBeans IDE along with all necessary modules to support GlassFish ESB functionalities in design time.

We can start the server separately by running start_glassfish_domain1 script for times that we do not need the development environment running. Otherwise we can start NetBeans IDE by running start_netbeans script and then letting NetBeans to start the server when required.

3 Developing and testing a simple application

NetBeans IDE is a very feature rich IDE for developing Java EE applications and inclusion of SOA and Composite application development functionalities which targets OpenESB make the IDE a perfect development tools for developing composite applications and integration components. In this section we create a very simple BPEL based application to show how the overall process works.

3.1 The sample scenario

It is important to understand what we want to build and what features of OpenESB artifacts we want to use to implement the required functionalities. We have a portal like system which users can add a whether Portlet to see the current weather of their home city. We want to store some statistics which later on helps us determine which country and cities has largest number of users which use the Portlet weather.

To achieve this goal we used two web services, the first one translate the IP address of our client to its location including country and city and the second service provides us with current weather condition. We should somehow weave these services together to achieve the desired result. We also need to log all access to these web services with details related to country, city and date in a text file or database table to perform the statistical analysis and extract the usage portion for each country and each city in each country.

We will only use two BEPL components including the Database BC and BPEL SE. with these two component we can achieve a complete solution for our problem which otherwise could take more time to implement with much less flexibility in term of applying new and updated business rules.

3.2 Creating the BPEL Module project

Run NetBeans IDE and switch to Services view (CTRL+5), expand the database node and right click on the Java DB instance and select Start Server from the context menu. Expand the drivers’ node and right click on Java DB (Network) node and select Connect Using.

When the New Database Connection opened, change different attributes of the connection as follow:

  • Database URL: jdbc:derby://127.0.0.1:1527/WeatherInfo;create=true

  • User: APP

Password: APP

Click OK and NetBeans will create a new connection to our database. Expand the connection node, right click on the Tables node and select Create Table item. Create a table named wRequestLog with fields listed in the table 3.

Table 3 The wRequestLog table’s fields

Field Name

Field Type

rDate

Varchar(30)

Country

Varchar(30)

City

Varchar(30)

 

The composite application runs inside the container and for accessing our WeatherInfo database we need to create a connection pool and data source in GlassFish application server. Create a connection pool for the above database and then create a data source named jdbc/winfo.

To create the connection pool you can use following asadmin command.

create-jdbc-connection-pool --datasourceclassname org.apache.derby.jdbc.ClientDataSource --restype javax.sql.XADataSource --property portNumber=1527:password=APP:user=APP:serverName=localhost:databaseName=WeatherInfo WinfoPool

I am sure that you remember how we used to create data sources but I provide the corresponding asadmin command if you have just forget the spelling ;-) .

create-jdbc-resource --connectionpoolid WinfoPool jdbc/winfo

Now we are ready to take one step further and create the project and its related files like copy of WSDL documents, BPEL process file and so on.

Run the SOA enabled NetBeans IDE and from the main menu select File>New>Project and from categories select SOA and from projects list select BEPL Module click next and change the project name to WeatherInfo.

Right click on project node in project view (CTRL+1) and select New>Other, a window will open, from the categories select XML and from file types select External WSDL Document and click next. We want to create a WSDL from a URL therefore use http://ws.cdyne.com/ip2geo/ip2geo.asmx?wsdl as the URL and click finish. NetBeans will create a reference to the WSDL file along with a local copy of the WSDL file which we may edit to tailor it to our requirement. This web service provides us with location of a given IP address. The IP2Geo web service is provided by CDYNE Corporation and I get a trial license for using the web service in the book.

Follow the same procedure and create a new WSDL file from http://www.webservicex.com/globalweather.asmx?WSDL. This web service takes a city name along with the country name and returns the current weather. The Global Weather web service is provided by WebserviceX.

We have two more steps and then we are finished with creating our project’s basic artifacts. The first artifact is a WSDL descriptor which let us use Database Binding Component to record all requests and the second artifact is the WSDL descriptor which describe input and output types of our provided service which is our BPEL process.

To create the database binding component, right click on the project node and select New>WSDL Document the wizard will open and guide you through the process. In the first page of wizard use the following information:

  • Change the name to DBLOGBC

  • Change the WSDL Type to Concrete WSDL Document; two new attributes will become available.

Change the Binding to Database and change the Type to Prepared Statement.

Click next, in this page we should determine which database connection we want to use, select the connection URL that we made in previous step and click Next. In this step we need to enter a valid prepared statement which the binding component will execute against the database. Enter the following snippet as the prepared statement value and then press Discover Parameters.

insert into APP.WREQUESTLOG (rdate,country,city) values (?,?,?)

Change the parameters name according to figure 3 and click Next then click Finish and we are done with defining a database binding component which can integrate into the solution and insert our records into database.

 

Figure 3 Database binding component’s prepared statement definition

The OpenESB version 2 design time modules does not works very good for naming the attributes and operations. We need to rename them manually to have easier mapping and navigation inside the project artifact later. Open the DBLOGBC.wsdl in the source editor and replace all instance of newuntitled_Operation with log_Operation. Also look for jdbc/__defaultDS and replace it with jdbc/winfo. Depending on your NetBeans and OpenESB design time component the default data source name may differ or even the wizard may asks you for the data source name but you can always manually edit the jdbc:address element of the DatabaseBC’s wsdl file to make the correct configuration.

You remember that we changed the parameters name, but your OpenESB design time modules may forget to apply the naming in the XSD file and therefore we will face some ambiguity problems during variables mapping in next steps. So open the DBLOGBC.xsd in the source editor and make following changes:

  • param1 should change to rDate

  • param2 should change to Country

param3 should change to City

Here comes the last step before creating the BPEL process, in this step we define the process communication interface which external clients will use to invoke our process and utilize its service.

Right click on the project node and select New>WSDL Document, when the wizard opened change the name to wInfoProcess; for the WSDL type select Concrete WSDL Document; for the binding choose SOAP and for the type attribute select RPC Literal press Next. Change the input message part name to IPAddress and change the output message part name to weatherInfo.

We are finished with defining all basic artifacts prior to designing the process, now we should just continue with designing the BPEL process itself. To do so, right click on the project node and select New>BPEL Process, change the name to wInfoProcess and click Finish. Now NetBeans should open the BPEL process in the BPEL designer which is a design time module of OpenESB.

In the right side of the IDE you can see components plat and in the left side the project explorer is in place. First let’s create the partner links which connect the BPEL process to other involved parties like external web services and our database binding component. The BPEL designer has three sections, left right and the middle section, the left and right side are used for partner links. Therefore drag and drop the WSDL files from project explorer into the design are as listed in table 4. When you drop a WSDL into the BPEL designer left or right side a window will open which allows you to change the partner link attribute and characteristics. We accept default values for all attributes expect for the partner link name which are listed in the table.

Table 4 adding WSDLs to BPEL process designer

WSDL name

BPEL designer area

Changes required for partner link

ip2geo.asmx.wsdl

Right Side

Change the name to Positioning

globalweather.asmx.wsdl

Right Side

Change the name to Weather

DBLOGBC.wsdl

Right Side

Change the name to Logger

wInfoProcess.wsdl

Left Side

Change the name to WInfoProcess

By now your designer window should be similar to figure 5. Partner Links in the left side meant to be internal to the BPEL process and those in the right side are external to the BPEL process.

Figure 5 The BPEL designer after adding all partner links.

Now we need to add BPEL elements to the process to implement the business logic that we discussed. From top to button we need to add the following elements to the BPEL designer window. The final view of designer window after we finish adding elements will be similar to figure 6.

 Figure 6 BPEL designer view adding all necessary elements

Table 5 shows the complete list of all elements which we should add to the designer. To add the elements we should drag and drop them from the right side Palette into the middle area of the designer. Designer will show you all possible places for dropping the element by shoeing an orange circle in that position. To rename an element we can simply select the element and press F2 or double click on the element name. To connect an element to one of the partners, click on the element, an envelop will appear, drag and connect the element to the partner link mentioned in the table 5

Table 5 List of required BPEL elements which we should add to the designer window

Element Type

Element Name

Partner Link

Receive

GetWeatherInfo

WInfoProcess

Assign

AssignIP

—-

Invoke

InvokeToResolveIP

Positioning

Assign

AssignCityAndCountry

—-

Flow (Structured Activity)

LogAndGetWeather

Invoke (Inside Flow)

GetWeather

Weather

Invoke (Inside Flow)

LogInformation

Logger

Assign

AssignWeather

—-

Reply

ReplyTheInfoToCaller

WInfoProcess

Now we need to add variables and variables assignment and our work with the process and the process designer is finished. In this step we will create all variables and then we will move toward assigning these variables to each other. To create the variables:

  • Double click on GetWeatherInfo and for the input variable click create, accept the defaults and click OK buttons as much as required to see the designer window again.

  • Double click on InvokeToResolveIP and create both output and input variable the same way that you create the variable for the GetWeatherInfo.

  • Double click on GetWeather and make sure that you select GetWeather as the operation and create the input and output variables similar to previous steps.

  • Double click on LogInformation and create input and output variables, accept defaults for variable names and other attributes.

Finally double click on the reply button and for the normal response create a variable and accept the defaults for its name and other attributes.

Now we should be able to assign the variables to each other to make the data flow possible in the process. Thankfully NetBeans come with a very nice and easy to use Assign variable editor called Mapper which we can use to assign the variables to each other. Double click on the AssignIP element and use the following procedure to assign the received IP in the previous step to input variable of InvokeToResolveIP.

In the left side of the Mapper window select output button to ensure that it is filtered for output variables and in the right side select input button to ensure that we are looking at input variables.

Expand the WInfoProcessOperationIn from the left side and expand ResolveIPIn from the right side, make sure that you expand them as much as it does not expand anymore. Now from the left side select IPAddress and connect it to ipAddress in the right side. From the Mapper top menu bar select String and add a String Literal to the middle section of the Mapper window. Change its value to 0 and connect it to licenseKey variable in the right side. Now we are finished with the first assign element. Now switch to the designer view to finish the mapping for AssignCityAndCountry element.

Double click on the AssignCityAndCountry element and assign the variables as follow:

Let’s assign the city name and country name to the GetWeather invoke element. To do so, from the left side expand ResolveIPOut and from the right side expand GetWeatherIn. From the left side, assign city and country parameters of the ResolveIPOut to similar parameters of the GetWeatherIn in the right side. Now we need to assign the same information to our database log operation therefore, expand the Log_operationIn and assign the city and country from the left side to its parameters. We have an rDate parameter which we should use a Current Date & Time predicate. So, from the top menu bar select Date And Time and drop a Current Date & Time predicate into the middle section of the Mapper window. Connect the new predicate to rDate variable of the Log_OperationIn. We are finished with the second variable assignment and one last item remains which we should complete. Figure 6 shows the Mapper window after assigning all variables.

 

Figure 7 Mapper window with complete AssignCityAndCountry assignment

One more variable assignment and we are finished with the BPEL process development. Double click on AssignWeather element and assign the output of GetWeatherOut parameter to WInfoProcessOperationOut parameter. Ok, the name looks unlikely and you may thing that it is an output variable but believe me it is an input variable.

3.2 Creating the Composite Application project

A composite application is the project type that we can use to deploy a composite application into the JBI container. Select File>New Project; from the categories select SOA and from Projects select Composite application and click next. Change the project name to WinfoCA and click finish. The composite application is created and is ready for adding JBI modules.

Right click on the project node and select Add JBI Module, select WeatherInfo project. The CASA editor opens which shows the BEPL module without any relation. Right click on WinfoCA project node and select Clean and Build. NetBeans will compile the composite application and its included JBI modules. When we issue a build command NetBeans refresh the CASA editor and we can add new module, change a data flow between components and so on.

3.4 Deploying and testing sample project

Deploying and testing a composite application is very easy using the well integrated Netbeans, GlassFish and OpenESB. To deploy the application, right click on the WinfoCA node and select deploy. NetBeans will deploy the assembly to OpneESB runtime. To create a test case for the composite application, expand the WinfoCA node and right click on Test node. A wizard will start that help us generate the test case.

In the first page, wizard asks for the test case name, it can be WinfoTest at the second step it asks us to choose which WSDL file we want to test. Expand the WeatherInfo node and select winfoprocess.wsdl press next. Now we should select which operation we want to test, select winfProrocessOperation and click finish. Now we have a test case created, expand the test case in project view and double click on input node to edit the test case input values. Double clicking the input node results in opening an XML file in the editor. The XML file is a SOAP message which we should change its parameters value to suite our test requirement. Therefore change the value of IPAddress element to 209.85.171.100 which is one the Google IP addresses. Save the file and we are finished with creating the test case.

Right click on WinfoTest and select run. IDE will invoke the operation defined in the WSDL file by passing the SOAP message we created to it. Then the output result will appear under the output node of the test case. The output should be information about current weather in Mountain View in the United States.

You can debug a BPEL process and generally a JBI application using NetBeans. The IDE allows you to view the variables during different steps of BPEL execution. The simplest way that we can use to debug the BPEL module is adding our required breakpoint and then executing the test using debug mode.

3.5 OpenESB administration from within NetBeans IDE

NetBeans IDE is very well integrated with OpenESB for not only for developing and testing applications but also for administration and monitoring purposes. All of these functionalities are hidden inside the NetBeans integration adapter for OpenESB.

Press CTRL+5 to open the servers tab and then expand the servers node, expand the OpenESB server instance and finally expand JBI node. Now your server view should be similar to figure 8. Now press CTRL+SHIFT+7 to open the Properties window and then select JBI node. It is wonderful that you can change configuration of the JBI container from within the IDE to continue your work without leaving the IDE and switching between different windows.

 

Figure 8 The OpenESB node in NetBeans Server view

Expand the Service Engines node and select sun-bpel-engine node, the Properties view shows you the entire configuration and read only attributes of the BPEL engine. You can enable the monitoring by checking the checkbox or you can enable the persisting feature to have your BPEL process recovered after any possible crash.

Right click on the sun-bpel-engine node and explore what operations you can perform on the engine from context menu. We can start, stop, upgrade, uninstall and perform any other lifecycle related task using the context menu. We can view the different endpoints used in BPEL process deployed in the BPEL engine using the Show Endpoints Statistics menu item. This menu item helps us to understand whether our services are called during our test period or not and if they are called what was the response semantic and quality.

4 OpenESB administration

The same administration channels which we saw for GlassFish are available for OpenESB and GlassFish ESB. OpenESB CLI commands are integrated with GlassFish CLI utility and follow the same principals. And the Web Based administration console uses GlassFish administration console to present required administration capabilities.

4.1 The CLI utility

OpenESB CLI administration is completely integrated with GlassFish administration and has the same set of characteristics. The only major difference is lack of some commands as GlassFish ESB version 2 is based on GlassFish version 2 and any new functionality that is included in GlassFish version 3 is not present in version 2.

Service assembly administration commands

JBI container like Java EE container has its own application type which is called a JBI service assembly or simply an assembly. Usually the overall procedure of creating and deploying an assembly is done using build systems or IDE but there some commands in the OpenESB CLI which let us administrate the assemblies. All of the OpenESB CLI commands are remote with all characteristics of a remote command like default target server, and so on.

Deploying and undeploying a service assembly are two most basic tasks related to OpenESB administration. In the previous step we developed and deployed an application using NetBeans, now lets undeploy the application and then deploy it using the CLI commands.

To underply the application we can use undeploy-jbi-service-assembly command. For example to undeploy the WinfoCA composite application we can use:

asadmin> undeploy-jbi-service-assembly WinfoCA

Now we can deploy the application archive using the deploy-jbi-service-assembly command. NetBeans puts the built packages into a directory named dist inside the project directory. Let’s deploy the WinfoCA application from that particular directory.

deploy-jbi-service-assembly /opt/article/WinfoCA/dist/WinfoCA.zip

This command deploy the application to the default target server with default attributes like application name and so on.

To list all deployed service assembly we can use list-jbi-service-assemblies command. Now that we have one application deployed into the container this command should show a list containing WinfoCA similar to:

asadmin> list-jbi-service-assemblies

WinfoCA

Command list-jbi-service-assemblies executed successfully.

Each service assembely contains one or more service units which connect services, binding components, and service engines along with any deployment artifacts like XSLT documents, BPEL process and so on. To view these service units we can use show-jbi-service-assembly command. Figure 9 shows how we can use the command to view detailed information for WinfoCA composite application.

Figure 9 viewing the detailed information for an assembly

We can stop, start and forcefully shutdown a service assembly when required by using the OpenESB provided commands.

  • To stop the WinfoCA service assembly: stop-jbi-service-assembly WinfoCA

  • To start the WinfoCA service assembly if it is stopped: start-jbi-service-assembly WinfoCA

To forcefully shutdown the WinfoCA service assembly if required: shut-down-jbi-service-assembly WinfoCA

There are more JBI service assembly commands in the OpenESB CLI which you can find them using ./asadmin help command.

Components administration commands

There two major types of JBI components including service engines and binding components which we may need to deal with. These two types are accompanied with another type named shared library which contains common library classes for several components. Table 6 shows important commands in this set along with an small explanation about each one of them.

Table 6 Important JBI components administration commands

Command

Explanation

start-jbi-component

stop-jbi-component

These commands can be used to start and stop binding components. Stopping a binding component result in any related service unit to stop.

list-jbi-binding-components

list-jbi-service-engines

list-jbi-shared-libraries

Showing a list of deployed JBI components

show-jbi-service-engine

show-jbi-shared-library

show-jbi-binding-component

Show detailed information about a given JBI component which is deployed in the target container.

install-jbi-component

install-jbi-shared-library

install-jbi-service-engine

Installing different JBI components into the target container.

uninstall-jbi-component

uninstall-jbi-shared-library

Uninstalling given JBI component from the target server.

shut-down-jbi-component

shut-down-jbi-service-assembly

Shutdown the given component. Any deployed service unit on the target component will shutdown consequently

Although there are many other command which an administrator may need during his daily tasks but we learned the most important commands in the section. In the next section we will take a look at web based administration console features for OpenESB.

4.2 Administration console

One good point about GlassFish and its companion product is the unified administration channels including CLI, JMX and web based administration console which let us use a unified look and feel and familiar environment to administrate all the infrastructure.

All of JBI administration capabilities are listed under the JBI node in the navigation tree. When you expand all nodes you can see something similar to figure 10. As you can see in figure 10 the JBI node also helps us have a big picture view of our service units’ deployment on different service engines and binding components.

 

Figure 10 OpenESB administration node in the GlassFish administration console

The JBI node itself allows us to configure the container settings like Logging, general statistics, and general configuration related to JBI artifacts installation. Subsequent nodes let us administrate the deployed applications, binding components, service engines and shared libraries.

Service assembly administration

Administration console provides deploy, undeploy, start, stop and shutdown operations for service assemblies. We also can view monitoring information for a deployed service assembles.

For each service assembly we may have one or more service units, we can view service units included in a service assembly along with accessing some monitoring information about them.

JBI components administration

Installing, uninstalling, starting, stopping and shutting down a JBI component which can be either a service engine or a biding component provided in the Components node. Administration console provides us with capabilities which allow us to change the component configuration; its loggers logging level, viewing the descriptor file for the component, and most important thing viewing detailed monitoring information about requests and request processing by each component.

We can see view which service units from which service assemblies are deployed on a component and navigate to the service unit or service assembly configuration.

JBI shared libraries administration

For the shared libraries, we can install, uninstall and view the depended components on each shared libraries to ensure that uninstalling the library will not cause unexpected result in other components.

4.3 Installing new components

OpenESB project provides many components out of the box but there are tens of components available in the OpenESB website at https://open-esb.dev.java.net/Components.html. From this page we can navigate to each component WIKI page and download the required and install them into OpenESB and NetBeans. But another effort is undergo to let the developers to download one single installer for each component and let the installer install all required artifacts like shared libraries, runtime engines and design time NetBeans modules. Latest build of installers for all components are available at http://download.java.net/jbi/binaries/installers/single-component/v2/nightly/latest/.

Installing the components using the installers available at the above page is very straight forward. the installer asks for NetBeans and OpenESB (GlassFish) directory and complete the installation.

5 Summary

In this article we discussed almost all basics of OpenESB administration and application development in a crush course mode. We saw how JBI and OpenESB are related, how OpenESB and GlassFish ESB are similar products with different naming. We developed a sample JBI service assembly which utilizing several binding components and service engines and finally we deployed the application into OpenESB and performed functional testing using NetBeans IDE.

We discussed how we can install and administrate OpenESB. We discussed CLI and administration console for managing OpenESB and we learned that OpenESB administration channels uses similar rules and look and feel that GlassFish administration and CLI uses.

Introducing NIO.2 (JSR 203) Part 1: What are new features?

I will write a series of blog to discuss what are the new features introduced in NIO.2 (JSR 203). The NIO.2 implementation is a part of OpenJDK project and we can alreay use it by downloading a copy of OpenJDK binary.  In the first entry I will just go through what are these new I/O features of Java 7, which help developer iron out better applications easier.

Talking about File systems support and features which let us  deal with file system we can name the following features:

  1. Platform friendly-ness of NIO.2: We can deal with all file systems in a unified model.
  2. File tree walk: We can walk on a file tree and examine each node using the built-in APIs, NIO.2 to let us know whether the current member is a file, a directory or a symbolic link. We can then perform any operation we want on that node.
  3. File Operations (Copy, Delete, Move): Basic operations are supported with plethora of options. The move operation can be performed in atomic way.
  4. Symbolic links support: count soft and hard links as well as managing them.
  5. Support for file attributes in NIO.2: Managing file systems attributes is fully supported for different file systems including DOS, POSIX…
  6. File system change notification: We can setup a watch service and receive notification when a change happens on the path we are watching.
  7. SPI for providing new file systems support, for example to support zip, zfs, btrfs, we can implement the provider interfaces and use the unified API to access that specific file system using our implementation

Working with sockets and reding/ writing files we can name the following features:

  1. Multicasting is now supported in the DatagramChannel meaning that we can send and receive IP datagrams from a complete group. Both IPv4 and IPv6 are supported.
  2. Asynchronous I/O for sockets and Files: Now we can have Asynchronous read and write both on channles and files. It basically means we can have event driven I/O over both networks and files.

Other improvement, features:

  1. Support for very large multi gigabyte buffers
  2. Some MXBeans are included to monitor IO specific buffers.
  3. Interoperability between Java 7 IO and previous versions using the Path API.

I will post sample codes for each of these features in upcomming entries. So stay tuned if you want to learn more about NIO.2

May 20th, 2010 | Filed under Java, Java SE, Learning

GlassFish Security book FAQ 1: Custom Security Realm in GlassFish

I decided to write down the answer for some questions which my book’s readers email me or ask me via twitter in my weblog so everyone can benefit from the answers. Here is the answer to the first question which involves custom security realms.

GlassFish supports 5 types of security realms out of the box which are sd follow:

  1. File Realm: Usefull for development and testing purposes. GlassFish provids a user/ group management interface for this realm. We can add user and groups using the administration console. When using this realm all usernames, passwords and groups are stored in a plain text file.
  2. JDBC Realm: In production environment we store user information including but not limited to username, passwords and groups in an RDBMS and then configure a JDBC realm to authenticate the given credentials againts the information stored in the datase.
  3. LDAP Realm: Sometimes we have all user details stored in an LDAP like Active Directory or Redhat Directory Server, OpenDS or Sun Java System Directory Server Enterprise Edition.
  4. Solaris Realm: This realm is used to authenticate users with a Solaris user directory.
  5. Certificate Realm: The certificate realm allows us to conduct mutual SSL authentication based on the client certificates.

Sometimes our users information is stored in a silo different than all of this mentioned storages and we need to use that source for authentication and access control. For example assume that we have our users information including username, passwords and group membership stored in an Object Database and we need to authenticate our enterprise application’s users with that storage. In such times we should either think about having a synchronized RDMBS keeping update user information and use JDBC realm for authentication and authorization or we should develop  a custom security realm which uses the object database as a source for authentication.

Setting up synchronization between the e.g object database and RDBS can be tricky while developing a custom authentication realm is much easier using GlassFish provided SPIs.

Second chapter of GlassFish security book discusses GlassFish security realms in details and discuss a sample application which uses these realms for authenticating and authorizing users. In the same chapter, developing custom security realms is discussed along with developing a sample realm.

In the same chapter GlassFish support for  JSR-196 (Java Authentication Service Provider Interface for Containers) is discussed to complete the ring of authentication and authorization in Java EE in general and GlassFish application server in particular.

Java EE Security Refcard is now available for download at no cost.

Java EE Security refcard is available for download. This refcard covers Java EE 6 security and discuss how each application server supports the specs. The refcard covers authentication, authorization, and transport security in Web Application, EJB application and web services by introducing the concept and the related annotations and deployment descriptors which help us realize the concept.

GlassFish, Geronimo and JBoss are discussed in the refcard to show how we can use the vendor specific deployent descriptors for implementing the security design of our applications.

Following list shows how what are covered in this.

  • Security in Java EE applications
  • Authentication an Authorization in Java EE
  • Web Applications Security
    • Authentication and Authorization in Web Module
    • Enforcing Transport Security
    • Other Security Elements of Web application deployment descriptors
    • Using Annotations to enforce security in Web modules
    • Programmatic Security in Web Module
  • EJB Applications Security
    • EJB module deployment descriptors
    • Security Annotation of EJB modules in Java EE 6
    • Securing EJB Modules programmatically
  • Application Client Security
    • Security enforcement in Geronimo ACC
    • Security enforcement in JBoss ACC
  • Defining Security in Enterprise application level
  • Securing Web Services in Java EE

  • Web Services Security in Web Modules
  • Web Services Security in EJB Modules
  • Web Services Authentication in GlassFish
  • Web Services Authentication in Geronimo
  • Web Services Authentication in JBoss

The refcard comes with 4 figures showing relation between different element and components in Java EE  along with 7 tables explaning the deployment descriptors elements and security annotations. For most of the above headings you will find sample code included in the refcard showing how we can do implement the discussed functionality according to Java EE and mentioned application Servers.

GlassFish v3 and EJBCA 3.x a fair couple for mutual SSL authentication.

Please use the following articles while I am updating this entry

  1. How to have your Own CA and configure Glassfish and your clients for mutual authentication?
  2. How to have your Own CA and configure Glassfish and your clients for mutual authentication?, Part II

Please post any comment or question here so we can have one main reference for this.

GlassFish Security Book Which Covers GlassFish v3 security, Java EE 6 security, and OpenSSO has just been published.

The Book in Details:

Security was, is, and will be one of the most important aspects of Enterprise Applications and one of the most challenging areas for architects, developers, and administrators. It is mandatory for Java EE application developers to secure their enterprise applications using Glassfish security features.

Learn to secure Java EE artifacts (like Servlets and EJB methods), configure and use GlassFish JAAS modules, and establish environment and network security using this practical guide filled with examples. One of the things you will love about this book is that it covers the advantages of protecting application servers and web service providers using OpenSSO.

The book starts by introducing Java EE security in Web, EJB, and Application Client modules. Then it introduces the Security Realms provided in GlassFish, which developers and administrators can use to complete the authentication and authorization setup. In the next step, we develop a completely secure Java EE application with Web, EJB, and Application Client modules.

The next part includes a detailed and practical guide to setting up, configuring, and extending GlassFish security. This part covers everything an administrator needs to know about GlassFish security, starting from installation and operating environment security, listeners and password security, through policy enforcement, to auditing and developing new auditing modules.

Before starting the third major part of the book, we have a chapter on OpenDS discussing how to install, and administrate OpenDS. The chapter covers importing and exporting data, setting up replications, backup and recovery and finally developing LDAP based solutions using OpenDS and Java.

Finally the third part starts by introducing OpenSSO and continues with guiding you through OpenSSO features, installation, configuration and how you can use it to secure Java EE applications in general and web services in particular.

Inspired from real development cases, this practical guide shows you how to secure a GlassFish installation and how to develop applications with secure authentication based on GlassFish, Java EE, and OpenSSO capabilities.

What you will learn from this book :

  • Develop secure Java EE applications including Web, EJB, and Application client modules.
  • Reuse the security assets you have by learning GlassFish security realms in great details along with the sample for each realm.
  • Secure GlassFish installation including operating system security and JVM policy configuration.
  • Secure Java EE applications using OpenSSO and set up Single Sign-On (SSO) between multiple applications.
  • Secure web services using Java EE built-in features, OpenSSO and WS-Security.
  • Secure network listeners and passwords using GlassFish provided facilities.
  • Learn using OpenSSO services, SDKs, and agents to secure Java EE enterprise applications including Web Services.
  • Learn using OpenDS both as administrator and as an LDAP solution developer.
  • All command lines and more than 90% of the book content applies for both GlassFish 3.x and 2.x.

Approach

Security is driven by requirement and design and we implement security on the basis of the requirements provided by analysts. In this book, we take a programmatic approach to understand Java EE and GlassFish security.

You will find plenty of code samples in this book. It is easy to secure your application when you have a demonstration of a complete and working application explained in the book, isn’t it? Each chapter starts with the importance and relevance of the topic by introducing some Java EE applications requirement, which will encourage you to read it further.

Who this book is written for

This book is for application designers, developers and administrators who work with GlassFish and are keen to understand Java EE and GlassFish security.

To take full advantage of this book, you need to be familiar with Java EE and GlassFish application servers. You will love this book if you are looking for a book that covers Java EE security and using GlassFish features to create secure Java EE applications, or to secure the GlassFish installation and operating environment and using OpenSSO.

var gaJsHost

Learning GlassFish v3 Command Line Administration Interface (CLI)

Learning GlassFish v3 Command Line Administration Interface (CLI)

Terminals and consoles was one of the earliest types of communication interfaces between a system administrator and the system administration layer. Due to this long time presence,  command line administration consoles become one the most utilized administration channel for configuring different software ranging from database engines to router’s embedded operating systems.

GlassFish provides several administration channels; one of them is the command line administration interface or CLI from now on.  The CLI has many unique features which make it very convenient for command line advocates and new administrators which like to get familiar with CLI and use it in the daily basis.  The CLI allows us to manage, administrate, and monitor any resources which application server exposes to the administrators. So we can perform all of our administration tasks just by firing up a terminal, navigating to glassfish bin directory and executing the asadmin script which is either a shell script in UNIX based operating systems or a batch file in Windows operating system.

The CLI has some degree of embedded intelligence which helps us to simply find the correct spelling and similar commands to the command or phrase that we try. Therefore with basic knowledge of GlassFish application server administration we can find out the command that we need and proceed with the task list which we have in front.

1 The CLI environment

CLI is an administration interface which let administrators and developers to change configurations like changing a listener port; performing life cycle related tasks like deploying a Web application, or creating a new domain; monitoring different aspects of the application server; and finally performing maintenance duties like creating backup from the domain configuration, preparing maintenance reports and so on.

Door to the CLI interface is a script which is place in glassfish_home/bin directory. For Linux and UNIX platforms it is a shell script named asadmin and for the Windows platform it is a batch file named asadmin.bat. So, before we start doing anything with the CLI interface we need to either have glassfish_home/bin in the system path or we should be in the same directory which the script resides.

Add glassfish_home/bin to operating system path

We can add glassfish_home/bin to windows operating system path by using the following procedure. You should have the glassfish_home variable already defined, if not you can replace %glassfish_home% with the full path to glassfish installation directory.

  • Right click on My Computer icon and select properties item
  • Select advanced tab in the from the tab set
  • Click on environment variables button, you will see two set of variables one for user and one for the system. I suggest you choose the user space to add your variable or update the currently defined variable.
  • If you can not find path in the list of variables, create a new variable named path and sets its value to %glassfish_home%/bin. If the variable is present then add ;glassfish_home/bin to the end of the variable’s value.

Close all cmd windows and open a new one to have the new path applied

And for UNIX and Linux machines, we can add it to operating system path by using the following procedure. Replace “${glassfish_home}” with the full installation of Glassfish.

Open a text editor like ktext, gedit or any editor which you are familiar with

Open ~/.bashrc file using the file menu

At the end of the file (last line) add export PATH=”${glassfish_home}”/bin:”${PATH}”

Close all terminals and fire up a new terminal console to have the effects applied

Info

We can execute the asadmin.bat in windows by calling asadmin.bat or asadmin in a cmd windows. We should be either in the bin directory or we should have the script in path.

For Linux and UNIX, if we have the script in path we can call asadmin in a terminal window, if we do not have it in the path then we should be in the bin directory and execute it by typing ./asadmin in the terminal window.

Info

In this article I will use an operating system natural syntax, for example I will use asadmin version which can be interpreted as asadmin.bat version  in windows or ./asadmin version in UNIX or the asadmin version itself when we have asadmin in our path.

2 Getting started with CLI

2.1 The commands format

The asadmin script is the door to GlassFish command line interface and all of its commands follow a de-facto naming convention and a standard format which we need to remember. All command names are self explaining and we can understand the command purpose from the command name. All of the asadmin commands use one or multiple words as the command name to completely explain the command purpose. These words which form the command name are separated using a dash (-).

The naming convention also provides another learning point about the asadmin commands. Commands are categorized into lifecycle management commands, configuration commands, listing commands and monitoring commands. Each command starts with a verb which determines the command nature, for example: create, delete, update, list, and configure are the starting words for many of asadmin commands.  The command syntax is shown in the following snippet.

command-name options operands

The command-name can be start-domain, stop-domain, and so on. The options are parameters which affects the command execution, for example the domain instance port. the JDBC connection pool data source class name and so on.  The operand are usually name of the resources which the command may affect, like name of the connection pool that we want to create, name of the domain which we want to start and so on.

2.2 The asadmin operating modes

The asadmin utility which we use to execute our administrative commands operates in two modes. Each mode is suitable for specific set of tasks and has its own characteristics when it comes to performance and productivity.

Headless operating mode

In the headless mode which is very suitable for writing scripts  we call the asadmin  utility and pass the command name along with its options and operands. The asadmin utility launches a JVM and execute the command. The result of the command will be either 0 as failure or 1 as a success. An example of this mode is similar to the following script:

asadmin version

This will simply execute the version command which shows the application server version. To get help for a command in this mode we can use asadmin help version or we can use asadmin version –help.

Multimodes operating mode

This operating mode let use execute multiple commands in one JVM instance, therefore it is faster for executing commands. This execution mode is not suitable for script developers as we should execute the commands in asadmin environment and not in the shell command line.

To execute a command in this mode we should enter the asadmin environment and then enter our commands along with options and operands. For example:

asadmin  A

asadmin> version --help B

A: Hit enter

B: Command name with parameters

The asadmin utility is an operating system native shell script which wrap around the actual Java application responsible for executing the administration commands which we issue. Later on we will see how this script can fall useful for administrating some domains from a system which is behind a proxy.

2.3 Local commands

Two sets of commands are present in asadmin which help administrators perform variety of tasks. Local commands are a set of commands which either affects the environment which application server is running or it needs accessing the application server environment locally to execute some scripts or batch files to perform a job.

A good example of local commands is domain lifecycle management commands which include creating a new domain, deleting a currently available domain, or starting a domain. All of these commands need to either access the application server installation directory layout or need to run a script on the target machine to perform the task.

Another place which we can discuss the local commands is the Java DB copy included with the GlassFish application server installation bundle. The following command start the database on the local machine. The command starts the database by creating another Java process directly by using the operating system shell.

asadmin start-database

You may wonder why this command has not options or operands. Generally all GlassFish administration commands need the minimum possible options and operands to perform the task when we use default setting and configuration.

Each command has its own set of parameters but most of the asadmin commands, either local or remote, have some shared parameters which are listed in table 1. Command’s parameters can have a default value which will be used if we do not specify it. The default value for each parameter is underlined.

Table 1 List of shared parameters between local and remote commands

Parameter

Acceptable values

Description

–terse or –t

false, true

Indicates that any output data  must  be  very  concise

–echo, -e

true, false

If set to true, the command-line statement is echoed on the standard output.

–interactive, -I

true, false

If set to true, only the required password options are prompted.

–passwordfile

Path to the password file

We will discuss it in section 5 of this article

–user, -u

No default value

A user with administrative privilege on target domain.

These parameters have no effect on the command execution but they just change the way that the command shows us the information and how we interact with the commands.

2.4 Remote commands

In the Opposite side of the local commands we have remote commands which form a set of commands that affects the running application server instance configuration and access the application server environment and file system using an application deployed in the application server itself. Therefore the target instance should be running and there should be a network route between the administration workstation and the GlassFish instance running on the server machine.

When we execute a remote command we should let the asadmin know where the target application server instance is running and what the instance administration port is.  The asadmin uses this information along with the authentication information to communicate with the application server over HTTP or HTTPs using a REST like URL pattern for commands and parameters. Figure 1 demonstrates the remote and local commands.

Figure 1 The asadmin utility communication with remote and local GlassFish domain and installation

In figure 1 you can see that in the running GlassFish instance there is an application deployed under /__asadmin/ context and listens for incoming asadmin commands. This application is listening on admin listener which is by default uses port number 4848.

Listing 1 shows a sample command content when it is heading toward the application server. It should have already flashed a light in your head about the RESTful Web services development articles or books that you have already read.

Listing 1 content of HTTP request for version command

GET /__asadmin/version HTTP/1.1

Content-type: application/octet-stream

Connection: Keep-Alive

Authorization: Basic YWRtaW46YWRtaW5hZG1pbg==

User-Agent: hk2-agent     #A

Cache-Control: no-cache

Pragma: no-cache

Host: localhost:4848

Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

#A The asadmin’s agent name

Listing 2 shows the response generated by application server for version command. As you can see, the response is plain and simple.

Listing 2 response generated by application server for version command

HTTP/1.1 200 OK

Content-Type: text/html

Transfer-Encoding: chunked

Date: Mon, 12 Jan 2009 19:26:01 GMT

Signature-Version: 1.0

message: GlassFish v3 Prelude (build b28c)

exit-code: SUCCESS #A

If you are thinking that trying URLs in your browser will result in some output, you are completely right. For example if you try browsing http://127.0.0.1:4848/__asadmin/uptime you will get a result page similar to figure 2.

Figure 2 Using browsers to run asadmin commands and view the result in browser

Now you may have some questions about how a command can generate an HTML oriented output in the browser while it can generates a plain text output when we use asadmin to execute the same command. The answer can be found in the way that browser identifies itself and asadmin utility identifies. The asadmin utility uses hk2-agent as the agent name and asadmin web application respond to this types of agent with a plain text response while it provides a full readable html for other agent types.

The only time that we feel difference between these two sets of commands is when we try to execute a local command on a remote machine.  For example creating a domain on a remote machine is not possible unless we have a node agent installed on that machine and we are using DAS to control that machine.

A good example of remote commands is application deployment command. We can deploy an application archive like an EAR or WAR file using asadmin. The deployment command will upload the file to the server and server takes care of the deployment. Following command will deploy the gia.war to the default glassfish instance.

asadmin deploy gia.war

The deploy commands has several parameters, we will discuss these parameters in details in subsequent sections. You may have already asked yourself how we identify which domain we want to execute a command against. Your answer is behind some shared parameters between all remote commands to distinguish the target domain which the command affects. These parameters are listed in table 2 along with the description and default values.

Table 2 List of all shared parameters between remote commands

Parameter

Default values

Description

–host, -H

localhost

when no value is determine for this parameter, the asadmin utility will try to communicate with localhost

–port, -p

4848

when no value is determine for this parameter, the asadmin utility will try to communicate with the determined host on port 4848

–secure, -s

false

If we have our asadmin application on a secure listener then we will use this parameter to prevent any security breach.

All of these default parameters value’s assumption allows us to have more compact, easy to write and understand commands. Based on the connate of this table we can say that the sample deploy command will deploy the application into a domain running on localhost with port 4848 assigned to its admin listener.

3 Performing common tasks with CLI

Application server administration is composed of some common tasks which deal with common concepts of Java EE application servers like domain administration, application lifecycle administration, and managed resources administration. Along with these common tasks there are many other tasks which might be common between application servers or not. These tasks includes listeners administration, resource adapter administration, application server security administration which includes both application server security and Java EE related security definitions, virtual servers administration, monitoring and so on. In this section we will discuss the common administration tasks.

3.1 Domain lifecycle administration

Domains are foundation of GlassFish application server instances; each domain is an independent instance of application server which uses the same application server installation and hardware resources. Domain lifecycle administration covers creating, starting, stopping, configuration backup, deleting the domain, and domain configuration recovery using previously created backups.

Creating a new domain

Creating a new domain is fairly simple when you know what attributes distinguishes one domain from another. A sample command which creates a domain is as follow:

create-domain --user admin --adminport 4747  --domaindir /opt/dev/apps/domains/GiADomain --profile developer --instanceport 8282 --domainproperties jms.port=8687 --savemasterpassword=true --passwordfile=/opt/dev/apps/passfile.txt  --savelogin=true GiADomain

This is a sample of create-domain command with most of the applicable parameters. We are using –adminport to determine the admin port, –domaindir let us create the domain in none default path like what we used instead of glassfish_home/domains which is the default directory. The –instanceport let us determine the port that default application listener uses. Some of the domain properties like JMS port, JMX port and so on can be determined using the –domainproperties parameter. All parameters are self describing except for following three parameters which you need to understand them thoroughly.

  • The –savemasterpassword parameter: Setting this option to true asks the domain creating process to save the master password into a file and facilitate the unattended (headless) domain startup. We will discuss this password in more details in section 4 of this article. For now just remember that default value for master password is changeit. I am sure that value of the password is talking for the importance of changing it.
  • The –passwordfile parameter: The asadmin utility policy encourages the administrators not to enter the password in the console and instead use a file which includes the required password. During the domain Creating two passwords are required which are domain administration password and master password. To avoid typing the passwords we can store them in a plain text file similar to the following snippet and pass it to any command that we execute instead of typing the passwords in an interactive way.

AS_ADMIN_PASSWORD=adminadmin

AS_ADMIN_MASTERPASSWORD=changeit

The file content is in properties file format and can be created using any text editor. If we do not use the –passwordfile parameter and a password file containing the passwords, the asadmin utility will asks for passwords interactively.

  • The –savelogin parameter: We will discuss automatic login with more details in section 4 of this article, but to be brief, this parameter make it possible to execute our commands on different domains without providing username and password on every command execution.

Starting and stopping a domain

We can start a domain using the start-domain command. An example of starting a domain is similar to the following snippet.

start-domain --debug=true  --verbose=true --user admin --passwordfile=/opt/dev/apps/passfile.txt

--domaindir= /opt/dev/apps/domains/  GiADomain

Although the command can be as simple as start-domain domain1 but that is for occasions when we are using all of the default values for any parameter and no customization has happened during the time which we create the domain. The –debug=true means that domain is started in debug mode and we can attach our debugger to the running instance. The –verbose=true means that we want to see all messages that application server emits during the startup; it is useful to catch errors and troubleshoot. The –passwordfile parameter lift the need to enter the admin and master passwords. The file content is similar to password file we used during the domain creation. And finally we need to determine where the domain resides if we create the domain in a non-standard location.

To stop a domain we can use a command similar to the following snippet which is fairly simple.

stop-domain  --domaindir= /opt/dev/apps/domains/ GiADomain

We just need to provide the path to the directory which contains the domain. The only applicable shared parameters are the items that we used. None of the other shared parameters is applicable in this command.

Domain utility commands

There are two utility commands for domain administration. The first command lists all of the domains which reside in the given directory along with the domain status indicating whether the domain is running or not. And the second command checks the structure of domain.xml file.

list-domains --domaindir=/opt/dev/apps/domains/

verify-domain-xml  --verbose=true --domaindir= /opt/dev/apps/domains/  GiADomain

The verify-domain-xml is very useful when we edit the domain.xml file manually.

Domain configuration backup and recovery

Yes, we can backup a domain configuration and later on restore that backup if we messed up with the domain configuration. Each backup file is an archive which contains description files and vital domain configuration files including domain.xml. By default all backups are placed inside a directory named backups which resides inside the domain directory. The backup file names follow a pattern similar to sjsas_backup_v00001.zip which means that it is the first backup of this domain. To create a backup a command similar to the following snippet will do the trick.

backup-domain --description "backup made for glassfish in action book" --domaindir /opt/dev/apps/domains/ GiADomain

After some times we will have several backup archives for each of our domains, we will need a command to get a list of all available backups or backups related to one single domain. To get list of backups for a single domain we can use:

list-backups --domaindir /opt/dev/apps/domains/ GiADomain

Or to get a list of all backups of all domains in the default domains directory we can use list-backups command alone with no parameters.

Now that we can list the available backups for each domain we need command which allows us to restore a domain. To restore a domain to one of its previous backups we should stop the domain and then use the restore command which is similar to:

restore-domain --domaindir /opt/dev/apps/domains/ --filename sjsas_backup_v00001.zip GiADomain

The command will simply pick up the backup archive and restore the given domain using its content.

Deleting a domain

We should deal with this command very carefully as it will delete the domain directory with all of its content including backups, deployed applications, configuration files and so on. To delete a domain we can use delete-domain command as follow to delete our GiADomain domain.

delete-domaind --domaindir=/opt/dev/apps/domains/ GiADomain

Domain management is the most basic task related to application server administration. Every asadmin command including domain administration commands has manual pages included in the asadmin commands package and accessible using asadmin utility. An example of getting help for create-domain command is similar to:

asadmin help create-domain

You can see complete list of parameters and their associated values for each of the discussed command using the help command. All of the domain administration commands are local commands. We can use list-commands command to see the list of all available commands in both remote and local categories.

3.2 Applications lifecycle administration’

Applications including web, enterprise, and resource adapter, and so on are our bits inside the application server which our clients relay on to get the required services. Applications can be deployed from command line in a very effective and customizable manner. Like all other administration commands application deployment is a single parameter command when we want to use the default parameters.

Deploying and un-deploying application

To deploy an application independently from its type (WAR, EAR, RAR, and so on) we can use deploy command. The command which is one of the most basic remote commands deploys any kind of application known to the GlassFish application server to its dedicated container. The command has many options which are omitted to show the common use case. The GlassFish instance should be up and running to use deploy or any other remote command.

deploy   --host  127.0.0.1 --port 4747  --user  admin –name aName --contextroot cRoot --upload=true --dbvendorname derby --createtables=true  /home/masoud/GiA.ear

Deploying a web application using default parameters is as simple as passing the archive to the deploy command. The context name will be same as the archive file.

deploy GiA.war

We can remove an application using the undeploy command. The command will remove the application bits from the application server directories along with removing it from the list of known applications in the domain.xml file. Following snippet shows how we can use it.

undeploy  --droptables=true aName

The undeply command uses the application name to remove it from the application server; we have the liberty to drop the automatically created tables (for enterprise applications) automatically. Deploying and undeploying other application types is similar to enterprise application deployment. You can view the complete list of parameters by executing deploy with no parameter or you can view the complete help content by using help deploy command.

Application utility commands

For domains with developer profile we have only one utility command named list-applications which list the deployed applications. In addition to all shared parameter this command has one important parameter named –type which accepts application,    connector, ejb, jruby, and web as its value. Following command will list all web applications deployed in out domain.

list-applications --type=web

You can see all commands related to application administration by trying asadmin application which will show all commands which has application word in the command name.

3.3 Application server managed resources

Dealing with managed resources is one of the most recurring tasks which an administrator faces during the application deployment and development. The most important types of managed resources are JDBC and JMS resources which we will discuss in this section.

JDBC connection pool administration

A JDBC connection pool is a group of reusable connections for a particular database. Because creating each new physical connection is time consuming, the server maintains a pool of available connections to increase performance. When an application requests a connection, it obtains one from the pool and when the application closes the connection, the connection is returned to the pool instead of being closed. To create a JDBC connection pool we can use create-jdbc-connection-pool command.

create-jdbc-connection-pool --user admin

--passwordfile=/opt/dev/apps/passfile.txt  --host localhost --port 4747

–datasourceclassname org.apache.derby.jdbc.ClientDataSource –restype javax.sql.XADataSource

--property portNumber=1527:password=APP:user=APP:serverName=

localhost:databaseName=GiADatabase:create=true GiA_Derby_Pool

The command may looks scary at the beginning but if you take a closer look you can see that all of the parameters and values are well known for you. We ca delete a JDBC connection pool using delete-jdbc-connection-pool which in addition to shared parameters accept an operand which is the name of the connection pool which we want to delete

Now that we have a connection pool we need a reference to the connection pool in the JNDI tree to ensure that our applications can access the connection pool through the application server.

JDBC resources administration

A JDBC resource or a data source is the mediator between application and the connection pool by providing a JNDI name to access the connection pool. Multiple JDBC resources can specify a single connection pool.

create-jdbc-resource –user admin –port 4747 –host localhost –passwordfile=/opt/dev/apps/passfile.txt

--connectionpoolid GiA_Derby_Pool jdbc/GiAPool

We determined a name for our JDBC connection pool when we create the pool. And when we want to create the data source we use that name to identity the JDBC connection pool we want to specify in the JDBC resource.

We can delete a JDBC resource using delete-jdbc-resource which in addition to shared parameters accepts an operand which is name of the connection pool that we want to delete.

JMS Destination administration

In enterprise applications, asynchronous communication is one of the in-evitable requirements. JMS destinations are virtually places which each message are headed to. JMS clients are listening on the same destinations to receive these messages. We can create a JMS destination either a Queue or Topic by create-jmsdest command.

create-jmsdest --user admin --passwordfile=/opt/dev/apps/passfile.txt --host localhost --port 4747 --desttype queue  --property User=public:Password=public GiAQueue

We can create a JMS topic by changing the value of –desttype parameter to topic. To delete a JMS destination we can use delete-jmsdest command which accept the name of destination which we want to delete as an operand. For example the following command will delete the JMS queue which we create in previous step.
delete-jmsdest GiAQueue

Make sure that you create the above queue again as we will need it in the next steps.

JMS resources administration

JMS connection factories are door to consuming and producing JMS messages. We need to define these factories prior to be able to access a JMS destination. To create a JMS connection factory we can use creste-jms-resource command. For example:

create-jms-resource --user admin --passwordfile=/opt/dev/apps/passfile.txt  --host localhost --port 4747  --restype javax.jms.QueueConnectionFactory --property ClientId=MyID:UserName=guest:Password=guest jms/GiAQueueConnectionFactory

Our sample command creates a connection factory which provides us with queue connections. When we need to interact with a JMS topic we can change the –restype parameter to javax.jms.TopicConnectionFactory.

Deleting a JMS resource is possible by using delete-jms-resource command which takes the resource name which we want to delete as a parameter in addition to the shared parameters.

Utility commands

There are several utility commands related to manage resources, table 3 shows these commands along with a sample and description.

Table 3 Some asadmin utility commands for administering managed resources

Command

Sample

Description

flush-jmsdest

flush-jmsdest GiAQueue*

purges the messages in a JMS destination

jms-ping

jms-ping

checks to see if the JMS provider is running, the command can ping cluster wide configurations

list-jms-resources

ist-jms-resources –restype javax.jms.TopicConnectionFactory

List all JMS resources

list-jmsdest

list-jmsdest

List all JMS destinations

list-jdbc-connection-pools

list-jdbc-connection-pools

List all JDBC connection pools

list-jdbc-resources

list-jdbc-resources

List all JDBC data sources

*I removed all shared parameters to fit the commands in the table.

The asadmin utility has a very rich set of commands for administrating the managed resources. We learned basic commands here.

3 Monitoring with CLI

Monitoring is an integral part of the administrators daily task list. Monitoring helps us to: find possible problems, detect performance bottlenecks, find system resource shortage, plan system capacity or upgrade, and finally monitor the daily performance of the system. The GlassFish application server infrastructure allows us to monitor almost any object which corresponds to a Java EE concept. For example we can monitor an HTTP listener, a Servlet, or a JDBC connection pool.

To monitor an object, system should gather statistics about that object and this statistics gathering has some overhead even in ideal software as more byte codes should be executed to gather the statistics. Based on the fact that GlassFish application server should be well tuned out of the box, all monitoring functionalities are turned off to prevent any extra overhead during the system work hours.

GlassFish provides 3 monitoring level for any object available for monitoring. These levels include:

  • OFF: No monitoring information is gathered
  • LOW: Only object’s attributes changes are monitored
  • HIGH: In addition to attributes methods execution is counted

The asadmin utility provides multiple ways for getting statistical data from the application server core. Multiple commands are introduced to facilitate our job in viewing this statistical information. These commands include:

  • The monitor command: We can use this command to view common statistical information about different application server services, we can filter the statistics for only on monitor-able object in the service or we can view cumulative statistical information about all objects in that particular service. For example all JDBC connection pools or just one single JDBC connection pool statistics can be viewed using the monitor command.
  • The list command: We can use this command to get the hierarchic of all monitor-able and configuration objects or specific type of objects like JDBC connection pools. The list command has an important boolean parameter named monitor which determine whether we want to see monitor-able objects or configuration objects.
  • The set command: We can use this command to change the monitoring level of a monitor-able object. And in broader view, We can use it to change application server configuration by changing the attributes of configuration objects.
  • The get command: We can get customized monitoring information about different attributes of different monitor-able objects. In broader view, we can use this command to view value of any configuration object’s attributes.

3.1 Dotted names

All monitor-able and configuration objects shape a tree composed of these objects and their children objects. The children objects have attributes which are either the monitoring factor or configuration elements. Objects in the tree are separated using a dot and therefore we can simply navigate from the root object to any of lower level child objects. For example if we execute list –monitor=true server we will get a list of all monitor-able objects which are direct child of server objects. The list can be similar to the following snippet.

server.applications

server.connector-service

server.http-service

server.jms-service

server.jvm

server.orb

server.resources

server.thread-pools

server.transaction-service

After getting the high level child we can go deeper toward leaf nodes by listing the immediate or related children of any top level object. For example to get immediate children or http-service object we can use list –monitor=true server.http-service to show all immediate children of http-service object which can result in an output similar to:

server.http-service.__asadmin

server.http-service.connection-queue

server.http-service.file-cache

server.http-service.keep-alive

server.http-service.pwc-thread-pool

server.http-service.server

We can further do down and monitor any monitor-able object in the application server. We can use list –monitor=true server.http-service.* to view a recursive list of immediate children and children of those immediate children. We use * with list command as a place holder for any part of the dotted name. For example we can use server.jvm.* or server.resource* to get all children of server.jvm or all children which starts with resource.

The dotted names are not provided for sole monitoring purposes, we can use them to view and change the configuration of application server by using the asadmin utility. We can get list of configurable objects by omitting the –monitor=true parameter from the list command.

Enabling the GlassFish monitoring

GlassFish monitoring is turned off when we install the application server, we need to enable the monitoring system to gather statistical information for us. To do so, we can use set command to change the monitoring level for one or all of the GlassFish services like JDBC connection pool, HTTP listener, and so on.  But before changing the monitoring level from OFF to HIGH we can check and see the current level by using a simple get command similar to the following snippet.

get server.monitoring-service.module-monitoring-levels.*

Executing this snippet shows us a result similar to the following snippet which means that monitoring is OFF for all services.

server.monitoring-service.module-monitoring-levels.connector-service=OFF

server.monitoring-service.module-monitoring-levels.ejb-container=OFF

server.monitoring-service.module-monitoring-levels.http-service=OFF

server.monitoring-service.module-monitoring-levels.jdbc-connection-pool=OFF

server.monitoring-service.module-monitoring-levels.jms-service=OFF

server.monitoring-service.module-monitoring-levels.jvm=OFF

server.monitoring-service.module-monitoring-levels.orb=OFF

server.monitoring-service.module-monitoring-levels.thread-pool=OFF

server.monitoring-service.module-monitoring-levels.transaction-service=OFF

server.monitoring-service.module-monitoring-levels.web-container=OFF

We can enable the monitoring for JDBC connection pools by using set command as follow:

Set server.monitoring-service.module-monitoring-levels.jdbc-connection-pool=HIGH

Now we are sure that any activity involving any of the JDBC connection pool will be monitored and its statistical information will be available for us to view and analyze.

3.2 The monitor command

Using monitor command is the simplest way to view monitoring information about GlassFish application server. Following snippet shows the monitor command syntax. I have not included the shared parameters to make it easier to read and see the command specific parameters.

monitor –type  monitor_type [--filename file_name] [--interval interval]

[--filter filter_name]   instance_name

We can save the command output to CSV files using the –filename parameter and we can determine the interval which the command uses to retrieve the statistics by using the –interval parameter. The instance_name argument let us use this command on a DAS to retrieve the statistics related to one of the DAS member instances. Two other parameters determine what service and which object in the service we want to monitor. Most important acceptable values for –type parameter is listed in table 4 along with related description.

Table 4 acceptable values for the monitor command’s type parameter

Value

Description

statefulsession

Statistics related to State full Session Beans

statelesssession

Statistics related to Stateless Session Beans

connectorpool

JCA connector pool statistics

endpoint

Web services end point statistics

entitybean

Entity Beans statistics

filecache

GlassFish HTTP level cache system statistics

httplistener

HTT listener statistics

httpservice

HTTP service statistics

jdbcpool

JDBC connection pool statistics

jvm

Underlying JVM statistics

servlet

Servlet statistics

You can see an example monitoring command to monitor our newly created JDBC connection pool in the following snippet.

monitor –type jdbcpool –interval 10 –filter GiA_Derby_Pool server

We just want to view the statistics related to one JDBC connection pool on the default instance. The interval for retrieving the statistics is 10 seconds. The output for this command is very similar to figure 3.

Figure 3 Outputs for monitoring GiA_Derby_Pool JDBC connection pool using monitor command

Monitoring results are categorized under some column and for each column we have several statistic factors like highest number of free connections, and current number of free connections. Next service which we want to monitor is the application server runtime or the JVM instance that our application server is running on. To monitor the JVM we can use a command similar to the following snippet.

monitor –type jvm –interval 1 server

Command output is similar to figure 4 which shows almost no changes in heap size during the monitoring period.

Figure 4 outputs for JVM monitoring using the monitor command

The monitor command combined with LOW monitoring level is very useful when we need to get an overview of different GlassFish services in production environment.

3.3 Monitoring and configuration by get and set commands

Explain more about get and set commands

Monitoring a JDBC connection pool

Now we want to use these set of four commands to monitor our newly created JDBC connection pool.

get --monitor=true server.resources.GiA_Derby_Pool.*

This command will return a handful set of statistical information about our connection pool. Although we can change the command in order to get only one of the connection pool attributes instead of complete statistical set. To get number of free connections in our JDBC pool we can use the following command

get --monitor=true  server.resources.DerbyPool.numconnfree-current

We can use get to view the configuration attributes of any configurable object in the application server. If we try to use get without –monitor=true, we should give try to view a configuration attribute instead of a monitoring attribute. For example to view the maximum pool size for our connection pool we can use the following command:

get server.resources.jdbc-connection-pool.DerbyPool.max-pool-size

We can use set command alongside with get command to change the configuration parameters using the dotted names and asadmin utility.

set server.resources.jdbc-connection-pool.DerbyPool.max-pool-size=64

It is very simple and effective to get detailed monitoring information out of the application server to catch up with performance related issues.

4 CLI security

The CLI is our means to administrate the application server. As well as it can be very useful for daily tasks it can be catastrophic if we fail to protect it well from the unauthorized access.

4.1 The asadmin related credentials

In the commands which we studied in this article you saw that for some of them we used the –user and –passwordfile parameters and for some of them we did not. The main reason behind the fact that we could execute a command with or without providing any credentials refers back to the way that we create the domain. If you look at the command we used to create the domain you can see that we used –savemasterpassword=true and –savelogin=true.  These two parameters save the domain credentials and asadmin reuse those credentials whenever we want to execute a command.

The so called master password

The master password is designated to protect the domain encrypted files like digital certificate store from unauthorized access.

When we start a GlassFish domain, startup process needs to read these certificates and therefore it need to open the certificates store files. GlassFish needs master password to open the store files and therefore we should either provide the master password during the start-domain command execution in an interactive way or we should use the –passwordfile parameter to provide the process with the master password.

The most common situation for using a previously saved master password is when we need our application server to start in an unattended environment, like when we make a Windows service or Linux Daemon for it.

To provide this password for the application server startup process, we should use the –savemasterpassword=true during the domain creation. If we use this parameter the master password will be saved into a file named master-password which resides inside the domain/config directory.

We said that the master password protects some files from unauthorized access. One of the file set that master password protects is the digital certificates storage files which differ between developer and cluster profile.

The domain administration credentials

So far, we that we can execute asadmin commands with or without providing the password file. You may ask, how it is possible that we are not entering the password and nor we are providing the password file and hence we saw that our command are carried out by the  asadmin.

We did not provide any password in an interactive manner or any password file for asadmin to carry out our command because we used a parameter during the domain creation. The –savelogin=true asks the domain creation command to save the administration password of our domain into a file name .asadminpass which is located inside our home directory. The content of this file is similar to the following snippet.

asadmin://admin@localhost:4747 YWRtaW5hZG1pbg==

The syntax simply determine what is the administration username and administration password for a domain that is running on localhost and uses 4747 as its administration port Sure the password is encrypted to prevent anyone learning it without being authorized.

There is an asadmin command which perform a similar task to what –savelogin does for domains that are already created.  We can use this command to save the credentials to prevent the asadmin utility asking for them either in an interactive mode or as  –passwordfile parameter. Following snippet shows how we can use login command.

login   --host localhost --port 9138

This command will interactively ask for administration username and administration password and after a successful authentication it will save the provided credentials into the .asadminpass file. After we execute this command the content of .asadminpass will be similar to the following snippet.

asadmin://admin@localhost:4747 YWRtaW5hZG1pbg==

asadmin://admin@localhost:9138 YWRtaW5hZG1pbg==

The .asadminpass contains the SHA hashed copy of passwords therefore it is not possible for anyone to recover the original passwords if he can grasp the file.

The login command falls very useful when we need to administrate several domains from our administration workstation. We can simply login into each remote or local domain that we need to administrate and then asadmin will pickup the correct credential from the .asadminpass file based on the –host and –port parameters.

Changing passwords

As and administrator we usually like to change our passwords from time to time to ensure keep a higher level of security precautions. GlassFish let us simply change the master or administration password using some provided commands.

To change the master password we must be sure that application server is not running and then we can the change-master-password as follow:

Change-master-password --domaindir=/opt/dev/apps/domains/ --savemasterpassword=true GiADomain

After executing this command, the asadmin utility will interactively asks us for the new master password which must be at least 8 characters. And we use the –savemasterpassword to ensure that the master password is saved and during the domain startup we do not need to provide the asadmin with it. We need to change the password file if we are using it to feed the asadmin utility with the master password.

To change the administration password we can use change-admin-password which is a remote command and need the application server to be running. Following snippet shows how we can change the administration password for a given username.

change-admin-password --host 127.0.0.1 --port 4747 --user admin

After executing this command, asadmin will asks for administration password and then change the password of the given user. If we change the password for a user, we will need to login into that domain again if we need to use automatic login. Also we need to change the password file if we are using it to feed the asadmin utility with its required passwords.

In advanced administration article we will discuss how we can add more administration users and how we can use an already credentials store like an LDAP for administration authentication.

4.2 Protecting passwords

We have many places in any application server which we need to provide it wit some username and passwords which the application server will use to communicate with external systems like JMS brokers and Databases. Usually each part of the overall infrastructure has its own level of policy and permission set which lead to the fact that we should protect these passwords and avoid leaving these passwords in plain text format in any place, even in the application server configuration files which can be opened using any text editor.

GlassFish provides a very elegant way for protecting these passwords by providing us with the required commands and infrastructure to encrypt the passwords and use the encrypted password’s assigned alias in the application server configuration files. The encrypted passwords are stored inside an encrypted file named domain-passwords which resides inside the domain’s config directory. The domain-passwords file is encrypted using the master password and if the master password compromised then these file can be decrypted.

The command for creating password aliases is a remote command named create-password-alias and a sample usage is as following snippet:

create-password-alias --user admin --host localhost --port 4747 GiA_Derby_Pool_Alias

After we execute this command asadmin utility will ask for the password which we want this alias to hold.  Although asadmin may asks for administration credentials if we are not logged in.

Now that we create the alias we can use it by using the alias accessing syntax which follows the ${ALIAS=password-alias-password} format. For example if we want to create the JDBC connection pool that we create in 3.3 we can change the command as follow:

create-jdbc-connection-pool --user admin  --host localhost --port 4747

--datasourceclassname org.apache.derby.jdbc.ClientDataSource --restype javax.sql.XADataSource

--property portNumber=1527:password=${ALIAS= GiA_Derby_Pool_Alias }:user=APP:serverName=

localhost:databaseName=GiADatabase:create=true GiA_Derby_Pool

Password aliasing is not present just for external resources, but it can be used to protect the content of the password file which contains administration and master password for using instead of typing the password when the asadmin interactively asks for it.  We can simply create a password alias for administration password and for the master password and use them in password file. Sample content for a password file with aliased password is like.

AS_ADMIN_PASSWORD=${ALIAS=admin-alias}

AS_ADMIN_MAPPEDPASSWORD=${ALIAS=master-alias}

Like all other administration commands, the alias administration commands set have some other commands which help with the commands administration. Other commands in the set are

  • The delete-password-alias command: We can delete an alias when we are sure we are no longer using it.
  • The list-password-aliases command: We can get a list of all aliases that we have in our domain-password file.
  • The update-password-alias command: We can update an alias by changing the password that it holds.

Password aliasing is very helpful when we do not want to give our passwords to the personal in charge of application server management or administration tasks. Instead we can provide them aliased password which they can use.

5 Summary

The GlassFish command line administration interface is one of the most powerful and feature complete command line based administration utilities in the application server markets.  The asadmin utility provides all required commands which we need to administrate any part of the application server directly from the command line instead of wandering in the XML configuration files or third party utilities or the web based administration console.

The asadmin utility is a not only a client side application which we can use to administrate an application and instead it is a composition of client side and a server side application which makes it possible to use the asadmin utility to administrate remote domains as well as local domains.

The asadmin utility has enough intelligence embedded in its routines which helps us find the required commands and the command structure simply by entering a part of command. By using asadmin utility we can administrate domains, applications, and application server managed resources.

When it comes to security, which is one of the highest concerns of the administrators, GlassFish provides many measures to protect passwords and keep the possibility of compromising passwords to the lowest possible value by using encryption for storing external resource passwords and asadmin administration passwords.

Manage, Administrate and Monitor GlassFish v3 from Java code using AMX & JMX

Management is one of the most crucial parts of an application server set of functionalities. Development of the application which we deploy into the server happens once with minor development iteration during the software lifecycle, but the management is a lifetime task. One of the very powerful features of the GlassFish application server is the powerful administration and management channels that it provides for different level of administrators and developers whom want to extend the application server administration and management interfaces.

GlassFish as an application server capable or serving mission critical and large scale applications benefits from several administration channel including the CLI, web based administration console and finally the possibility to manage the application server by using standard Java management extension or the JMX.

Not only GlassFish fully expose its management functionalities as JMX MBeans but also it provides a very easier way to manage the application server using local objects which proxies JMX MBeans. These local objects are provided as AMX APIs which lift the need for learning JMX by administers and developers whom want to interact with the application server by code.

GlassFish provides very powerful monitoring APIs in term of AMX MBeans which let developers and administrators monitor any aspect of anything inside the application server using Java code without need to understand the JMX APIs or complexity of monitoring factors and statistics gathering. These monitoring APIs allows developers to monitor a bulk of Java EE functionalities together or just monitor or single attribute of a single configuration piece.

GlassFish self management capability is another powerful feature based on the AMX and JMX APIs to let administrators easily automate daily tasks which can consume a handful amount of time without automation. Self management can manage the application server dynamically by monitoring the application server in runtime and changing the application server configuration dynamically based on predefined rules.

1 Java Management eXtension (JMX)

JMX, native to Java platform, introduced to let Java developers have a standard and easy to learn and use way for managing and monitoring their Java applications and Java enabled devices. We as architects, designers and developers of Java applications which can be as small as an in house invoice management or as big as a running stock exchange system need a way to expose management of our developed software to other industry accepted management software and JMX is the answer to these need.

1.1 What is JMX?

JMX is a part of Java Standard edition and was present from early days of Java platform existence and seen many enhancements during Java platform evolution. The JMX related specifications define the architecture, design patterns, APIs, and services in the Java programming language for managing and monitoring applications and Java enabled devices.

Using the JMX technology, we can develop Java classes which perform the management and monitoring tasks and expose a set of their functionalities or attributes by means of an interface to which later on are exposed to JMX clients through specific JMX services. The objects which we use to perform and expose management functionalities are called Managed Beans or MBeans in brief.

In order for MBeans to be accessible to JMX clients, which will use them to perform management tasks or gathers monitoring data, they need to be registered in a registry which later on let our JMX client application to find and initialize them. This registry is one of the fundamental JMX services and called MBean Server.

Now that we have our MBeans registered with a registry, we should have a way to let clients communicate with the running application which registered the MBeans to execute our MBeans operations, this part of the system is called JMX connectors which let us communicate with the agent from a remote or local management station. The JMX connector and adapter API provides a two way converter which can transparently connect to JMX agent over different protocols and provides a standard way for management software to communicate with the JMX agents regardless of communication protocol.

1.2 JMX architecture

The JMX benefits from a layered architecture heavily based on the interfaces to provide independency between different layers in term of how each layer works and how the data and services are provided for each layer by its previous one.

We can divide the JMX architecture to three layers. Each layer only relay on its direct bottom layer and is not aware of its upper layer functionalities. These layers are: instrumentation, agent, and management layers. Each layer provides some services either for other layers, in-JVM clients or remote clients running in other JVMs. Figure 1 shows different layers of JMX architecture.

Figure 1 JMX layerd architecture and each layer components

Instrumentation layer

This layer contains MBeans and the resources that MBeans are intended to manage. Any resource that has a Java object representative can be instrumented by MBeans. MBeans can change the value of object’s attributes or call its operations which can affect the resource that this particular Java object represents. In addition to MBeans, notification model and MBean metadata objects are categorized in this layer. There are two different types of MBeans for different use cases, these types include:

Standard MBeans: Standard MBeans consisting of an MBean interface which define the exposed operations and properties (using getters and setters) and the MBean implementation class. The MBean implementation class and the interface naming should follow a standard naming pattern in Standard MBeans. There is another type of standard MBeans which lift the urge for following the naming pattern called MXBeans. The Standard MBeans naming pattern for MBeans interface is ClassNameMBean and the implementation class is ClassName. For the MXBeans naming pattern for the interface is AnythingMXBean and the implementation class can have any name. We will discuss this naming matter in more details later on.

Dynamic MBeans: A dynamic MBean implements javax.management.DynamicMBean, instead of implementing an static interface with a set of predefined methods. Dynamic MBeans relies on javax.management.MBeanInfo that represents the attributes and operations exposed by them. MBeans client application call generic getters and setters whose implementation must resolve the attribute or operation name to its intended behavior. Faster implementation of JMX management MBeans for an already completed application and the amount of information provided by MBeans metadata classes are two benefits of Dynamic MBeans.

Notification Model: JMX technology introduces a notification model based on the Java event model. Using this event model MBeans can emit notifications and any interested party can receive and process them, interested parties can be management applications or other MBeans.

MBean Metadata Classes: These classes contain the structures to describe all components of an MBean’s management interface including its attributes, operations, notification, and constructors. For each of these, the MBeanInfo class include a name, a description and its particular characteristics (for example, an attribute is readable, writeable, or both; for an operation, the signature of its parameter and return types).

Agent layer

This layer contains the JMX Agents which are intended to expose the MBeans to management applications. The JMX agent’s implementation specifications fall under this layer. Agents are usually located in the same JVM that MBeans are located but it is not an obligation. The JMX agent consisting of an MBean server and some helper services which facilitate MBeans operations. Management software access the agent trough an adapter or connecter based on the management application communication protocol.

MBean Server: This is the MBeans registry, where management applications will look to find which MBeans are available to them to use. The registry expose the MBeans management interface and not the implementation class. The MBeans registry provides two interfaces for accessing the MBeans from a remote and in the same JVM client. MBeans can be registered by another MBeans, by the management application or by the Agent itself. MBeans are distinguished by a unique name which we will discuss more in AMX section.

Agent Services: there some helper services for MBeans and agent to facilitate some functionalities. These services include: Timer, dynamic class loader, observers to observer numeric or string based properties of MBeans, and finally relation service which define associations between MBeans and enforces the cardinality of the relation based on predefined relation types.

Management layer

The Management tier contains components required for developing management applications capable of communicating with JMX agents. Such components provide an interface for a management application to interact with JMX agents through a connector. This layer may contain multiple adapters and connectors to expose the JMX agent and its attached MBeans to different management platforms like SNMP or exposing them in a semantic rich format like HTML.

JMX related JSRs

There are six different JSRs defined for the JMX related specifications during past 10 years. These JSRs include:

JMX 1.2 (JSR 3): First version of JMX which was included in J2SE 1.2

J2EE Management (JSR 77): A set of standard MBeans to expose application servers’ resources like applications, domains, and so on for management purposes.

JMX Remote API 1.0 (JSR 160): interaction with the JMX agents using RMI from a remove locaten.

Monitoring and Management Specification for the JVM (JSR 174): a set of API and standard MBeans for exposing JVMs management to any interested management software.

JMX 2.0 (JSR 255): The new version of JMX for Java 0 which introduces using generics, annotation, extended monitors, and so on.

Web Services Connector for JMX Agents (JSR 262): define an specification which leads to use Web Services to access JMX instrumentation remotely.

1.3 JMX benefits

What are JMX benefits that JCP defined a lot of JSRs for it and on top of it, why we did not follow another management standard like IEEE Std 828-1990. The reason is behind the following JMX benefits:

Java needs an open to extend and close to change API for integration with emerging requirement and technologies, JMX does this by its layered architecture.

The JMX is based on already well defined and proven Java technologies like Java event model for providing some of required functionalities.

The JMX specification and implementation let us use it in any Java enabled software in any scale.

Almost no change is required for an application to become manageable by JMX.

Many vendors uses Java to enable their devices, JMX provide one standard to manage both software and hardware.

You can imagine many other benefits for JMX which are not listed above.

1.4 Managed Beans (MBeans)

We discussed that generally there are two types of MBeans which we can choose to implement our instrumentation layer. Dynamic MBeans are a bit more complex and we would rather skip them in this crash course, so in this section we will discuss how MXBeans can be developed, used locally and remotely to prepare ourselves for understanding and using AMX to manage GlassFish.

We said that we should write an interface which defines all exposed operation of the MBeans both for the MXBeans and standard MBeans. So first we will write the interface. Listing 1 shows the WorkerMXBean interface, the interface has two methods which supposed to change a configuration in a worker thread and two properties which return the current number of workers threads and maximum number of worker threads. Number of current workers thread is read only and maximum number of threads is both readable and updateable.

Listing 1 The MXBean interface for WorkerMXBean

@MXBean

public interface WorkerIF

{

public int getWorkersCount();

public int getMaxWorkers();

public void setMaxWorkers(int newMaxWorkers);

public int stopAllWorkers();

}

I did not told you that we can forget about the naming conversion for MXBean interfaces if we are intended to use Java annotation. As you can see we simply marked the interface as an MBean interface and defined some setter and getter methods along with one operation which will stop some workers and return the number of stopped workers.

The implementation of our MXBean interface will just implement some getter and setters along with a dummy operation which just print a message in standard output.

Listing 2 the Worker MXBean implementation

public class Worker implements WorkerIF {

private int maxWorkers;

private int workersCount;

public Worker() {

}

public int getWorkersCount() {

return workersCount;

}

public int getMaxWorkers() {

return maxWorkers;

}

public void setMaxWorkers(int newMaxWorkers) {

this.maxWorkers = newMaxWorkers;

}

public int stopAllWorkers() {

System.out.println(“Stopping all workers”);

return 5;

}

}

We did not follow any naming convention because we are using MXBean along with the annotation. If it was a standard MBean then we should have named the interface as WorkerMBean and the implementation class should have been Worker.

Now we should register the MBean to some MBean server to make it available to any management software. Listing 3 shows how we can develop a simple agent which will host the MBean server along with the registered MBeans.

Please replace the numbers with cueballs

Listing 3 How MBeans server works in a simple agent named WorkerAgent

public class WorkerAgent {

public WorkerAgent() {

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); #1

Worker workerBean = new Worker();                  #2

ObjectName workerName = null;

try {

workerName = new                                #3 ObjectName(“article:name=firstWorkerBean”);

mbs.registerMBean(workerBean, workerName);          #4

System.out.println(“Enter to exit…”);            #5

System.in.read();

} catch(Exception e) {

e.printStackTrace();

}

}

public static void main(String argv[]) {

WorkerAgent agent = new WorkerAgent();

System.out.println(“Worker Agent is running…”);

}

}

At #1 we get the platform MBean Server to register our MBean. Platform MBean server is the default JVM MBean server. At #2 we initialize an instance of our MBean.

At #3 we create a new ObjectName for our MBean. Each JVM may use many libraries which each of them can register tens of MBeans, so MBeans should be uniquely identified in MBean server to prevent any naming collision. The ObjectName follow a format to represent an MBean name in order to ensure that it is shown in a correct place in the management tree and lift any possibility for naming conflict. An ObjectName is made up of two parts, a domain and a name value pair separated by a colon. In our case the domain portion is article and the description is name=name=firstWorkerBean

At #4 as register the MBean to the MBean server. At #5 we just make sure that our application will not close automatically and let us examine the MBean.

Sample code for this chapter is provided along with the book, you can run the sample codes by following the readme.txt file included in the chapter06 directory of source code bundle. Using the sample code you will just use Maven to build and run the application and JConsole to monitor it. But the behind the scene procedure described in the following paragraph.

To run the application and see how our MBean will appear in a management console which is standard JConsole bundled with JDK. To enable the JMX management agent for local access we need to pass the -Dcom.sun.management.jmxremote to the JVM. This command will let the management console to use inter process communication to communicate with the management agent. Now that you have the application running you can run JConsole. Open a terminal window and run jconsle. When JConsole opens, it shows a window which let us select either a remote or a local JVM to connect. Just scan the list of local JVMs to find WorkerAgent under name column; select it and press connect to connect to the JVM. Figure 2 shows the new Connection window of JConsole which we talked about.

Figure 2 The New Connection window of JConsole

Now you will see how JConsole shows different aspects of the selected JVM including memory meters, threads status, loaded classes, JVM overview which includes the OS overview and finally the MBeans. Select MBeans tab and you can see a tree of all MBeans registered with the platform MBean server along with your MBean. You should remember what I said about ObjectName class, the tree clearly shows how a domain includes its child MBeans. When you expand article node you will see something similar to figure 3.

Figure 3 JConsole navigation tree and effect of ObjectName format on the MBean placing in the tree

And if you click on stopAllWorkers node the context panel of the JConsole will load a page similar to figure 4 which also shows the result of executing he method.

Figure 4 The content panel of JConsole after selecting stopAllWorkers method of the WorkerMBean

It was how we can connect to a local JVM, in the 1.6 we will discuss connecting to a JVM process from a remote location to manage the system using JMX.

1.5 JMX Notification

The JMX API defines a notification and notification subscription model to enable MBeans generate notifications to signal a state change, a detected event, or a problem.

To generate notifications, an MBean must implement the interface NotificationEmitter or extend NotificationBroadcasterSupport. To send a notification, we need to construct an instance of the class javax.management.Notification or a one of its subclasses like AttributeChangedNotification, and pass the instance to NotificationBroadcasterSupport.sendNotification.

Every notification has a source. The source is the object name of the MBean that generated the notification.

Each notification has a sequence number. This number can be used to order notifications coming from the same source when order matters and there is a risk of the notifications being handled in the wrong order. The sequence number can be zero, but preferably the number increments for each notification from a given MBean.

Please replace the # with cueball in the source and the paragraph

1.6 Remote management

To manage our worker application from a remote location using a JMX console like JConsole we will just need to ensure that an RMI connector is open in our JVM and all appropriate settings like port number, authentication mechanism, transport security and so on are provided. So, to run our sample application with remote management enabled we can pass the following parameters to the java command.

-Dcom.sun.management.jmxremote.port=10006     #1

-Dcom.sun.management.jmxremote.authenticate=true #2

-Dcom.sun.management.jmxremote.password.file=passwordFile.txt #3

-Dcom.sun.management.jmxremote.ssl=false #4

At #1 we determine a port for the RMI connector to listen for incoming connections. At #2 we enable authentication in order to protect our management portal. At #3 we provide the path to a password file which contains the list of username and password in plain text. In the password file, each username and password pair are placed in one line with an space between them. At #4 we disable SSL for transport layer.

To connect to a JVM which started with these parameters, we should choose remote in the New Connection window of JConsole and provide the service:jmx:rmi:///jndi/rmi://127.0.0.1:10006/jmxrmi as Remote Process URL along with one of the credentials which we defined in the passwordFile.txt.

2 Application Server Management eXtension (AMX)

GlassFish fully adheres to the J2EE management (JSR 77) in term of exposing the application server configuration as JMX MBeans but dealing with JMX is not easy and likeable for all developers, so Sun has included a set of client side proxies over the JSR 77 MBeans and other additional MBeans of their own to make the presence of JMX completely hidden for the developers who want to develop management extensions for GlassFish. This API set is named AMX and usually we use them to develop management rules.

2.1 J2EE management (JSR 77)

Before we dig into AMX we need to know what JSR 77 is and how it helps us to using JMX and AMX for managing the application server. JSR 77 specification introduces a set of MBeans and services which let any JMX compatible client manage Java EE container’s deployed objects and Java EE services.

The specification defines a set of MBeans which models all Java EE concepts in a hierarchic of MBeans. The specification determines which attributes and operation each MBeans must have and what should be the effect of calling a method on the managed objects. Specification defines a set of events which should be exposed to JMX clients by the MBeans. The specification also defines a set of attributes’ statistics which should be exposed by the JSR 77 MBeans to the JMX client for performance monitoring.

Services and MBeans provided by JSR 77 covers:

Monitoring performance statistics of managed artifacts in the Java EE container. Managed objects like EJBs, Servlets, and so on.

Event subscription for important events of the managed objects like stopping or starting an application.

Managing state of different standard managed objects if the Java EE container like changing an attribute of a JDBC connection pool or underplaying an application.

Navigation between Managed objects.

Managed objects

The artifacts that JSR 77 exposes their management, monitoring to JMX clients include a broad range of Java EE components and services. Figure 5 shows the first level of the Managed objects in the Managed objects hierarchic. As you can see in the figure all objects inherits four attributes which later on will be used to determine whether an object state is manageable, the object provides statistics or the object provide events for its important performed actions.

The objectName attribute which we discussed before has the same use and format, for example amx:j2eeType=X-JDBCConnectionPoolConfig,name=DerbyPool represent a connection pool named DerbyPool in the amx domain, the j2eeType attribute shows the MBean’s type.

Figure 5 first level hierarchic of JSR 77 Managed objects which based on the specification must be exposed for JMX management.

Now that you saw how broad the scope of JSR 77 is you ask what the use of these MBeans is and how they work and can be used.

Simple answer is that as soon as a Managed object become live in the application server a corresponding JSR 77 MBeans will get initialized for it by the application server management layer. For example as soon as you create a JDBC connection pool a new MBeans will appear under the JDBCConnectionPoolConfig node of connected JConsole which represent the newly created JDBC connection. Figure 6 shows the DerbyPool under the JDBCConnectionPoolConfig node in JConsole.

Figure 6 The DerbyPool place under JDBCConnectionPoolConfig node in JConsole

In the figure 5 you can see that we can manage All deployed objects using the JSR 77 exposed MBeans, these objects J2EE applications and modules which are shown in figure A deployed application may have EJB, Web, and any other modules; Glassfish management service will initialize a new insistence of appreciated MBeans for each module in the deployed application. The management service uses ObjectName which we discussed before to uniquely identify each MBean instance and later on we will use this unique name to access each deployed artifact independently.

Figure 7 The specification urge implementation of MBeans to manage all shown deployable objects

Getting lower into the deployed modules we will have Servlets, EJBs and so on. The JSR 77 specification provided MBeans for managing EJBs and Servlets. The EJB MBeans inherit the EJB MBean and includes all necessary attributes and method to manage different types of EJBs. Figure 8 represent the EJB sub classes.

Figure 8 All MBeans related to EJB management in GlassFish application server, based on JSR 77

Java EE resources is one the most colorful area in the Java EE specification and the JSR 77 provides MBeans for managing all standard resources managed bye Java EE containers. Figure 9 shows which types of resources are exposed for management by the JSR 77.

Figure 9 Java EE resources manageable by the JSR 77 MBeans

All of Java EE base concepts are covered by the JSR 77 in order to make it possible for the 3rd party management solution developers to integrate Java EE application server management into their solutions.

The events propagated by JSR 77

In the beginning of this section we talked about events that interested parties can receive from JSR 77 MBeans. These events are as follow for different type of JSR 77 MBeans.

J2SEEServer: An event when the corresponding server enters RUNNING, STOPPED, or FAILED state

EntityBean: An event when the corresponding Entity Bean enters RUNNING, STOPPED, or FAILED state

MessageDrivenBean: An event when the corresponding Entity Bean enters RUNNING, STOPPED, or FAILED state

J2EEResource: An event when the corresponding J2EE Resource enters RUNNING, STOPPED, or FAILED state

JDBCResource: An event when the corresponding JDBC data source enters RUNNING, STOPPED, or FAILED state

JCAResource: An event when a JCA connection factory or managed connection factory entered RUNNING, STOPPED, or FAILED state

The monitoring statistics exposed by JSR 77

The specification urge exposing some statistics related to different Java EE components by JSR 77 MBeans. The required statistics by the specification includes:

Servlet statistics: Servlet related statistics which include Number of currently loaded Servlets; Maximum number of Servlets loaded which were active, and so on.

EJB statistics: EJB related statistics which Include include Number of currently loaded EJBs, Maximum number of live EJBs, and so on.

JavaMail statistics: JavaMail related statistics which Include maximum number of sessions, total count of connections, and so on.

JTA statistics: Statistics for JTA resources which includes successful transactions, failed transactions and so on.

JCA statistics: JCA related statistics which includes both the non-pooled connections and the connection pools associated with the referencing JCA resource.

JDBC resource statistics: JDBC resource related statistics for both non-pooled connections and the connection pools associated with the referencing JDBC resource, connection factory. The statistics include total number of opened and closed connections, maximum number of connections in the pool, and so on. This is really helpful to find connection leak for an specific connection pool.

JMS statistics: The JMS related including statistics for connection session, JMS producer, and JMS consumer.

Application server JVM Statistics: The JVM related statistics. Information like different memory sector size, threading information, class loaders and loaded classes and so on.

2.2 Remotely accessing JSR 77 MBeans by Java code

Include a sample code which shows accessing JSR 77  MBeans from remote location using java code to show how cumbersome it is and how simple AMX made it. // Done

Now that we discussed the details of the JSR 77 MBeans, let’s see how we can access the DerbyPool MBeans from java code and then how we can change an attribute which represent maximum number of connections in the connection pool. Listing 4 show the sample code which will access a GlassFish instance with default port for JMX listener (the default port is 8686)

Listing 4 Accessing a JSR 77 MBean for changing DerbyPool’s MaxPoolSize attribute.

public class RemoteClient {

private MBeanServerConnection mbsc = null;

private ObjectName derbyPool;

public static void main(String[] args) {

try {

RemoteClient client = new RemoteClient(); #A

client.connect();                          #B

client.changeMaxPoolSize();              #c

} catch (Exception e) {

e.printStackTrace();

}

}

private void connect() throws Exception {

JMXServiceURL jmxUrl =

new JMXServiceURL(“service:jmx:rmi:///jndi/rmi://127.0.0.1:8686/jmxrmi”); #1

Map env = new HashMap();

String[] credentials = new String[]{“admin”, “adminadmin”};

env.put(JMXConnector.CREDENTIALS, credentials);              #2

JMXConnector jmxc =

JMXConnectorFactory.connect(jmxUrl, env);             #3

mbsc = jmxc.getMBeanServerConnection();                     #4

}

private void changeMaxPoolSize() throws Exception {

String query = “amx:j2eeType=X-JDBCConnectionPoolConfig,name=DerbyPool”;

ObjectName queryName = new ObjectName(query);             #5

Set s = mbsc.queryNames(queryName, null);                   #6

derbyPool = (ObjectName) s.iterator().next();

mbsc.setAttribute(derbyPool, new Attribute(“MaxPoolSize”, new Integer(64)));                                                   #7

}

}

#A initiate an instance of the class

#B get the JMX connection

#C change the attribute’s value

At #1 we create a URL to GlassFish JMX service. At #2 we prepared the credentials which we should provide for connecting to the JMX service. At #3 we initialize the connector. At #4 we create a connection to GlassFish’s MBean server. At #5 we query the registered MBeans for an MBean similar to our DerbyPool MBean. At #6 we get the result of the query inside a set. We are sure that we have an MBean with the give name otherwise we should have checked to see whether the set is empty or not. At #7 we just change the attribute. You can check the attribute in JConsole and you will se that it change in the JConsole as well.

In the sample code we just update the DerbyPool’s maximum number of connections to 64. it can be counted as one of the simplest task related to JSR 77, management, and using JMX. Using plain JMX for a complex task will overhaul us with many lines of complex reflection based codes which are hard to maintain and debug.

2.3 Application Server Management eXtension (AMX)

Now that you see how hard it is to work with JSR 77 MBeans I can tell you that you are not going to use JSR 77 MBeans directly in your management applications, although you can.

What is AMX

In The AMX APIs java.lang.reflect.proxy is used to generate Java objects which implement the various AMX interfaces. Each proxy internally stores the JMX ObjectName of a server-side JMX MBean who’s MBeanInfo corresponds to the AMX interface implemented by the proxy.

So, in the same time we have JMX MBeans for using trough any JMX compliant management software and we have the AMX dynamic proxies to use them as easy to use local objects for managing the application server.

The GlassFish administration architecture is based on the concept of administration domain. An administration domain is responsible for managing multiple resources which are based on the same administration domain.  A resource can be a cluster of multiple GlassFish instances, a single GlassFish instance, and a JDBC connection pool inside the instance and so on. Hundreds of AMX interfaces are defined to proxy all of the GlassFish managed resources which themselves are defined as JSR 77 MBeans for client side access. All of these interfaces are placed under com.sun.appserv.management package.

There are several benefits in AMX dynamic proxies over the JMX MBeans, which are as follow:

Strongly typed methods and attributes for compile time type checking

Structural consistency with both the domain.xml configuration files.

Consistent and structured naming for methods, attributes and interfaces.

Possibility to navigate from a leaf AMX bean up to the DAS.

AMX MBeans

AMXdefines different types of MBean for different purposes or reasons, namely, configuration MBeans, monitoring MBeans, utility MBeans and JSR 77 MBeans. All AMX MBeans shares some common characteristics including:

They all implement the com.sun.appserv.management.base.AMX interface which contains methods and fields for checking the interface type, group, reaching its container and its root domain.

They all have a j2eeType and name property within their ObjectName. The j2eeType attribute specifies the interface we are dealing with.

All MBeans that logically contain other MBeans implement the com.sun.appserv.management.base.Container interface. Using the container interface we can navigate from a leaf AMX Bean to the DAS and vice-versa. For example by having the domain AMX Bean we can get a list of all connection pools or EJB modules in deployed in the domain.

JSR 77 MBeans that have a corresponding configuration or monitoring peer expose it using getConfigPeer or getMonitoringPeer. However; there are many configuration and monitoring MBeans that do not correspond to JSR 77 MBeans.

Configuration MBeans

We discussed that there are several types of MBeans in the AMX framework, one of them is the configuration MBeans. Basically these MBeans represent domain.xml and other configuration file content and structure.

In GlassFish all configuration information are stored in one central repository named DAS, in a single instance installation the instance act as DAS and in a clustered installation the DAS responsibility is sole taking care of the configuration and propagating it to all instances. The information stored in the repository are exposed to any interested party like an administration console trough AMX interfaces.

Any developer with familiarity with domain.xml structure will find him very comfortable with configuration interfaces.

Monitoring MBeans

Monitoring MBeans provide transient monitoring information about all the vital components

of the Application Server. A monitoring interface can either provides statistics or not and if it provides statistics it should implements the MonitoringStats interface which is JSR 77 compliant interface for providing statistics.

Utility MBeans

UtilityMBeans provide commonly used services to the Application Server. These MBeans all extend either or both of the Utility and Singleton interfaces. All of these MBeans interface are located in com.sun.appserv.management.base package. Notable utility MBeans are listed in table 1

Table 1 AMX Utility MBeans along with description

MBean interface

description

SystemInfo

Provides information about application server capabilities like clustering support

QueryMgr

Provides JMX-like queries which are restricted to AMX MBeans.

BulkAccess

Provides network-efficient “bulk” calls whereby many Attributes or Operations in many MBeans may be fetched and invoked in one invocation, thus minimizing network overhead.

NotificationService

Provides buffering and selective dynamic listening for Notifications on AMX MBeans.

UploadDownloadMgr

Supports uploading and downloading of files to/from the application server.

Java EE Management MBeans

The Java EE management MBeans implement, and in some cases extend, the management

Hierarchy as defined by JSR 77, which specifies the management model for the whole Java EE platform. All JSR 77 MBeans in the AMX domain offer access to configuration and monitoring MBeans using the getMonitoringPeer and getConfigPeer methods.

Dynamic Client Proxies

Dynamic Client Proxies are an important part of the AMX API, and enhance ease-of-use for the programmer. JMX MBeans can be used directly by an MBeanServerConnection to the server. However, client proxies greatly simplify access to Attributes and operations on MBeans, offering get/set methods and type-safe invocation of operations. Compiling against the AMX interfaces means that compile-time checking is performed, as opposed to server-side runtime checking, when invoked generically through MBeanServerConnection.

See the API documentation for the com.sun.appserv.management package and its sub-packages for more information about using proxies. The API documentation explains the use of AMX with proxies. If you are using JMX directly (for example, by using MBeanServerConnection), the return type, argument types, and method names might vary as needed for the difference between a strongly-typed proxy interface and generic MBeanServerConnection or ObjectName  interface.

Changing the DerbyPool attributes using AMX

In listing 4 you saw how we can use JMX and pure JSR 77 approach to change the attributes of a JDBC connection pool, in this part we are going to perform the same operation using AMX to see how much easier and more effective the AMX is.

Listing 5 Using AMX to change DerbyPool MaxPoolSize attribute

AppserverConnectionSource appserverConnectionSource = new AppserverConnectionSource(AppserverConnectionSource.PROTOCOL_RMI, “127.0.0.1″, 8686, “admin”, “adminadmin”,null,null);              #1

DomainRoot dRoot = appserverConnectionSource.getDomainRoot(); #2

JDBCConnectionPoolConfig cpConf= dRoot.getContainee(XTypes.JDBC_CONNECTION_POOL_CONFIG, “DerbyPool”); #3

cpConf.setMaxPoolSize(“100″);            #4

You are not mistaking it with another idea or code, that four lines of code let us change the maximum pool size of the DerbyPool.

At #1 we create a connection to the server that we want to perform our management operation on it. Several protocols can be used to connect to the application server management layer. As you can se when we construct the appserverConnectionSource instance we used AppserverConnectionSource.PROTOCOL_RMI as the communication protocol to ensure that we will not need some JAR files from OpenPDK project. Two other protocols which we can use are AppserverConnectionSource.PROTOCOL_HTTP and AppserverConnectionSource.PROTOCOL_JMXMP. The connection that we made does not uses TLS, but we can use TLS to ensure transport security.

At #2 we get the AMX domain root which later on let us navigate between all AMX leafs which are servers, clusters, connection pools, and listeners and so on. At #3 we query for an AMX MBean which its name is DerbyPool and its j2eeType is equal to XTypes.JDBC_CONNECTION_POOL_CONFIG. At #4 we set a new value for the attribute of our choice which is MaxPoolSize attribute.

Monitoring GlassFish using AMX

The monitoring term comes to the developers and administrators mind whenever they are dealing with performance tuning, but monitoring can also be used for management purposes like automation of specific tasks which without automation need an administrator to take care of it. An example of these types of monitoring is critical condition notifications which can be send either via email or SMS or any other gateway which the administrators and system managers prefer.

Imagine that you have a system running on top of GlassFish and you want to be notified whenever acquiring connections from a connection pool named DerbyPool is taking longer than 35 seconds.

You also want to store all information related to the connection pool when the pool is closing to saturate. For example when there are only 5 connections to give away before the pool get saturated.

So we need to write an application which monitor the GlassFish connection pool, check its statistics regularly and if the above criteria meets, our application should send us an email or an SMS along with saving the connection pool information.

AMX, provides us with all required means to monitor the connection pool and be notified when any connection pool attributes or any of its monitoring attributes changes so we will just use our current AMX knowledge along with two new concepts about the AMX.

The first concept that we will use is AMX monitoring MBeans which provides us with all statistics about the Managed Objects that they monitor. Using the AMX monitoring MBeans is the same as using other AMX MBeans like the connection pool MBean.

The other concept is the notification mechanism which AMX provides on top of already established JMX notification mechanism. The notification mechanism is fairly simple, we register our interest for some notification and we will receive the notifications whenever the MBeans emit a notification.

We know that we can configure GlassFish to collect statistics about almost all Managed Objects by changing the monitoring level from OFF to either LOW or HIGH. In our sample code we will change the monitoring level manually using our code and then use the same statistics that administration console shows to check for the connection pool consumed connections.

Listing 6 shows sample applications which monitor DerbyPool and notify the administrator whenever acquiring connection take longer than accepted. The application saves all statistics information when the connection pool gets close to its saturation.

Please Replace the numbers with cueballs

Listing 6 monitoring a connection pool and notifying the administrator when connection pool is going to reach the maximum size

public class AMXMonitor implements NotificationListener {      #1

AttributeChangeNotificationFilter filter;                                          #2

AppserverConnectionSource appserverConnectionSource;

private int cPoolSize;

private DomainRoot dRoot;

JDBCConnectionPoolMonitor derbyCPMon;                                          #3

JDBCConnectionPoolConfig cpConf;

private void initialize() {

try {

appserverConnectionSource = new AppserverConnectionSource(AppserverConnectionSource.PROTOCOL_RMI, “127.0.0.1″, 8686, “admin”, “adminadmin”, null, null);

dRoot = appserverConnectionSource.getDomainRoot();

Set<String> stpr = dRoot.getDomainConfig().getConfigConfigMap().keySet();            #4

ConfigConfig conf=     dRoot.getDomainConfig().getConfigConfigMap().get(“server-config”); #4

conf.getMonitoringServiceConfig().getModuleMonitoringLevelsConfig().setJDBCConnectionPool(ModuleMonitoringLevelValues.HIGH); #4

cpConf = dRoot.getContainee(XTypes.JDBC_CONNECTION_POOL_CONFIG, “DerbyPool”);

cPoolSize = Integer.getInteger(cpConf.getMaxPoolSize());

filter = new AttributeChangeNotificationFilter();         #2

filter.enableAttribute(“ConnRequestWaitTime_Current”);       #2

filter.enableAttribute(“NumConnUsed_Current”);             #2

Set<JDBCConnectionPoolMonitor> jdbcCPM =

dRoot.getQueryMgr().queryJ2EETypeSet

(XTypes.JDBC_CONNECTION_POOL_MONITOR);                           #5

for (JDBCConnectionPoolMonitor mon : jdbcCPM) {

if (mon.getName().equalsIgnoreCase(“DerbyPool”)) {

derbyCPMon = mon;

break;

}

}

derbyCPMon = dRoot.getContainee(XTypes.JDBC_CONNECTION_POOL_MONITOR, “DerbyPool”);   #5

derbyCPMon.addNotificationListener(this, filter, null);  #5

} catch (Exception ex) {

ex.printStackTrace();

}

}

public void handleNotification(Notification notification, Object handback) {

AttributeChangeNotification notif = (AttributeChangeNotification) notification;                                                                                                    #6

if (notif.getAttributeName().equals(“ConnRequestWaitTime_Current”)) {

int curWaitTime = Integer.getInteger((String) notif.getNewValue());                                                                                    #7

if (curWaitTime > 3500) {

saveInfoToFile();

sendNotification(“Current wait time is: ” + curWaitTime);

}

} else {

int curPoolSize = Integer.valueOf((String) notif.getNewValue());                                                        #8

if (curPoolSize > cPoolSize – 5) {

saveInfoToFile();

sendNotification(“Current pool size is: ” + curPoolSize);

}

}

}

private void saveInfoToFile() {

try {

FileWriter fw = new FileWriter(new File(“stats_” + (new Date()).toString()) + “.sts”);

Statistic[] stats = derbyCPMon.getStatistics(derbyCPMon.getStatisticNames()); #9

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

fw.write(stats[i].getName() + ” : ” + stats[i].getUnit()); #10

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

private void sendNotification(String message) {

}

public static void main(String[] args) {

AMXMonitor mon = new AMXMonitor();

mon.initialize();

}

}

At #1 we implement the NotificationListener interface as we are going to use the JMX notification mechanism. At #2 we define an AttributeChangeNotificationFilter which filter the notifications to a subset that we are interested. We also add the attributes that we are interested to the set of non-filtered attribute change notification. At #3 we define and initialize an AMX MBeans which represent DerbyPool monitoring information. We will get an instance not found exception the connection pool had no activities yet. At #4 we change the monitoring level of JDBC connection pools to ensure that GlassFish gather the required statistics. At #5 we find our designated connection pool monitoring MBean and add a new filtered listener to it.

The handleNotification method is the only method in the NotificationListener interface which we need to implement. At #6 we convert the received notification to AttributeChangeNotification as we know that the notification is of this type. At #7 we are dealing with change in the ConnRequestWaitTime_Current attribute. We get its new value to check for our condition. In the same time we can get the old value if we are interested. At #8 we are dealing with NumConnUsed_Current attribute and later on with calling the saveToFile method and sendNotification methods.

At #9 we get names of all connection pool monitoring factors and at #10 we just write the monitoring attribute’s name along with its value to a text file.

AMX and Dotted Names

AMX is designed with ease of use and efficiency in mind. So in addition to using standard JMX programming model, the getters and setters, we can use another hierarchical model to access all AMX MBeans attributes. In the dotted named model each attribute of an MBean starts from its root which is either the domain for all configuration MBeans and server for all runtime MBeans. For example domain.resources.jdbc-connection-pool.DerbyPool.max-pool-size represents the maximum pool size for the DerbyPool which we discussed before.

Two interfaces are provided to access the dotted names either for monitoring or for management and configuration purposes. The MonitoringDottedNames is provided to assists with reading an attribute. The other interface is ConfigDottedNames which provides writing access to attributes using the dotted format. We can get an instance of its implementation using dRoot.getMonitoringDottedNames().

3 GlassFish Management Rule

The above sample application is promising especially when you want to have tens or rules for automatic management, but running a separate process and watching that process is not in taste of many administrators. GlassFish application server provides an very effective way to deploy such management rules into GlassFish application server for sake of simplicity and integration. Benefits and use cases of the Management Rules can be summarized as follow:

Manage complexity by self-configuring based on the conditions

Keep administrators free for complex tasks by automating mundane management tasks

Improve performance by self-tuning in unpredictable run-time conditions

Automatically adjusting the system for availability by preventing problems and recovering from one (self healing)

Enhancing security measures by taking self-protective actions when security threats are detected

A GlassFish Management Rule is a set of:

Event: An event uses the JMX notification mechanism to trigger actions. Events can range from an MBean attribute change to specific log messages.

Action: Actions are associated with events and are triggered when related events happen. Actions can be MBeans that implement the NotificationListener interface.

When we deploy a Management Rule into GlassFish, GlassFish will register our MBean in the MBean server and register its interests for the notification type that we determined. Therefore, upon any event which our MBean is registered for, the handleNotification method of our MBeans will execute. GlassFish provides some pre-defined types of events which we can choose to register our MBean’s interest. These events are as follow:

Monitor events: These types of events trigger an action based on an MBean attribute change.

Notification events: Every MBean which implements the NotificationBroadcaster interface can be source of this event type.

System events: This is a set of predefined events that come from the internal infrastructure of GlassFish application server. These events include: lifecycle, log, timer, trace, and cluster events.

Now, let’s see how we can achieve a similar functionality that our AMXMonitor application provides from The GlassFish Management Rules. First we need to change our application to a mere JMX MBean which implements NotificationListener interface and perform required action which is, for example, sending an email or SMS, in the handleNotification method.

Changing the application to MBean should be very easy; we just need to define an MBean interface and then the MBean implementation which will just implement one single method, the handleNotification method.

Now that we have our MBeans compiled JAR file, we can deploy it using the administration console. So open the GlassFish administration console, navigate to the Custom MBeqns node and deploy the MBeans by providing the path to the JAR file and the name of the MBeans implementation class. Now that we have our MBeans deployed into GlassFish, it is available for the class loader to be used as an action for a Management Rule, so in order to create the Management Rule, use the following procedure.

In the navigation tree select Configuration node, select Management Rules node. In the content panel select New and user dcpRule as the name, make sure that you teak the enabled checkbox, select monitor in the event type combo box and let the events to be recorded in the log files, press next to navigate to the second page of the wizard.

In the second page, for the Observed MBean field enter amx:X-ServerRootMonitor=server,j2eeType=X-JDBCConnectionPoolMonitor,name=DerbyPool and for the observed attribute enter ConnRequestWaitTime_Current. For the monitor type select counter. The number type is int and the initial threshold is 35000 which indicate the number which if the monitored attribute exceed, our action will start.

Scroll down and for the action, select AMXMonitor which is the name of our MBean which we deployed in previous step.

You saw that the overall process is fairly simple, but there are some limitations like possibility to monitor one single MBean and attribute at a time. Therefore we need to create another Management Rule for NumConnUsed_Current attribute.

Now that we reached to the end of this article, you should be fairly familiar with JMX, AMX and GlassFish Management Rules. In next articles we will use the knowledge that we gained here to create administration commands and create monitoring solutions.

4 Summary

We toughly discussed managing GlassFish using Java code by discussing JMX which is the foundation of all Java based management solutions and framework. We discussed JMX architecture, event model and different types of MBeans which are included in the JMX programming model. We also covered AMX as the GlassFish way providing its management functionalities to client side applications which are not interested in using complicated JMX APIs.

We discussed GlassFish management using AMX APIs to show how much simpler the AMX is when we compare it to the plain JMX implementation and we covered GlassFish monitoring using the AMX APIs.

You saw how we can use GlassFish’s Self management and self administration functionalities to automate some tasks to keep administrators free from dealing with low level repetitive administration and management tasks.

Oracle is NOT taking back OpenSolaris, ZDNet Dana Blankenhorn got it wrong.

Once again the FUD around Solaris and OpenSolaris fate started to spread after Dana Blankenhorn misunderstood the licensing terms and used a eye catching and visitor increasing title, Oracle taking back OpenSolaris, for his blog entry. Well, from this article we can get that even the veteran writers can get things wrong and spread incorrect news :-)

Folks, Solairs is one of the biggest Sun assets that Oracle is now own by taking over Sun . Solaris and OpenSolaris are going to be around in a much better shape than before because Oracle is betting its fight for the market share on this operating system to form a complete stack including storage, hardware, OS, middle-ware, support and so on.

Oracle may change the licensing terms for the Solaris OS, which is the Commercial distribution of OpenSolaris (with some added/ removed components) supported by Sun in old era, but to close the OpenSolaris code-base, no way. Changing the licensing terms can be result of Oracle seeking a higher revenue stream from the product and I bet Oracle will be able to get more out of Solaris than Sun because of its powerful marketing department :-P

Looking at the these FUD from any angel tells you that they are not correct because of at least the following reasons:

  • OpenSolaris has a large community around it which Oracle do not like to send away.
  • The Solaris/ OpenSolaris adoption highly increased after Sun pushed the source codes into OpenSolaris project. The whole Solaris on Z architecture, adoption of OpenSolaris increased so adoption of Solaris itself. Long story short, just take a look at http://www.genunix.org/ and http://hub.opensolaris.org/bin/view/Main/downloads to see how many active distributions are based on OpenSolaris core.
  • Solaris/ OpenSolaris is more important to Oracle to let it fall apart  because it has a lot to offer in Oracle strategy of offering end to end stack of its own.

People are talking about why the 2010.3 release is not released when it is already first days of April, the answer is “A few more weeks of development and testing will gives us a more stable OS” if you want to check the latest features which will be included in the 2010.3, grab the latest build (which is build 134 right now) from http://www.genunix.org/dist/indiana/ and play with it, but keep it in mind the build is not production ready yet. If you want the source code of OpenSolaris, take a look at http://hub.opensolaris.org/bin/view/Main/get to get the source code and build the OS yourself.

I am wondering what these people are getting from spreading wrong words and incorrect news about thins they have no clue about. Folks, Solaris OS is not OpenSolaris. OpenSolaris is CCDL licensed (except for some parts which are not CCDLed (http://hub.opensolaris.org/bin/view/Main/no_source)  while the Solaris distribution contains some of OpenSolaris components and features. some value added components and well along with some license/ distribution fees and first class support from Oracle.

Well, it was my personal feelings about the whole issue of OpenSolaris/ Solaris FUDs flying around.