Developing and running data access applications for the Liberty profile using WebSphere Application Server Developer Tools for Eclipse

IBM® WebSphere® Application Server V8.5 includes the Liberty profile, an ultra lightweight, fast starting, highly composable application server profile that optimizes developer productivity and web application deployment. The article looks at simplified development of data access applications, using the WebSphere Application Server Developer Tools plug-in for Eclipse, for publishing on the lightweight application-serving Liberty profile environment. This article includes a JPA-based sample data access application to demonstrate dynamic capabilities of the Liberty profile. This content is part of the IBM WebSphere Developer Technical Journal.

Share:

Anoop Ramachandra (anramach@in.ibm.com), Senior Staff Software Engineer , IBM China

Anoop Ramachandra is a Senior Staff Software Engineer in IBM India Software Labs. He has over eight years of experience on WebSphere Application Server product as a Technical Lead, developer and Level 3 support engineer. His major areas of expertise in WebSphere Application Server include System Management, Java EE Connector Architecture, Virtual Member Manager, Scheduler and Asynchronous beans. He is an IBM Certified System Administrator for WebSphere Application Server.



Rispna Jain (rispjain@in.ibm.com), Software Deployment Manager, IBM China

Rispna Jain is a Technical Software Deployment Manager for WebSphere suite of products in IBM Global Technology Services and works with clients in North America. She has seven years of experience on WebSphere Application Server product development at IBM Software Group in various roles such as development, L3 support and test. Rispna has also been a technical speaker for WebSphere Application Server related topics at various WebSphere conferences. She is an IBM Certified SOA associate and holds a Master of Technology degree in Computer Science.



05 December 2012

Also available in Chinese

Introduction

The Liberty profile is a dynamic and composable profile available in IBM WebSphere Application Server V8.5 that provides a simplified and lightweight run time environment for web applications. The Liberty profile also provides rapid application deployment either by using a drop-in directory or by adding applications to the server configuration. The Liberty profile provides easy and quick distribution and deployment of a Liberty profile server and its applications as a single package..

This article provides an overview of the Liberty profile in WebSphere Application Server V8.5, and looks particularly the WebSphere Application Server Developer Tools for Eclipse, will be used throughout this article to demonstrate the dynamic capabilities of the Liberty profile.

Liberty profile overview

The Liberty profile has a dynamic application server run time environment that can be quickly installed by extracting compressed files. The Liberty profile can also be installed using IBM Installation Manager. The Liberty profile enables flexible sharing of resources, such as SDKs, run time binary files, server configurations, and application binary files, among many server instances. It also supports multiple Java™ Runtime Environments (JREs) of Version 6.0 or later. A packaged server, containing an application, a Liberty profile server runtime, and its configuration, can be created in a single archive that can be unzipped for deployment. Figure 1 shows the Liberty profile architecture. The OSGi configuration admin service manages system configuration, and an OSGi declarative services component manages the lifecycle of system services. The file monitor service detects application and configuration file changes, and the logging service writes messages and debug information to the local file system. Features provide the programming models and services that are required by applications.

Figure 1. Overview of the Liberty profile architecture
Overview of the Liberty profile architecture

WebSphere Application Server Developer Tools for Eclipse

IBM WebSphere Application Server Developer Tools for Eclipse (hereafter referred to as Developer Tools) are no-charge plug-ins from the Eclipse Marketplace that can be installed into an existing Eclipse environment or in IBM Rational® Application Developer to support the development of applications for the Liberty profile. The plug-ins include Web 2.0, Java EE, and OSGi tools, and when combined with the Liberty profile (Figure 2), Developer Tools provides a fast and lightweight environment for the rapid development and unit testing of web, Web 2.0, mobile, and OSGi applications. The supported versions for Eclipse are version 3.7 or later (Indigo), and 3.6.2 (Helios) with the latest updates. (See Resources for supported versions of Rational Application Developer and Eclipse.)

As shown in Figure 2, together with the Eclipse SDK and Eclipse Web Tools Platform, WebSphere Application Server Developer Tools for Eclipse provides a lightweight environment for developing Java EE and Web 2.0 applications

Figure 2. Comparison of various development tools
Comparison of various development tools

Click to see larger image

Figure 2. Comparison of various development tools

Comparison of various development tools

Developer Tools contains utilities to help you develop applications for several programming models, including:

OSGi

The Open Service Gateway initiative (OSGi) application framework provides a programming model for developing, assembling, and deploying modular applications (as bundles) that use both Java EE and OSGi technologies. Developer Tools contains OSGi-specific development tools, including support for deployment to WebSphere Application Server V8 and V8.5 OSGi bundle repositories.

Java EE

Eclipse with Developer Tools enables you to write applications that work with the Java EE specification. Web applications can be developed using the latest web technologies, such as HTML5, CSS3, Dojo Toolkit, Servlet 3.0, and JSP 2.2.

Web 2.0 and mobile

Developer Tools includes a rich page editor that makes it easy to edit HTML files, add Dojo widgets to HTML pages, and create and edit web pages for mobile devices. Dojo Toolkit V1.7 can be optionally installed in Developer Tools. Dojo helps in the design and development of rich interfaces, and is usable on all current mobile platforms.

Table 1 lists the programming models accommodated by Developer Tools for Eclipse and the application servers that support them.

Programming models and support in application servers
Programming model WebSphere Application Server V8.5 Liberty profileWebSphere Application Server V8.5 full profile
Java EE applicationsYes
(Some full profile features are not supported in the Liberty profile)
Yes
JAX-RS applicationsYesYes
JAX-WS applicationsNoYes
Web 2.0 and mobile web applications YesYes
OSGi applicationsYesYes

Setting up development environment for the Liberty profile

You can setup your development environment for the Liberty profile with these two simple steps:

  1. Install Developer Tools

    Developer Tools can be downloaded at no cost from the WASdev community website and installed with an easy drag and drop of the install icon. Alternatively, you can install the developer tools from the Eclipse Marketplace:

    1. From Eclipse or Rational Application Developer, navigate to Help > Eclipse Marketplace.
    2. From the Search tab, enter WebSphere in the search box, and click Go.
    3. In the search results panel, click the Install button next to the section that includes IBM WebSphere Application Server V8.5 Liberty Profile Developer Tools.
  2. Install Liberty profile runtime

    When Developer Tools has been installed, the Liberty profile runtime can be setup by either downloading the new runtime environment, or by pointing to already extracted Liberty profile runtime (Figure 3).

    To setup the Liberty profile runtime:

    1. From the Server panel in Eclipse, select WebSphere Application Server V8.5 Liberty Profile. (The Liberty profile option will be displayed after Developer Tools has been successfully installed.)
    2. Choose to define a new server and select WebSphere Application Server V8.5 Liberty Profile.
    3. Select Download or Install a new runtime environment.
    4. Download the Liberty profile runtime from either the last good build or from the download site to set it up.
Figure 3. Installing Liberty profile runtime
Installing Liberty profile runtime

Creating and starting the new Liberty profile server

To create and start a new Liberty profile server:

  1. In the workbench, right-click the Servers view and select .New > Server
  2. Select the WebSphere Application Server V8.5 Liberty Profile and click Next (Figure 4).
    Figure 4. Creating and starting the new Liberty profile server
    Creating and starting the new Liberty profile server
  3. On the next panel, click the New button to create a new server rather than using the pre-configured defaultServer (Figure 5). Name the new server LibertyTestServer and click Finish to create the server.
    Figure 5. Create new LibertyTestServer
    Create new LibertyTestServer
  4. You can start and stop the server, as well as add and remove applications by using the server context menu (right-click on the server to open the pop-up menu) or by selecting the tray buttons in the Servers view, shown in Figure 6. The server can also be started from the command line tool.
    Figure 6. Starting the server from server menu
    Starting the server from server menu

    Click to see larger image

    Figure 6. Starting the server from server menu

    Starting the server from server menu

The Liberty profile setup with Developer Tools is now complete.

Sample application

The sample application (DevWorkSample.war) provided with this article is a simple banking application that provides functions for depositing money to and withdrawing money from a specified customer account, and for displaying customer information stored in database. It also provides functionality to test the connection to the database and to reset the database. The sample application uses JPA and traditional JDBC in servlets.

The DevWorkSample.war sample application contains these servlets:

  • Deposit. java: Credits the specified amount into customer’s account.
  • Display.java: Lists the contents of the database.
  • Reset.java: Resets the database.
  • WithDraw.java: Withdraws the specified amount from customer’s account.
  • TestDB.java: Tests the connection to the database. The servlet uses a traditional JDBC API to test the connection to the database.
  • Index.jsp: JSP page with options to deposit, withdraw, test connection and display database contents.

The sample application uses JPA to persist the data into the database. The JPA entity in this sample application is CustomerAccount.java, which represents the customer table in the relational database. The persistence.xml file is a standard configuration file in JPA which is part of the META-INF directory inside the JAR file. The code segment in Listing 1 represents the persistence unit definitions defined in the application’s persistence.xml file. The persistent-unit references the datasource that will be used by the application class. The configuration of this datasource will be described later. The persistence.xml file in the DevWorkSample.war sample file contains the entry depicted in Listing 1.

Listing 1. persistence.xml
<persistence-unit name="CustomerQuery">
  <jta-data-source>java:comp/env/jdbc/MyDataSource</jta-data-source>
  <class>CustomerAcct</class>

  <properties>
    <property name="openjpa.LockTimeout" value="30000" />
    <property name="openjpa.jdbc.TransactionIsolation" value="read-committed" />
    <property name="openjpa.Log" value="none" />
    <property name="openjpa.jdbc.UpdateManager" value="operation-order" />
  </properties>
</persistence-unit>

EntityManager is the interface used to interact with the persistence context and provides APIs to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The persistence unit defines the entities managed by the EntityManager instance. In the sample application, ServletDeposit.java is used to create an EntityManager, which finds the customer account based on customerNumber (primary key). The new credit is then added to the existing balance and set on the customer account. Listing 2 illustrates the usage of EntityManager.

Listing 2. Usage of EntityManager
InitialContext ctx = new InitialContext();
UserTransaction tx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
UserTransaction userTran = getUserTrans();
userTran.begin();
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
em.joinTransaction();
CustomerAccount customerAcct = em.find(CustomerAccount.class,customerNumber);
// add credit to existing balance
double money = customerAcct.getCustomerMoney().doubleValue()+ moneyToCredit;
// set new existing balance
customerAcct.setCustomerMoney(new BigDecimal(money));
printResults(out, moneyToCredit, customerAcct);
userTran.commit();
em.close();

(See Resources for more on OpenJPA.)

Dynamic changes to feature configuration

The Liberty profile enables you to provision only the features that your applications require. For example, if an application requires just a servlet engine, then the Liberty profile can be configured to only start the WebSphere Application Server kernel, the HTTP transport, and the web container. This radically improves the server start time and results in a small footprint, since it does not use the complete Java EE stack. Furthermore, if the application requires additional features, such as database connectivity, the Liberty profile configuration can be dynamically modified to include the JDBC feature, without needing to restart the server.

To download the DevworkSample.ear included with this article and import the application into your Eclipse environment:

  1. Navigate to File > Import > Web > WAR file.
  2. Select the DevworkSample.war file.

The sample application included here uses the Java Persistence API (JPA), for which you should add the jpa-2.0 feature to the server configuration. This feature provides support for applications that use application-managed and container-managed JPA, written to the JPA 2.0 specification.

To add the JPA feature:

  1. Open the Server Configuration editor, then perform either option:
    1. In the Servers view, right-click the server configuration and select Open.
    2. In the Project Explorer view, expand your server project and the server folder. Right-click the server.xml file and select Open.
  2. Select Feature Manager from Configuration Structure section and click Add.
  3. The Add Features panel provides a list of features (Figure 7). Select jpa-2.0 from the list and click OK.
    Figure 7. Select Liberty Profile feature to enable
    Select Liberty Profile feature to enable

    Click to see larger image

    Figure 7. Select Liberty Profile feature to enable

    Select Liberty Profile feature to enable

In the Liberty profile, the server features that you want loaded are declared in a server configuration file, server.xml. Server.xml contains a set of features that are enclosed within the <featureManager> element, with each individual feature contained within <feature> tags. When the JPA feature has been added to the server configuration, an element for the jpa-2.0 feature is added to the list of features in the server.xml file, as shown in Listing 3.

Listing 3. Features added to server.xml
<server>
    <featureManager>
        <feature>servlet-3.0</feature>
        <feature>localConnector-1.0</feature>
        <feature>jpa-2.0</feature>
    </featureManager>
</server>

The elements localConnector-1.0 and servlet-3.0 are part of feature list by default. There is no support for dynamic removal of the jpa-2.0 feature at run time

The Liberty profile server configuration is described in a series of elements in the server.xml configuration file. By default, the path and filename for the configuration root document file is <LibertyHome>usr/servers/server_name/server.xml.


Defining the data source

A data source can be defined in the application either via annotations or in the Liberty profile server configuration.

Defining the data source using annotations

Java EE 6 supports DataSourceDefinition annotations, which provides an easy way to define a data source and register it with JNDI. Data source properties that are specified as annotation definitions are shown in Listing 4.

Listing 4. Use of DataSourceDefiniton annotations
@DataSourceDefinition(
        name         = "java:comp/env/jdbc/db2",
        className    = "com.ibm.db2.jcc.DB2DataSource",
        databaseName = "SAMPLEDB",
        serverName   = "localhost",
        portNumber   = 50000,
        properties   = { "driverType=4" },
        user         = "user1",
        password     = "pwd1"
        )
 public class MyServlet extends HttpServlet {

    @Resource(lookup="java:comp/env/jdbc/db2")
    DataSource ds;
    Connection con = ds1.getConnection();
    Statement stmt = null;
     try {
        stmt = con.createStatement();
        // create a table
        stmt.executeUpdate("create table cities (name varchar(50)" + 
        "not null primary key, population int, county varchar(30))");
        // insert a test record
        stmt.executeUpdate("insert into cities values ('myHomeCity'," + 
        "106769, 'myHomeCounty')");
        // select a record
        ResultSet result = stmt.executeQuery("select county from cities" + 
        "where name='myHomeCity'");
        result.next();
        // display the county information for the city.
        System.out.println("The county for myHomeCity is " + result.getString(1));
     } 
    catch (SQLException e) {
    e.printStackTrace();
     } 
    finally {
    try {
      // drop the table to clean up and to be able to rerun the test.
      stmt.executeUpdate("drop table cities");
    } 
    catch (SQLException e) {
      e.printStackTrace();
    }				
    con.close();
  }
}

Defining the data source in the server configuration

The sample application uses the data source jdbc/MyDataSource. To define the data source in the Liberty profile server configuration using Developer Tools, right-click on the Liberty server configuration in Eclipse and select the option to add a new Shared Library. Provide the Shared Library Id, for example DB2, and provide the location to the DB2 JAR files as part of the shared library definition by adding, Fileset reference, as shown in the Figure 8.

Figure 8. Defining the data source in Liberty server configuration
Defining the data source in Liberty server configuration

Click to see larger image

Figure 8. Defining the data source in Liberty server configuration

Defining the data source in Liberty server configuration

When these steps are complete, a shared library pointing to the location of DB2 JDBC driver JAR or compressed files is added to the server.xml file, shown in Listing 5.

Listing 5. Shared library usage in server.xml
<library id="DB2">
<fileset dir="C:\db\java" 
      includes="db2jcc.jar, db2jcc_license_cisuz.jar, db2jcc_license_cu.jar"/>
</library>

Next, you need to add a new JDBC driver. Right-click on the Liberty profile server configuration. From the Shared Libraries menu, select the library with Id DB2 you created above. Provide the Id name for the JDBC driver definition, for example DB2Driver. Define a data source by right-clicking on the Liberty profile server configuration and choose the defined JDBC driver from drop down menu, as shown in Figure 9. For example, here the JDBC driver name is DB2Driver. Provide a JNDI name; in this case, jdbc/MyDataSource. You can specify the data source type; if you don't, the Liberty profile selects the following, in sequence, depending on which is available:

  1. javax.sql.ConnectionPoolDataSource
  2. javax.sql.DataSource
  3. javax.sql.XADataSource

Optionally, a ConnectionManager can also be defined to provide connection pool properties, such as Max and Min connections, that are needed for the application.

Figure 9. Datasource defined in Liberty profile server configuration
Datasource defined in Liberty profile server configuration

Click to see larger image

Figure 9. Datasource defined in Liberty profile server configuration

Datasource defined in Liberty profile server configuration

Right-click on the data source in the Configuration Structure section to add properties for JDBC Driver. For this sample application, add properties for DB2 JCC. Provide the name of the database, driver type, hostname and port number.

When this configuration is complete, the server.xml configuration file will be updated with corresponding entries for the data source. Listing 6 shows the example server.xml with the data source defined.

Listing 6. server.xml with data source defined
<jdbcDriver libraryRef="DB2" id="DB2Driver">
</jdbcDriver>
<dataSource jndiName="jdbc/MyDataSource" 
  jdbcDriverRef="DB2Driver"  type="javax.sql.XADataSource">
  <connectionManager numConnectionsPerThreadLocal="10" 
  id="ConnectionManager" minPoolSize="1"/>
  <properties.db2.jcc databaseName="testdb" 
  user="db2admin"  password="{xor}Oz1tPjsyNjE="/>
</dataSource>

Executing the sample application

From the Enterprise Explorer view in Eclipse, select the application DevworkSample and run the application, targeting the Liberty profile server that you created; for example, LibertyTestServer created earlier. The URL to access the web application is displayed in the Eclipse console. This is shown in Listing 7.

Listing 7. URL to access the application
[AUDIT   ] CWWKE0001I: The server LibertyTestServer has been launched.
[AUDIT   ] J2CA8000I: The connectionManager ConnectionManager is available.
[AUDIT   ] J2CA8004I: The dataSource default-0 is available as jdbc/MyDataSource.
[AUDIT   ] J2CA8000I: The jdbcDriver DB2Driver is available.
[AUDIT   ] CWWKZ0058I: Monitoring dropins for applications. 
[AUDIT   ] CWWKT0016I: Web application available (default_host): 
http://localhost:9080/DevworkSample/*
[AUDIT   ] CWWKZ0001I: Application DevworkSample started in 2.478 seconds.
[AUDIT   ] CWWKF0011I: The server LibertyTestServer is ready to run a smarter planet.

Accessing the URL in the browser will take you to the sample application’s home page (Figure 10), which displays options to withdraw and deposit money to a customer account, list customer details, test the connection to the database, and reset the database. (This sample application is best viewed in Internet Explorer and Eclipse internal web browser.)

Figure 10. Sample application home page
Sample application home page

Dynamic application updates

In the Liberty profile, deployed applications are monitored for updates, and the updates are dynamically applied to the running application. When files within a deployed application are added, removed, or modified, or entire application is replaced with an updated version, the previous version is automatically stopped, and the new version is started. This applies to applications that are deployed through configuration entries, and to those deployed from the dropins directory. The dynamic update behavior can be configured using Developer Tools.

Select Configuration Admin Service or Application Monitor in the server configuration design view and change the Application Update Trigger as required. The application update trigger property has three possible values:

  • polled: The runtime environment scans the deployed application files for changes using the time interval specified by the pollingRate property.
  • mbean: The runtime environment only looks for updates when prompted to do so through a call to an mbean. This is the mode that is used by the Developer Tools to update applications, unless you override it.
  • disabled: Application updates are not dynamically applied. To update a deployed application when this mode is active, uninstall then reinstall the application.

By default in Developer Tools, the updateTrigger property is set to mbean. Consider changing it to polled to get dynamic updates at regular intervals. The server.xml will have an entry for this property, as shown in Listing 8.

Listing 8. updateTrigger property
<applicationMonitor updateTrigger="polled" pollingRate="500ms" 
                    dropins="dropins" dropinsEnabled="true"/>

To enable or disable automatic publishing from Developer Tools to the Liberty profile runtime, click on the server name from the console to be able to see and set these options for dynamic application publishing:

  • Never publish automatically
  • Automatically publish when resource changes(default)
  • Automatically publish after a build event

By default, applications that improve performance and usability are run from the Eclipse workspace when supported by application type, but applications are deleted when the project is deleted.

Dynamic runtime

Changing the database

The database configured for the data source can be changed dynamically at run time without restarting the Liberty profile server or the application. Under Server Configuration, select properties for the configured driver (Figure 11) and change the database name.

Figure 11. Changing the database for the configured driver
Changing the database for the configured driver

Click to see larger image

Figure 11. Changing the database for the configured driver

Changing the database for the configured driver

When the database name is changed, the existing connections and transactions continue to be valid, but are not used for new application requests. The connections to the old database are closed when configuration parameters such as aged timeout, unused timeout, and so on, take effect.

After the changes are saved, the server configuration is updated at run time and the application will persist the data in the new database.

The log messages shown in Listing 9 are generated when a change in the data source becomes effective on the server.

Listing 9. Log messages when a change in data source is effective on server‘
[AUDIT   ] CWWKG0016I: Starting server configuration update. 
[AUDIT   ] J2CA8002I: The dataSource default-0 is modified.
[AUDIT   ] CWWKG0017I: The server configuration was successfully updated in 0.86 seconds.

Changing the data source for application

To change the application’s data source dynamically:

  • Create a new data source using the server configuration and add the driver properties pointing to the new database. If the data source is pointing to a database from different vendor, add new driver details (Figure 12).
    Figure 12. Changing driver details
    Changing driver details

    Click to see larger image

    Figure 12. Changing driver details

    Changing driver details
  • From the sample application servlets, update the new data source name to be looked up (Listing 10).
    Listing 10. Updating data source name in sample application
            @Resource(name = "jdbc/MyDataSourceNew", 
            type = javax.sql.DataSource.class,      
            shareable = true, authenticationType = AuthenticationType.CONTAINER)
  • Change persistence.xml to point to the new data source (Listing 11).
    Listing 11. Changing persistence.xml to point to new data source
    <persistence-unit name="CustomerQuery">
    <jta-data-source>java:comp/env/jdbc/MyDataSourceNew</jta-data-source>
    <class>myjpa.CustomerAcct</class>

After the configuration is saved, the application will be restarted and data will be persisted using the new data source without restarting the Liberty profile server.

The log messages shown in Listing 12 display in the console when the application is restarted.

Listing 12. Log messages printed in console when the application is started.
[AUDIT   ] CWWKG0017I: The server configuration was successfully updated in 0.5 seconds.
[AUDIT   ] CWWKT0017I: Web application removed (default_host): 
http://localhost:9080/DevworkSample/*
[AUDIT   ] CWWKZ0009I: The application DevworkSample has stopped successfully.
[AUDIT   ] CWWKT0016I: Web application available (default_host): 
http://localhost:9080/DevworkSample/*
[AUDIT   ] CWWKZ0003I: The application DevworkSample updated in 0.38 seconds.

Changing the data source properties

Table 2 lists the data source properties that can be changed using Developer Tools and describes how each configuration update is applied.

Table 2. Data source properties that can be changed using Developer Tools
Attribute nameHow the configuration update is applied
beginTranForResultSetScrollingAPIsThe update is effective immediately.
beginTranForVendorAPIsThe update is effective immediately.
commitOrRollbackOnCleanupThe update is effective immediately.
connectionManagerRefAll connections and the connection pool are destroyed. The data source is then managed by the new connection manager.
connectionSharingThe update is applied with each first connection handle in a transaction.
isolationLevelThe update is applied with new connection requests; current connections retain their isolation level.
jdbcDriverRefAll connections and the connection pool are destroyed. The new JDBC driver is then used.
jndiNameAll connections and the connection pool are destroyed. The new JNDI name is then used.
propertiesRefIf the data source is Derby Embedded, all connections and the connection pool are destroyed before new properties go into effect. For other JDBC drivers, the new properties go into effect with new connection requests.
queryTimeoutThe update is effective immediately.
statementCacheSizeThe statement cache is resized upon next use.
supplementalJDBCTraceAll connections and the connection pool are destroyed. The new setting is then used.
syncQueryTimeoutWithTransactionTimeoutThe update is effective immediately
transactionalThe update is applied to new connections and existing connections not in use from the connection pool.
typeAll connections and the connection pool are destroyed. The new setting is then used.

Updating connection pooling configuration at run time

Run time updates can be made to the data source connection pooling configuration without restarting the Liberty profile server. Table 3 lists the connection pool properties. In this case, all configuration updates are applied immediately.

Connection pool properties
Attribute nameHow the configuration update is applied
agedTimeoutThe update is effective immediately.
connectionTimeout
maxIdleTime
maxNumberOfMCsAllowableInThread
maxPoolSize
minPoolSize
numConnectionsPerThreadLocal
reapTime
purgePolicy
numConnectionsPerTheadLocal

Classloading in the Liberty profile

The Liberty profile server provides its own classloader to every Java EE application. The Liberty profile assumes some default settings for all Java EE applications so that they can access the supported specification APIs (for example, the Servlet APIs if the servlet feature is enabled), and the IBM APIs.

By default, Java EE applications do not have access to the third party APIs available in the Liberty profile. Liberty profile classloaders for enterprise Java applications have the ability to hide the classes that established the foundation implementation of the Liberty profile. This feature can isolate the applications from the internal libraries used by the Liberty profile.

The Liberty profile provides options for listing library references unique to an application’s classloader. From Server Configuration in Developer Tools, click on the Application :<applicationame> and Add ClassLoaderService. The options provided are:

  • Private Library Reference: Lists the library references unique to the classloader and class instances that are independent from class instances of other classloaders. The code in Listing 13 showing the privateLibrary tag, which corresponds to references unique to the classloader.
  • Shared Library Reference: Lists library class instances that are shared with other classloaders. The code in Listing 13 showing the commonLibrary tag corresponds to references shared with other classloaders.
Listing 13. An example server.xml with library references
<application id="DevworkSample" location="DevworkSample.war"
    	name="DevworkSample" type="war">
    	<classloader>
            <privateLibrary name="UnShared">
                <fileset dir="C:\example\notshared" includes="policy.jar"/>
            </privateLibrary>
            <commonLibrary name="Shared">
                <fileset dir="C:\sharedjars" includes="shared.jar"/>
            </commonLibrary>
        </classloader>
</application>

Troubleshooting data access applications

To enable traces in the Liberty profile server, logging properties can be set in either the bootstrap.properties or server.xml file:

  • bootstrap.properties: Bootstrap properties are set in this text file, which should be located in the server directory alongside the configuration root file server.xml. By default, the server directory is usr/servers/server_name. Add the line below to have the bootstrap.properties file to enable traces; this is the trace string for debugging problems in the data access application:

    com.ibm.ws.logging.trace.specification=WAS.j2c=all:RRA=all=enabled

  • Server.xml: Add the tag below to enable traces

    <logging traceSpecification="*=audit=enabled:WAS.j2c=all:RRA=all=enabled"/>

    The trace files will be generated at <Libertyhome>\usr\servers\<servername>\logs. Be aware that <LibertyHome> refers to the directory where the Liberty profile is installed.

Generating dump for support

The Utilities menu in Developer Tools can be used to generate a server dump to capture all service-related information for support. Right-click on the Liberty server from the Eclipse console and choose Utilities. Select Generate Dump for Support. The dump will be generated at location <LibertyHome>\usr\servers\<servername>\ .

Known issues

These known issues with data access applications in the Liberty profile require a configuration change:

  • Changing the JDBC data source at run time might result in JPA failures

    If not specified through properties, OpenJPA detects and calculates the database dictionary type when the first entity manager is created and the database connection is made. This database dictionary type is used for all entity managers that are subsequently created. If the JDBC data source is changed while an application is running, the entity manager factory does not detect this change and continues to use the old dictionary for operations against the new data source. This can result in failures if the database is changed to a different vendor. To resolve these failures, restart the application.

  • Changing a database to a different vendor

    Modifying the data source, JDBC driver, connection manager, and JDBC vendor properties at run time might result in JPA failures. If you update the configuration of the data source, JDBC driver, connection manager, or any of the JDBC vendor properties lists (for example, properties.db2.jcc or properties.oracle) while the server is running, you might see J2CA8040E <eng> failures. These failures state that multiple data source elements cannot be associated with a single connection manager. These failures are generated even if your configuration associates only one connection manager with the data source element. To resolve these failures, restart the application.

Liberty profile footprint

To enable monitoring of the Liberty profile, add the monitor-1.0 feature to the server configuration, as shown in Listing 15.

Listing 15. Example entry in server.xml file to enable monitoring in Liberty profile
<feature>monitor-1.0</feature>

Listing 16 illustrates the log messages in console.

Listing 16. Log messages in the console
[AUDIT   ] CWWKG0016I: Starting server configuration update. 
[AUDIT   ] CWWKG0017I: The server configuration was successfully updated in 0.86 seconds.
[AUDIT   ] CWWKF0012I: The server installed the following features: [monitor-1.0].
[AUDIT   ] CWWKF0008I: Feature update completed in 1.384 seconds.

Monitoring the Liberty profile from JConsole

Launch jconsole.exe from <Java installation folder>\bin. Start a New Connection and choose the Liberty profile server to monitor that is displayed by default (Figure 13). Figure 14 depicts a graph that shows the footprint for the Liberty profile server is only between 10 MB to 20 MB of memory.

Figure 13. JConsole new connection
JConsole new connection
Figure 14. Graph depicting memory footprint of Liberty Profile server
Graph depicting memory footprint of Liberty Profile server

Click to see larger image

Figure 14. Graph depicting memory footprint of Liberty Profile server

Graph depicting memory footprint of Liberty Profile server

Migrating from full profile to the Liberty profile

If you wish, the resources in WebSphere Application Server full profiles can be migrated to the Liberty profile. Listing 17 illustrates the resource.xml file from a full profile and Listing 18 illustrates the equivalent configuration in server.xml of the Liberty profile.

Listing 17. resource.xml file of a full profile
<resources.jdbc:JDBCProvider xmi:id="JDBCProvider_1321914412932" 
            providerType="DB2 Using IBM JCC Driver" isolatedClassLoader="false" 
            implementationClassName="com.ibm.db2.jcc.DB2ConnectionPoolDataSource" 
            xa="false">
   <classpath>${DB2_JCC_DRIVER_PATH}/db2jcc4.jar</classpath>
   <classpath>${DB2_JCC_DRIVER_PATH}/db2jcc_license_cu.jar</classpath>
   <classpath>${DB2_JCC_DRIVER_PATH}/db2jcc_license_cisuz.jar</classpath>
   <factories xmi:type="resources.jdbc:DataSource" xmi:id="DataSource_1321914498985"  
  name="DefaultDB2Datasource"      jndiName="jdbc/DefaultDB2Datasource"   
  providerType="DB2 Using IBM JCC Driver" authMechanismPreference="BASIC_PASSWORD" 
  authDataAlias="IBM-9NE5C7ONIG4Node01/dbuser2" relationalResourceAdapter="builtin_rra"
  statementCacheSize="10"  
  datasourceHelperClassname="com.ibm.websphere.rsadapter.DB2UniversalDataStoreHelper">
      <propertySet xmi:id="J2EEResourcePropertySet_1321914499000">
         <resourceProperties xmi:id="J2EEResourceProperty_1321914499000" 
         name="databaseName"   type="java.lang.String" value="TESTDB" 
         required="true" ignore="false"  confidential="false" 
         supportsDynamicUpdates="false"/>
         <resourceProperties xmi:id="J2EEResourceProperty_1321914499001" 
         name="driverType" type="java.lang.Integer" value="4"
         required="true" ignore="false"   confidential="false" 
         supportsDynamicUpdates="false"/>
<resourceProperties xmi:id="J2EEResourceProperty_1321914499002" name="serverName" 
type="java.lang.String" value="localhost" required="false" ignore="false" 
confidential="false" supportsDynamicUpdates="false"/>
<resourceProperties xmi:id="J2EEResourceProperty_1321914499003" name="portNumber" 
type="java.lang.Integer" value="50000" required="false" ignore="false" 
confidential="false" supportsDynamicUpdates="false"/>          
</propertySet>
<connectionPool xmi:id="ConnectionPool_1321914499012" connectionTimeout="180"   
maxConnections="10" minConnections="1"   reapTime="180" unusedTimeout="1800"    
agedTimeout="7200" purgePolicy="EntirePool" />
 <mapping xmi:id="MappingModule_1321914681786" mappingConfigAlias="" 
 authDataAlias="IBM-9NE5C7ONIG4Node01/dbuser2"/>
 </factories>
</resources.jdbc:JDBCProvider>
<systemLoginConfig xmi:id="JAASConfiguration_2">
<authDataEntries xmi:id="auth1" alias="IBM-9NE5C7ONIG4Node01/dbuser2"   
userId="dbuser2" password="{xor}LDcfLTo7Oz0=" />
</systemLoginConfig>
Listing 18. resource.xml of Liberty profile
<variable name="DB2_JCC_DRIVER_PATH" value="C:/Drivers/DB2" />
<library id="db2Lib">
   <fileset dir="${DB2_JCC_DRIVER_PATH}" includes="db2jcc4.jar
   db2jcc_license_cu.jar db2jcc_license_cisuz.jar" />
</library>
<dataSource id="DefaultDB2Datasource" jndiName="jdbc/DefaultDB2Datasource"
    statementCacheSize="10"  syncQueryTimeoutWithTransactionTimeout="false"
    isolationLevel="TRANSACTION_READ_COMMITTED"
    queryTimeout="10" >
   <jdbcDriver libraryRef="db2Lib"   javax.sql.ConnectionPoolDataSource=
   "com.ibm.db2.jcc.DB2ConnectionPoolDataSource"/>
   <properties.db2.jcc   databaseName="TESTDB"   driverType="4"
   serverName="localhost"   portNumber="50000"  user="dbuser2" 
    password="{xor}LDcfLTo7Oz0="  />
   <connectionManager connectionTimeout="180" maxPoolSize="10" 
   minPoolSize="1" reapTime="180"  maxIdleTime="1800" agedTimeout="7200" 
   purgePolicy="EntirePool"/>
</dataSource>

Packaging the Liberty profile server

A compressed file of your Liberty profile containing a server runtime environment, server configuration, and applications can be created using the included packaging wizard. Because a Liberty profile server is lightweight, it is useful to package up applications and the server in a compressed file. You can then store this package, distribute it to colleagues, use it to deploy the application to a different location or to another machine, or even embed it in your product distribution.

To package your Liberty profile environment:

  1. Stop the server.
  2. Right-click your Liberty profile server, and select Utilities > Package Server.
  3. In the Archive field on the Package Server panel, type a filename and path for your archive package, or click Browse to locate a filename and path. This filename can include a full path name. If the full path is omitted, a compressed file called package_file_name.zip is created in the ${server.output.dir} directory.
  4. In the Include field, select one of these options, depending on what you want in your packaged file:
    • All server content, which includes binary files
    • Only server configuration and applications
  5. Click Finish.

Conclusion

This article provided information about leveraging the features of the Liberty profile in IBM WebSphere Application Server V8.5. Configuration changes for accessing databases from a Liberty profile application can be made easily and are reflected dynamically to suit an iterative develop-publish-test cycle. Server footprint, troubleshooting data access problems, Liberty profile server packaging, and migrating applications from the WebSphere Application Server full profile to the Liberty profile were also described.

Acknowledgements

The authors thank Soloman J Barghouthi for his valuable suggestions and feedback, and David Cohen for providing his basic JPA sample application, which the authors modified for the purpose of this article.


Download

DescriptionNameSize
Code sampleDevWorkSample.war27 KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Mobile development
ArticleID=848651
ArticleTitle=Developing and running data access applications for the Liberty profile using WebSphere Application Server Developer Tools for Eclipse
publish-date=12052012