Mindmajix

JBOSS Tutorial

JBOSS Tutorial

This tutorial gives you an overview and talks about the fundamentals of JBOSS.

Java EE Overview and Architecture

1.1 What is Java EE?

  • Java EE is an open and standard-based platform for developing, deploying, and managing multi-tier, web-enabled, server-centric, and component-based enterprise applications
  • As a super-set of Java SE, Java EE adds additional specifications, libraries, documentation, and tools.

1.2 Open and Standard-based

  • Single specification, multiple competing implementations
  • Implementations available as both OSS/free and high-end commercial
  • Vast community resources: books, tutorials, guides, examples, etc.
  • Large developer pool
  • Application portability

Some of Java EE Application Servers available on the market today:

  • Apache Tomcat (Servlet/JSP container only)
  • Oracle Web Logic
  • IBM Websphere
  • JBoss AS
  • Oracle Application Server 10g
  • Glass fish application server
  • SAP AG Web Application Server
  • Sun Java System Application Server

1.3 Multi-tier

OO framework for integrating together:

  • Clients (e.g. web browsers)
  • Access and presentation components
  • Business components (e.g. ecommerce business logic)
  • Data-stores (e.g. RDBMS)

System-level separation of concerns

Screenshot_1

Figure 1. Multi-tier Architecture

  • Client Tier usually consists of thin clients like web browsers and it makes the request into the Web Tier over HTTP.
  • Client Tier (B2B) is a set of external applications that makes requests into the Business Tier through Web Services over SOAP or directly through Java’s RMI.
  • Web Tier is usually implemented with Servlets, JSPs, and simple JavaBeans, based on the Model-View-Controller design pattern.
  • Business Tier is composed of EJBs and/or plain old Java objects (POJOs).
  • Data Access Tier is either managed by the applications (e.g. BMP, DAO), O/R mapping tools (e.g. Hibernate), or through Container Managed Persistence (CMP).
  • Connector/Messaging Tier allows asynchronous access to legacy systems or other external systems.
  • Legacy/External Tier consists of enterprise information systems.
  • Data Tier is usually composed of RDBMS and/or LDAP Directory Servers.

1.4 Web-Enabled

  • By using the Servlet/JSP technology, Java EE applications are automatically web-enabled:
    • Efficient, Java/OO, Easy, I18N, MVC
  • Complete support for web-services
    • Clients
    • End-points

1.5 Server Centric

  • Java EE apps run within a Java EE application server that provides all middle-tier services.
  • Thin (web-based) clients
  • Support for rich clients through RMI, Web Services, etc.
    • The design of such clients is beyond the scope of Java EE

1.6 Component-Based Distributed Architecture

Screenshot_2

Java EE applications and services are built out of components that can run in a single or multiple (distributed) Java EE Application Server instances.

1.7 Enterprise Applications

  • Java EE applications are made up of:
    • Presentation logic
    • Business logic
    • Data access logic and model
  • Java EE facilitates separation of concerns

The goal of Java EE is to significantly reduce the cost, time, and complexity of developing and managing multi-tier enterprise applications

1.8 Java EE Services

Java EE Application Server handles:

  • Concurrency, Scalability, Availability
  • Security
  • Persistence, Transactions
  • Life-Cycle Management
  • Application Components focus on:
  • Presentation
  • Business Logic

Overview of JBoss Application Server

2.1. JBoss Organization

  • JBoss – The Professional Open Source Company
  • Focuses on middleware software and services – JBoss Enterprise Middleware Suite (JEMS)
  • Software is open source and free
  • Makes money on services
  • Acquired by Red Hat in April 2006 for $420M

JBoss Enterprise Middleware Suite (JEMS):

  • Application Server (JBoss AS, Tomcat)
  • O/R Mapping and Persistence (Hibernate)
  • Portal Platform (JBoss Protal)
  • Business Process Management and Rules (JBoss jBPM, JBoss Rules)
  • Object/Data Cache (JBoss Cache)
  • Distributed Transaction Management (JBoss Transactions)
  • Development Tools (JBoss Tools plugin for Eclipse)

2.2. JBoss AS Background

  • Established in 1999 as an open-source EJB container
  • Version 2.x becomes a full J2EE application server
  • Version 3.x is the production series – based on JMX microkernel and service-oriented architecture (May 2002)
  • Version 4.x explores the aspect-oriented middleware services, adds support for EJB 3 (September 2004)
  • Version 5.x comes with JBoss Microcontainer (also a stand-alone project) and replaces JMX Microkernel of the 3.x and 4.x JBoss series (December 2008)
  • Version 6.x to add support for Java EE 6 APIs and Profiles. Replaces JBoss Messaging with HornetQ (6.0.0.M3 released in April 2010)

2.3. Highlights of JBoss AS

  • Enterprise-class reliability, performance, scalability, and high-availability
  • Zero-cost product license, to download, use, embed, and distribute
  • Open-source
  • Built for standards – provides a safe choice for portable applications (interoperable)
  • Service-oriented architecture provides consistency, makes it embeddable
  • Aspect-oriented architecture simplifies interaction with middleware services
  • 24×7 professional support by the core development team
  • Active developer community
  • Over 5 million downloads
  • 25+% market share
  Note
JBoss AS 5 has passed the Java EE 5 Technology Compatibility Kit (TCK) test suite (100%).

2.4. What is new in JBoss AS 5?

  • New kernel ⇒JBoss Microcontainer
    • is a refactoring of old JMX Microkernel (JBoss AS 3.x and 4.x)
    • the core of JBoss AS 5
  • New messaging provider ⇒JBoss Messaging
    • Replaces old JBossMQ (shipped with JBoss AS 4.x series)
  • One of the first application servers to implement EJB 3.0 specification (dating back to 4.x series)
  • Reliable transaction manager ⇒JBoss TS
    • more than 20 years of expertise in transaction management
  • JBoss Webbased on Apache Tomcat 6.0
  • JBoss WS 3.0(support for JAX-WS/JAX-RPC)
    • can be replaced by Sun Metro or Apache CXF for example
  • Two new configurations:
    • standard: Java EE compliant configuration.
    • web: provides support for JTA/JCA and JPA in addition to the Servlet/JSP container. The server can only be accessed through the http port.

2.5. JBoss AS Architecture

“JBoss AS is assembled from a set of independent, yet cooperating components and services that are neatly packaged and fully hot-deployable. It is architected to be seamlessly embeddable in applications, and the nature of its embedding is completely customizable to the requirements of the application itself. Only the critical and necessary application server components, therefore, need to be brought along as part of the application’s baseline footprint. Developers can also easily create and add their own services to the system, thus ensuring that custom services exhibit the same consistent behavior as the JBoss standard set of services.”

Figure 2. JBoss AS 4.x Architecture

 

Figure 3. JBoss AS 5.x Architecture

2.6. JBoss Microcontainer Layer

JBoss Microcontainer is an inversion of control (IoC) framework. IoC frameworks let you create, configure and wire up simple Java objects (POJOs). Classes don’t need special coding to be usable. The objects created usualy represent the modules of your application.

  • Replaces JMX-based Microkernel, though still supports all JMX Microkernel features
  • IoC framework similar to Spring IoC
  • POJO based kernel (no need for Standard/XMBean or MBeanProxy)
  • Simplified and improved lifecycle management
  • Additional control over dependencies
  • Transparent AOP integration
  • Virtual File System (VFS)
  • Virtual Deployment Framework
  • OSGi class-loading

2.7. Services Layer

  • Service-oriented architecture – service is either defined as a POJO or a JMX Managed Bean (use the JMX kernel, still available in JBoss 5.x but is created by JBoss Microcontainer).
  • Services are hot-pluggable
  • Makes it possible to tune the system for just the required services to lower the overall footprint (easier to secure and tune)
  • Easy to define new services and package them as SARs (service archives) or JARs (Java ARchives)
  • Examples: Servlet/JSP container, EJB container, transaction management, messaging, connection pooling, security etc.

2.8. Aspect Layer

Increase the modularity of an application by allowing the separation of cross-cutting concerns (e.g logging is often required in many parts of your application).

  • Based on aspect-oriented programming model (AOP)
  • Defines cross-cutting simple-to-use services
  • Makes it possible to add object persistence, caching, replication, remoteness, security, etc. late in the development cycle by annotating existing plain-old-java-objects (a.k.a POJOs)
  Note
Available since JBoss AS 4

2.9. Application Layer

  • This is where Java EE applications reside
  • This layer deals with the business logic while leaving the container services up to JBoss AS
  • Portable – Independent of JBoss AS

2.10. JBoss AS Services

  • JBoss Microcontainer – POJOs services container
  • JBoss Microkernel – JMX MBean server (One of the primary POJOs created by JBoss Microcontainer)
  • Aspect-oriented Framework
  • Web Application Services – based on Tomcat (Servlet, JSP, JSF)
  • Enterprise Services: EJB, ORB, JNDI, JTA
  • Web Services – based on SOAP, WSDL, UDDI, and XML
  • Messaging Services: JMS, JDBC, JCA
  • Persistence Services – Hibernate O/R mapping and transparent persistence
  • HA Services: clustering, fail-over, load-balancing, distributed deployments
  • Security Services – based on JAAS
  • Console Services – monitoring, configuration, deployment, management, lifecycle

2.11. JBoss AS Requirements

  JBoss 3.2.x JBoss 4.x JBoss 5.x
Java (JDK) 1.3+ 1.4-1.5+ 1.5+
OS/Platform Any Java-compliant Any Java-compliant Any Java-compliant
Memory – RAM 128MB 512MB 512MB
CPU 266MHz 400MHz 400MHz
Disk 100MB 100MB 100MB
DB (Optional) Any JDBC-Compliant Any JDBC-Compliant Any JDBC-Compliant

3. Installing JBoss AS3.1. Getting and Installing Java

  • Download Java SE 6 JDK from http://java.sun.com/javase/downloads/index.jsp or http://java.sun.com/products/archive/ (for Java SE 5 JDK)
  • On UNIX run the installer or uncompress the distribution into a directory of your choice
  • On Windows, run the installer
    • Avoid installing Java into a directory that contains spaces or other special characters (e.g. under C:\Program Files)
    • You can choose not to install “Public JRE”, demos, and source components

3.2. Configuring Java

  • Set JAVA_HOME to point to the directory where you installed Java and add $JAVA_HOME/bin to your PATH
    • On Windows, add JAVA_HOME System Variable under Start -> Settings -> Control Panel -> System -> Advanced -> Environmental Variables and prefix the existing PATH variable with %JAVA_HOME%\bin;.
    • On UNIX-like systems, make these changes in your shell’s configuration file (e.g. ~/.bashrc): export JAVA_HOME=/path/to/java-install-dir and export PATH=$JAVA_HOME/bin:$PATH
  • Test that java -version prints the expected Java version
  • Test that javac prints usage message
  • This verifies that JDK is installed (vs. JRE)

3.3. Getting JBoss AS

  Note
You can either download jboss-<version>.zip or jboss-<version>-jdk6.zip depending on the version of Java you installed. Generally, Java 6 is preferred as it is faster, offers better management features, and it is backwards compatible with Java 5.

 

How to build from source?

  1. Get Ant from http://ant.apache.org/
  2. Uncompress it in a directory like C:\Ant
  3. Set ANT_HOME to point to the directory where you installed Ant
  4. Add $ANT_HOME/bin (on Linux), %ANT_HOME%\bin (on Windows) to your PATH
  5. get jboss-<release>-src.tar.gz from http://www.jboss.org/jbossas/downloads
  6. unzip it
  7. browse to build directory and run ant
  8. Once finished the binaries will be under jboss-<release>.GA-src\build\output\jboss-<release>.GA

3.4. Installing JBoss AS 5

  • Unpack the compressed archive
    • This is the typical installation method because it is the easiest
  • Alternatively, install the source-built binary
    • Not a common installation method
  • Set JBOSS_HOME to the root folder of JBoss.
  • You can also add $JBOSS_HOME/bin (Linux) or %JBOSS_HOME%\bin (Windows) to your PATH in case you want to run your server from the command-line.

Note: Even though this is supported, avoid installing/unpacking JBoss AS into a directory path that contains spaces or any other special characters. There is no requirement for the installation directory to be owned by “root” (or any other privileged user). JBoss AS does not require super-user privileges, since none of the default ports are within the 0-1023 port range, which is considered privileged on many Unix-like systems.

4. JBoss Directory Structure

4.1. JBoss AS Directory Structure

JBossORG-EULA.txt       copyright.txt           lib/

bin/                    docs/                   readme.html

client/                 jar-versions.xml        server/

common/                 lgpl.html

  • Root dir known as home.dir or $JBOSS_HOME
  • Understanding the layout is important:
    • Locating libraries
    • Updating configuration
    • Deploying apps and services

When JBoss AS is installed (uncompressed), the following directories are created:

  • ${jboss.home.dir}/bin
  • ${jboss.home.dir}/client
  • ${jboss.home.dir}/common
  • ${jboss.home.dir}/docs
  • ${jboss.home.dir}/lib
  • ${jboss.home.dir}/server

4.2. The bin Directory

README-service.txt      run.conf                twiddle.sh

classpath.sh            run.conf.bat            wsconsume.bat

jboss_init_hpux.sh      run.jar                 wsconsume.sh

jboss_init_redhat.sh    run.sh                  wsprovide.bat

jboss_init_suse.sh      service.bat             wsprovide.sh

jbosssvc.exe            shutdown.bat            wsrunclient.bat

password_tool.sh        shutdown.jar            wsrunclient.sh

probe.bat               shutdown.sh             wstools.bat

probe.sh                twiddle.bat             wstools.sh

run.bat                 twiddle.jar

JBoss AS ${jboss.home.dir}/bin directory contains startup/shutdown scripts, bootstrap libraries, Web Services and server management utilities:

  • sh: A tool to determine JBoss classpaths (both client and server)
  • sh and jboss_init_suse.sh: JBoss system control scripts for RedHat and SuSE systems
  • sh and probe.bat: used for discovering JBoss AS clusters.
  • sh and run.bat: Scripts for starting JBoss AS
  • jar: Bootstrap code for starting JBoss AS
  • bat: Script to manage JBoss as a Windows service.
  • sh and shutdown.bat: Scripts for shutting down JBoss AS (including remote instances)
  • jar: Bootstrap code for shutting down JBoss AS
  • sh and twiddle.bat: Scripts for running JBoss AS command-line management client (based on JMX)
  • jar: Bootstrap code for the JMX management (instrumentation) client
  • wsconsume, wsprovide, wsrunclient and wstools are utilities for Web Services.

4.3. The client Directory

  • Contains the Java libraries (JARs) required for clients that run outside the JBoss AS containers, such as:
    • Web Service clients
    • EJB clients
    • JMX clients
  • Used by external applications that need to access JNDI resources
  • On Unix, to get the client CLASSPATH, run: ${jboss.home.dir}/bin/classpath.sh -c
  • As of JBoss 5, the file client/jbossall-client.jar contains references to other JARs via Class-Path setting in its META-INF/MANIFEST.MF This makes it possible for external JBoss clients to just reference this one JAR file as opposed to many of them.
  Note
We will use the client/ directory later with some clients (like JMS) that will run outside the JBoss AS.

4.4. The common directory

  • Contains the lib directory (also known as common.lib.url).
    • lib folder contains the common libraries shared by all server configurations (more on this later)
    • This directory is new to JBoss 5. In earlier versions of JBoss a number of common libraries were simply duplicated for each configuration set.

4.5. The docs Directory

dtd/            examples/       licenses/       schema/         tests/

  • Examples: sample configuration: JMX, JCA, JMS, NetBoot, etc.
    • Contains excellent examples for many different configurations. For example, the file docs/examples/jca/mysql-ds.xml can serve as a starting point in defining a MySQL-based Data Source (shared database connection-pool) in JBoss AS.
  • DTDs and Schemas for J2EE and JBoss XML files
    • Contain all J2EE-referenced XML DTD and XSD files, making it simple to validate XML files and lookup the relevant “grammar” when making configuration changes. DTDs were employed by J2EE 1.3 and JBoss 4 whereas Schemas are used since J2EE 1.4 and JBoss 5.
  • Licenses for all JBoss components
  • Unit test results

4.6. The lib Directory

  • Contains JBoss bootstrap libraries (core libraries)
  • Do not place your own files here or remove any of the existing files
  • As an example, you’ll find here the JBoss Micro container and the old JMX kernel.

4.7. The server Directory

all/            minimal/        node2/          web/

default/        node1/          standard/

  • Known in JBoss AS server.base.dir
  • Root of server configuration sets
  • JBoss comes with minimal, default and all
  • Version 5.x comes with 2 new configurations: standard and web
  • Defaults to configuration set in server/default
  • Configuration sets contain the actual JBoss services

To change the configuration set that JBoss AS runs with, execute: bin/run.sh -c <configuration-set>

For example:

bin/run.sh -c minimal

bin/run.sh -c all

Configuration sets:

minimal/

  • Includes support for JNDI and logging. It does not contain any other J2EE services like Servlet/JSP container, EJB container, or JMS.
  • Can serve as a starting point when creating your own configuration sets

default/

  • As the name implies, this is the default Java EE 5 configuration. Contains the most used services except JAXR, IIOP and clustering services.

all/

  • This configuration extends the default configuration set and also include JAXR, IIOP and clustering services

standard/

  • Certified Java EE 5 configuration compliant.
  Note
The major difference with the existing configurations is that call-by-value and deployment isolation are enabled by default, along with support for rmiiiop and juddi (taken from the all config).

web/

  • Lightweight web container profile (Java EE 6 web profile). It provides support for JTA/JCA and JPA except for the servlet/JSP container.

4.8. The server Configuration Sets

all/            minimal/        node2/          web/

default/        node1/          standard/

  • The currently running server/<server> dir is known in JBoss AS as server.home.url
  • The name of the server (e.g. “default”) is known as server.name
  • Configuration sets are independent of each other
  Note
Each configuration set has to have at least the following four directories: conf/, deploy/, deployers/, and lib/. Other (referenced) directories such as data/, log/, tmp/, and work/ are automatically created on JBoss AS startup if they do not exist.

4.9. The default/conf Directory

bindingservice.beans/           jbossts-properties.xml

bootstrap/                      jndi.properties

bootstrap.xml                   login-config.xml

java.policy                     props/

jax-ws-catalog.xml              standardjboss.xml

jboss-log4j.xml                 standardjbosscmp-jdbc.xml

jboss-service.xml               xmdesc/

  • Known in JBoss as server.config.url
  • Contains a bootstrap descriptor (jboss-service.xml) that defines which services are loaded for the lifetime of the instance

The files in directory ${jboss.server.config.url} :

  • bootstrap/*: Bootstrap descriptors for core micro container services defined in xml
  • xml: Defines the core micro container beans to load during bootstap
  • jboss-service.xml: Defines the core JMX services configurations
  • properties: Specifies a set of properties that are passed to JNDI when new InitialDirContext() is called within JBoss
  • jboss-log4j.xml: Configuration file for the logging service (Log4J) defining log filters, priorities, and destinations
  • login-config.xml: Defines security realms used for authentication and authorization (JAAS)
  • props/*.properties: Java property files (usually used for JAAS realms)
  • policy: Placeholder for security permissions (Java Security Manager). Grant-All by default
  • xml: Configuration file for the standard EJB container
  • standardjbosscmp-jdbc.xml: Configuration file for the standard JBossCMP engine
  • xmdesc/*-mbean.xml: XMBean descriptors for services configured in the jboss-service.xml file
  • props/*: property files defining users and roles for the jmx-console
  Important
Any changes to files in this directory require a full server restart in order to take effect.

4.10. The default/data Directory

hypersonic/             wsdl/

tx-object-store/        xmbean-attrs/

  • Known in JBoss as server.data.dir
  • Location where some services store private content on the file system
    • Hypersonic DB – built-in (by default use as the temporary message store by JMS)
    • XMBeans attribute persistence (not enabled by default)
    • Transaction objects (temporary storage of objects during the two-phase commit process)
  • This directory is not directory exposed to the end users (e.g. though the web interface)
  Note
Unless you use Hypersonic DB, the contents of this directory (including the directory itself) can be cleared (deleted) between JBoss restarts.

4.11. The default/deploy Directory

CurrencyConverterApp.ear                jsr88-service.xml

ROOT.war/                               legacy-invokers-service.xml

admin-console.war/                      mail-ra.rar

cache-invalidation-service.xml          mail-service.xml

ejb2-container-jboss-beans.xml          management/

ejb2-timer-service.xml                  messaging/

ejb3-connectors-jboss-beans.xml         monitoring-service.xml

ejb3-container-jboss-beans.xml          my-ws.war

ejb3-interceptors-aop.xml               printservice.sar/

ejb3-timerservice-jboss-beans.xml       profileservice-jboss-beans.xml

fortune.war/                            profileservice-secured.jar/

hdscanner-jboss-beans.xml               properties-service.xml

hsqldb-ds.xml                           quartz-ra.rar

http-invoker.sar/                       remoting-jboss-beans.xml

jboss-local-jdbc.rar                    schedule-manager-service.xml

jboss-xa-jdbc.rar                       scheduler-service.xml

jbossweb.sar/                           security/

jbossws.sar/                            sqlexception-service.xml

jca-jboss-beans.xml                     transaction-jboss-beans.xml

jms-ra.rar                              transaction-service.xml

jmx-console.war/                        uuid-key-generator.sar/

jmx-invoker-service.xml                 vfs-jboss-beans.xml

jmx-remoting.sar/                       xnio-provider.jar/

  • Dynamic deployment content directory
  • This is where applications and services are deployed
  • Default location used by hot deployment service
  • Contains code and configuration files for all services

Some files in the deploy directory include:

  • war: is the / root web application
  • cache-invalidation-service.xml – Custom invalidation of EJB caches via JMS
  • ejb2-container-jboss-beans.xml – UserTransaction integration bean for EJB2 container
  • ejb2-timer-service.xml – EJB timer service bean
  • ejb3-connectors-jboss-beans.xml – EJB3 remoting transport bean
  • ejb3-container-jboss-beans.xml – UserTransaction integration bean for EJB3 container
  • ejb3-interceptors-aop.xml – AOP for EJB3
  • ejb3-timer-service.xml – alternate quartz based timer service
  • hdscanner-jboss-beans.xml – hot deployment scanner bean
  • hsqldb-ds.xml – Hypersonic embedded database and related connection factories
  • http-invoker.sar – Detached invoker that supports RMI/HTTP
  • jboss-local-jdbc.rar – JCA to DataSource adaptor for JDBC drivers
  • jboss-xa-jdbc.rar – JCA to XADataSource adaptor for JDBC drivers.
  • sar – Tomcat Servlet/JSP Engine
  • sar – The JBoss service that supports web services
  • jca-jboss-beans.xml – Connection management facilities for integrating JCA adaptors into JBoss AS
  • jms-ra.rar – JMS resssource adapter
  • messaging/connection-factories-service.xml – DLQ, ExpiryQueue JMS connection factory
  • messaging/destinations-service.xml – Message persistence store service
  • messaging/jms-ds.xml
  • messaging/legacy-service.xml
  • messaging/messaging-jboss-beans.xml – JMS security and management beans
  • messaging/messaging-service.xml – Core messaging service
  • messaging/remoting-bisocket-service.xml – JMS remoting service layer
  • jmx-console.war – Web application that provides HTML interface to manage MBean server
  • jmx-invoker-service.xml – RMI to JMX adaptor into JBoss
  • jmx-remoting.sar –
  • legacy-invokers-service.xml –
  • jsr-88-service.xml –
  • mail-ra.rar – Resource adaptor that provides a JavaMail connector
  • mail-service.xml – JavaMail session service (SMTP)
  • monitoring-service.xml – Configuration for alert monitors such as email or console listeners
  • properties-service.xml – JavaBeans PropertyEditors and definition of system properties
  • admin-console.war – admin console for JBoss AS
  • scheduler-service.xml – JBoss scheduling service
  • sqlexception-service.xml – Vendor-specific SQL exception handler
  • security/security-jboss-beans.xml – Security domain related beans
  • security/security-policies-jboss-beans.xml – Security authorization for EJB and web authorization
  • transaction-jboss-beans.xml – JTA transaction manager related beans
  • uuid-key-generator.sar – UUID-based key generation facility

4.12. The default/deployers Directory

alias-deployers-jboss-beans.xml         jboss-threads.deployer/

bsh.deployer/                           jbossweb.deployer/

clustering-deployer-jboss-beans.xml     jbossws.deployer/

dependency-deployers-jboss-beans.xml    jsr77-deployers-jboss-beans.xml

directory-deployer-jboss-beans.xml      logbridge-jboss-beans.xml

ear-deployer-jboss-beans.xml            messaging-definitions-jboss-beans.xml

ejb-deployer-jboss-beans.xml            metadata-deployer-jboss-beans.xml

ejb3.deployer/                          seam.deployer/

hibernate-deployer-jboss-beans.xml      security-deployer-jboss-beans.xml

jboss-aop-jboss5.deployer/              webbeans.deployer/

jboss-ejb3-endpoint-deployer.jar        xnio.deployer/

jboss-jca.deployer/

  • Contains all the JBoss AS services that are used to recognize and deploy different application and archive types.

Some files in the deployers directory:

  • hibernate-deployer-jboss-beans.xml – Deployer for Hibernate archives (HAR)
  • ejb-deployer-jboss-beans.xml – Service responsible for deploying EJB JAR files
  • ear-deployer-jboss-beans.xml – Service responsible for deploying EAR files
  • deployer – Service responsible for deploying WAR files
  • jboss-aop-jboss5.deployer – Deployer that sets up Aspect Manager Service and deploys AOP applications
  • etc…
  Note
This directory is new as of JBoss AS 5

4.13. The default/lib Directory

  • Directory referred to by the bootstrap code when loading the configuration set
  • Known within JBoss as server.lib.url
  • This directory is for Java code (JARs) to be used both by the deployed applications and JBoss AS services
  • If you have Java libraries that you need to be made available to all your applications/services, these can be placed in the ${jboss.server.lib.url}
  • Similarly, you would also use this directory for Java libraries that need to be used by both your applications/services, and JBoss AS services.
    • A typical example of this is a JDBC driver that is needed by JBoss AS to manage a pool of database connections, as well as your code, which implicitly uses it to interact with the database server.
  Note
As of JBoss 5, some JARs that used to reside in this directory have been moved to common/lib in order to share them with other configuration sets.

4.14. The default/log Directory

  • Known within JBoss as server.log.dir
  • Default destination directory for JBoss AS log files (3 log files)
  • log – logs boot process until logging service starts
  • log – takes over once the logging service is initialized from ${jboss.server.config.url}/jboss-log4j.xml
  • log – audit security
  • Default startup log priority: DEBUG
  • STDOUT and STDERR are logged to console

By default:

  • Log file log is rolled over daily (with the “.yyyy-MM-dd” extension)
  • Existing logs are overwritten on [re]start
  • Old log files are not automatically cleaned by the server during runtime

Since the logging system is managed by Log4J it can be easily configured to:

  • Roll over logs hourly
  • Roll over logs by size (e.g. 500KB)
  • Automatically remove old logs
  • Log to SMTP, SNMP, Syslog, JMS, etc.

This directory can be cleared (deleted) between JBoss restarts.

4.15. The default/tmp Directory

  • Known in JBoss as server.temp.dir
  • Used by JBoss AS to store temporary files such as unpacked service and application deployments
  • Deployments are automatically removed on server shutdown

This directory can be cleared (deleted) between JBoss restarts.

  Note
Unpacked deployments (e.g. expanded WAR files) are not copied over. Packed deployments (WAR, EAR, RAR) are uncompressed, whereas JARs and XML-described services are copied over.

4.16. The default/work Directory

  • Directory where compiled JSP .java and .class files reside
  • Also contains cached TLDs
  • Very useful for debugging problems in JSPs

Java Server Pages (.jsp files) are automatically compiled into Java Servlets (.java file) and then into Java byte-code (.class files) by Tomcat (the embedded servlet engine running within JBoss AS).

Many JSP errors are easier to fix when developers are able to look at the compiled .java files and match the line numbers to error/exception messages.

Unless you care to preserve compiled JSPs, this directory can be cleared (deleted) between JBoss restarts.

5. Controlling the Life-Cycle of JBoss AS

5.1. Starting JBoss AS

  • To start JBoss, run $JBOSS_HOME/bin/run.sh on Unix/Linux and %JBOSS_HOME%\run.bat on Windows
  • The script figures out JBOSS_HOME by itself – though it does not hurt to have it pre-specified.
  • By default, this script runs the default configuration set
    • Alternative configuration set can be specified: ./run.sh -c <configuration_set_name>
  • By default, this script binds JBoss AS to 0.0.1 (for security reasons) making it inaccessible from the outside world
    • To bind JBoss to a specific address, execute: ./run.sh -b 10.1.2.3 or ./run.sh –host=10.1.2.3
    • To bind JBoss to all addresses, execute: ./run.sh -b 0.0.0.0 or ./run.sh –host=0.0.0.0
  • To start JBoss as a system service
    • On Unix/Linux, use a script like sh
      • Copy (or symbolically link) this script to /etc/init.d/jboss
      • Edit the script as needed (to specify user, IP, and file paths)
      • Add #chkconfig: 3 80 20 and #description: JBoss to this script
      • Run chkconfig –add jboss
    • On Windows use JavaService (http://forge.objectweb.org/projects/javaservice/), which comes with an installation script for JBoss

usage: run.bat [options]

options:

-h, –help                    Show this help message

-V, –version                 Show version information

—                            Stop processing options

-D<name>[=<value>]            Set a system property

-d, –bootdir=<dir>           Set the boot patch directory; Must be absolute or url

-p, –patchdir=<dir>          Set the patch directory; Must be absolute or url

-n, –netboot=<url>           Boot from net with the given url as base

-c, –configuration=<name>    Set the server configuration name

-B, –bootlib=<filename>      Add an extra library to the front bootclasspath

-L, –library=<filename>      Add an extra library to the loaders classpath

-C, –classpath=<url>         Add an extra url to the loaders classpath

-P, –properties=<url>        Load system properties from the given url

-b, –host=<host or ip>       Bind address for all JBoss services

-g, –partition=<name>        HA Partition name (default=DefaultDomain)

-m, –mcast_port=<ip>         UDP multicast port; only used by JGroups

-u, –udp=<ip>                UDP multicast address

-l, –log=<log4j|jdk>         Specify the logger plugin type

  Note
On Unix/Linux, run.sh (and shutdown.sh) source JVM/runtime options from run.conf file whereas on Windows run.bat specifies those options internally.

5.2. Verifying JBoss AS Startup

  • JBoss has successfully started when in its console window you can see a line like this:

13:26:33,625 INFO  [ServerImpl] JBoss (Micro container) [5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 2m:20s:844ms

  • If you see any exception traces, then there was a problem starting one or more of the JBoss services. Examine the error messages before continuing. A common problem is a port conflict: another server (possibly another instance of JBoss AS itself) is running on one or more of the required JBoss AS ports.
  • Point your browser to http://localhost:8080/status to verify the server startup.

5.3. Stopping JBoss AS

  • If started in foreground using the run script, simply hit CTRL+C
  • If running in the background as an OS service, stop it just like any other OS service
    • /etc/init.d/jboss stop (on UNIX/Linux)
    • kill -TERM <jboss-pid> (on UNIX/Linux)
    • NET STOP JBoss (on Windows)
  • Use the shutdown script (remote shutdown): $JBOSS_HOME/bin/shutdown.sh -S (bat on Windows)

A JMX client to shutdown (exit or halt) a remote JBoss server.

usage: shutdown [options] <operation>

options:

-h, –help                Show this help message (default)

-D<name>[=<value>]        Set a system property

—                        Stop processing options

-s, –server=<url>        Specify the JNDI URL of the remote server

-n, –serverName=<url>    Specify the JMX name of the ServerImpl

-a, –adapter=<name>      Specify JNDI name of the MBeanServerConnection to use

-u, –user=<name>         Specify the username for authentication

-p, –password=<name>     Specify the password for authentication

operations:

-S, –shutdown            Shutdown the server

-e, –exit=<code>         Force the VM to exit with a status code

-H, –halt=<code>         Force the VM to halt with a status code

To shutdown a remote JBoss AS instance, use: ./shutdown.sh -s jnp://remoteHostOrIP:1099 -S Remote instance’s IP address and port are specified by its Naming service configured in ${jboss.server.config.url}/jboss-service.xml

5.4. Starting From a Remote Server

  • JBoss can load itself from a network server using run script’s -netboot=<url> option
  • Result: home.dir=<url>
    • Everything resolved relative to home URL
  • NetBoot requires jar on the client side, and a web server with support for PROPFIND WebDAV command
    • JBoss AS itself can serve this role
    • Use an Ant script to set this up
  • To boot JBoss AS from a remote server, you would execute something like this: ./run.sh –netboot=http://192.168.0.1:8080/jboss/

6. Deployments on JBoss

6.1. Java EE Deployment Lifecycle

Development and Deployment Lifecycle:

  1. Design static content (HTML, CSS, GIF, JPG, etc.)
  2. Develop dynamic content (Servlets, JSPs, and other Java components like EJBs)
  3. Write deployment descriptors (e.g. xml, application.xml, ejb-jar.xml, etc.) for components
  4. Assemble components into deployable packages (e.g. WAR, JAR, EAR, etc.)
  5. Provide all resources that the components require (e.g DBCP, Mail sessions, message queues, etc.)
  6. Deploy packages (e.g. WAR, JAR, EAR, etc.) on the Java EE application server
  7. Manage Java EE applications on the server

6.2. Deployment Descriptors

  • Give the containers instructions on how to use and manage deployed Java EE components
    • Security
    • Transactions
    • Persistence
  • Declarative customization (XML-based)
  • Enables portability of Java EE components
  Note
J2EE 1.3 and JBoss pre 5.x deployment descriptors are defined by XML DTD documents. These can be found in $JBOSS_HOME/docs/dtd/ directory. As of J2EE 1.4 and JBoss 5.x, deployment descriptors are defined by XML Schema (XSD) documents. These can be found in $JBOSS_HOME/docs/schema/ directory.

6.3. Deployment on JBoss AS

  • Deployment is a two-step process
    • First we notify JBoss that of the application we want to deploy by copying it to ${jboss.server.home.url}/deploy/ or any of its subdirectories
    • Then, JBoss performs the necessary steps to make that application ready for our use
  • Undeployment is also a two-step process
    • First we notify JBoss that of the application we want to undeploy by removing it from ${jboss.server.home.url}/deploy/ directory
    • Then, JBoss performs the necessary steps to stop the application and unload its resources
  • Alternatively, applications can be deployed/undeployed/and re-deployed via system:service=MainDeployer JMX MBean (more on this later).
    • This mechanism also support remote management of JBoss deployments
  • Supports deployment dependencies
  • Hot-deployment vs. cold-deployment
  • Archived components are uncompressed (a.k.a. exploded) under ${jboss.server.temp.dir}/deploy/
    • JBoss deletes (or at least it is supposed to delete) ${jboss.server.temp.dir}/deploy/ deployments upon restart
    • It is recommended to deploy applications already uncompressed (exploded) for to avoid the overhead of uncompression, and provide easy access to deployment descriptors and JSP files
  • The deployed components are automatically redeployed if their deployment descriptors are modified while JBoss AS is running
  • JBoss supports nested deployments (e.g. WAR under EAR) regardless of whether they are compressed into archives or deployed uncompressed
  • With clustering enabled, JBoss AS also supports farmed deployment – that is, pushing applications across the entire cluster when deployed on any single member of that cluster
  • JBoss supports JSR-88 (Java EE application deployment spec) but
    • There are no tools that make this kind of deployment easy – requires writing code
    • The resulting deployments go into the tmp/ directory – making redeployments harder

6.4. Deployers on JBoss AS

  • JBoss has an extensible deployment architecture that allows components to be easily integrated into the core JBoss Microcontainer
  • Deployers for: WARs, EARs, EJBs, JAR libraries, RARs, SARs, XML-based services, HARs, Aspects, Client, BeanShell scripts
    • The deployers are deployed themselves as *.deployer or *-deployer-beans.xml under ${jboss.server.home.url}/deployers/ directory

6.5. Hot vs. Cold Deployment

  • Hot deployment is cool, but there is a risk of:
    • Class-Loader exceptions (more on this later)
    • Unrecognized configuration settings
    • Lost session/application scoped data
  • Cold deployment is slow but stable
    • Stop JBoss AS
    • Optionally delete data/, log/, tmp/, work/
    • Redeploy your application(s)
    • Start JBoss AS

Hot deployment is generally considered safe for:

  • Java Server Pages (.jsp) files. They get recompiled automatically by the servlet engine following a change.
  • Class files that do not change their public interfaces, especially when there is no RMI involved. This requires full redeployment, so it is still somewhat risky.

7. Web Application Administration

7.1. Tomcat Web Container

  • Apache Tomcat (6.x) is a free and open source Servlet (2.5) and JSP (2.1) Container
  • Embedded in JBoss AS as deploy/jbossweb.sar
  • JBoss AS configuration for Tomcat integration in each application are located in META-INF/jboss-web.xml
    • Default JAAS Security Domain
    • Class Loading and Sharing
    • Session Management and Caching
    • Clustering and Load Balancing (in all config)

<jboss-web>

<security-domain>java:/jaas/simple-security-domain</security-domain>

</jboss-web>

7.2. Tomcat’s server.xml

  • Tomcat’s own configuration file: deploy/jbossweb.sar/server.xml
  • Configures
    • Connectors (HTTP, HTTPS, AJP)
    • Security Realms (Inherits from JBoss)
    • Logging (Tomcat Service)
    • Valves (Request/Response interceptors)
    • Virtual Hosts (Name-based)
    • Web application contexts (Per-app configuration)

<Server>

<!– Optional listener which ensures correct init and shutdown of APR,

and provides information if it is not installed –>

<Listener className=”org.apache.catalina.core.AprLifecycleListener” SSLEngine=”on” />

<!–Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html –>

<Listener className=”org.apache.catalina.core.JasperListener” />

<Service name=”jboss.web”>

<!– A HTTP/1.1 Connector on port 8080 –>

<Connector protocol=”HTTP/1.1″ port=”8080″ address=”${jboss.bind.address}”

connectionTimeout=”20000″ redirectPort=”8443″ />

<!– A AJP 1.3 Connector on port 8009 –>

<Connector protocol=”AJP/1.3″ port=”8009″ address=”${jboss.bind.address}”

redirectPort=”8443″ />

<Engine name=”jboss.web” defaultHost=”localhost”>

<Realm className=”org.jboss.web.tomcat.security.JBossWebRealm”

certificatePrincipal=”org.jboss.security.auth.certs.SubjectDNMapping”

allRolesMode=”authOnly”

/>

<Host name=”localhost”>

<Valve className=”org.jboss.web.tomcat.service.jca.CachedConnectionValve”

cachedConnectionManagerObjectName=”jboss.jca:service=CachedConnectionManager”

transactionManagerObjectName=”jboss:service=TransactionManager” />

</Host>

</Engine>

</Service>

</Server>

7.3. Tomcat’s web.xml

  • Default web descriptor for all web apps deployers/jbossweb.deployer/web.xml
  • Configures
  • Common Filters
  • Servlets for handling static content (DefaultServlet), JSPs, SSI, CGI scripts, invokers, etc.
  • Default session timeout
  • MIME Type mappings
  • Welcome file list: index.html, index.jsp, etc.

7.4. Defining and Mapping Servlets

  • In WEB-INF/web.xml file:
    • Define a servlet with <servlet> where <servlet-name> points to a fully qualified <servlet-class>
      • Optionally initialize with <init-param>-s
      • Optionally <load-on-startup>
    • Map a defined servlet with <servlet-mapping> where <url-pattern> points to previously specified <servlet-name>
      • Map under multiple <url-pattern>-s if needed
      • <servlet>
      • <servlet-name>IPLoggerServlet</servlet-name>
      • <servlet-class>example.servlet.IPLoggerServlet</servlet-class>
      • <init-param>
      • <param-name>file</param-name>
      • <param-value>/WEB-INF/ip.log</param-value>
      • </init-param>
      • <load-on-startup>2</load-on-startup>
      • </servlet>
      • <servlet-mapping>
      • <servlet-name>IPLoggerServlet</servlet-name>
      • <url-pattern>/ip</url-pattern>
      • </servlet-mapping>
      • <servlet-mapping>
      • <servlet-name>IPLoggerServlet</servlet-name>
      • <url-pattern>/logmyip</url-pattern>

</servlet-mapping>

7.5. Defining and Mapping Filters

  • In WEB-INF/web.xml file:
    • Define a filter with <filter> where <filter-name> points to a fully qualified <filter-class>
      • Optionally initialize with <init-param>-s
    • Map a defined filter with <filter-mapping> where <url-pattern> points to previously specified <filter-name>
      • Map under multiple <url-pattern>-s if needed
      • Map with /* to apply to all requests
      • <!ELEMENT filter (icon?, filter-name, display-name?, description?, filter-class, init-param*)>
      • <filter>
      • <filter-name>Logger</filter-name>
      • <filter-class>example.servlet.AccessLogFilter</filter-class>
      • </filter>
      • <!ELEMENT filter-mapping (filter-name, (url-pattern | servlet-name))>
      • <filter-mapping>
      • <filter-name>Logger</filter-name>
      • <url-pattern>/*</url-pattern>

</filter-mapping>

7.6. Session Configuration

  • Configure <session-timeout> in the <session-config> element
  • The value (in minutes) indicates how long the servlet container will maintain an idle session (in memory or on disk) before timing out
  • Value ⇐ 0 indicates that sessions never expire – unless destroyed explicitly (through users logouts)
  • Significant impact on server memory usage and end users dissatisfaction with time outs
  • <session-config>
  • <session-timeout>30</session-timeout>

</session-config>

7.7. Serving Static Content

  • Tomcat serves static content via its DefaultServlet (configured in Tomcat’s xml file)
    • Any file under an application’s structure (but outside WEB-INF and META-INF directories) is considered static content
  • Application deploy/ROOT.war/ is considered special – it has no context path
    • Serves all content not served by any other application
  • Returns a HTTP 404 response if the requested static content does not exist
  • war also provides support for http://localhost:8080/status servlet (see its WEB-INF/web.xml)

7.8. Virtual Hosting with Tomcat

  • Add hosts and aliases to xml:
  • <Host name=”myhost.com”>
  • <Alias>www.myhost.com</Alias>

</Host>

  • Register applications for virtual hosts in their WEB-INF/jboss-web.xml files:
  • <jboss-web>
  • <context-root>/myapp</context-root>
  • <virtual-host>myhost.com</virtual-host>

</jboss-web>

  • Applications default to host specified by <Engine>’s defaultHost attribute

server.xml

<Server>

<Service>

<Connector …/>

<Engine>

<Host name=”myhost.com”>

<Alias>www.myhost.com</Alias>

</Host>

<Host name=”anotherhost.com”/>

</Engine>

</Service>

</Server>

myapp.war/WEB-INF/jboss-web.xml: 

<jboss-web>

<context-root>/myapp</context-root>

<virtual-host>myhost.com</virtual-host>

</jboss-web>

ROOT-another.war/WEB-INF/jboss-web.xml: 

<jboss-web>

<context-root>/</context-root>

<virtual-host>anotherhost.com</virtual-host>

</jboss-web>

8. JNDI Administration

8.1. Java Naming and Directory Interface

  • Core infrastructure (glue) for locating objects or services within an application server
  • Also allows external clients to locate services
  • Important for clustering: hides actual location
  • Divided into API and SPI
    • Applications code against the API
    • Application servers provide the SPI
  • SPIs for accessing remote resources, such as LDAP, DNS, NIS, file systems, RMI registry

8.2. JNDI in Java EE

  • JNDI is to Java EE what DNS is to Internet apps
  • JNDI maps high-level names to resources like mail sessions, database connection pools, EJBs, and plain environmental properties
  • JNDI organizes its namespace using Environmental Naming Context (ENC) naming convention:
    • Starts with java:comp/env
    • Private to each application
    • Contexts are delimited with a forward-slash (/)

JNDI ENC naming convention:

  • java:comp/env/var – Environmental variables
  • java:comp/env/url – URLs
  • java:comp/env/mail – JavaMail sessions
  • java:comp/env/jms – JMS connection factories and destinations
  • java:comp/env/ejb – EJB home interfaces
  • java:comp/env/jdbc – JDBC DataSources

8.3. JNDI on JBoss

  • Supports both local (optimized) and remote (over RMI) access to named objects
  • Provides a JVM-private app-shared java: context in addition to app-private java:comp
  • Everything outside java: is public and externally visible
  • Exposes JNDI operations over JMX invoke operations – allows access over HTTP/S
  • Supports viewing JNDI Tree remotely
  • Supports clustering through HA-JNDI

Configured in ${jboss.server.config.url}/jboss-service.xml:

<mbean code=”org.jboss.naming.NamingService”

name=”jboss:service=Naming”

xmbean-dd=”resource:xmdesc/NamingService-xmbean.xml”>

<mbean code=”org.jboss.naming.JNDIView”

name=”jboss:service=JNDIView”

xmbean-dd=”resource:xmdesc/JNDIView-xmbean.xml”>

</mbean>

Client configuration ${jboss.server.config.url}/jndi.properties:

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory

java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Remote clients would need to add:

java.naming.provider.url=jnp://jbosshost.domain.com:1099

9. Enterprise Java Beans Administration

9.1. Introduction to EJB 3.0

  • Stands for Enterprise Java Bean
  • It’s a server-side component that encapsulates the business logic of an application
  • EJBs are often combined where they call each other to execute business logic on the Java EE server
    • EJBs clients can be :
      • Web-tier components (local or remote)
      • Remote clients (over RMI)
      • Web service clients (over HTTP/SOAP)

The idea of EJBs is to move the business logic out of the web-tier and into a separate layer that exclusively focuses on modeling the business domain and the related operations.

9.2. EJB 3.0 Components

  • Two main components in EJB:
    • Session Beans perform business logic, manages transactions and access control.
    • Message Driven Beans perform actions on event (receive a JMS message) associated to JMS Queues and JMS Topics.

9.3. EJB Container

EJBs run within a EJB Container, a run-time environment of a Java EE app server

The EJB Container provides system-level services, such as:

  • Transactions (including distributed transactions)
  • Security
  • Persistence (via JPA)

Just like the web-tier components run in the Servlet container, EJBs require the services of a EJB container – i.e. EJBs cannot run on their own.

9.4. Benefits of EJB Technology

  • Simplify the development of large and distributed enterprise applications:
    • Bean developers focus on business problems, and the container takes care of the rest, most notably transactions and security. Persistence is managed by JPA.
    • Paradigm for separating the business logic from its presentation, which simplifies the UI development
    • EJBs are portable, easily integrate with existing beans, and run on any Java EE AS

EJB technology is a good candidate for the following situations:

  • Applications with complex business logic that must be scalable. Transparent distribution of load across multiple server instances is at core of EJB
  • Applications that require [distributed] transactions to ensure data integrity. The EJB container provides the necessary mechanisms that manage the concurrent access to shared objects

9.5. Drawbacks of EJBs

  • Prior to EJB3
    • EJB applications were harder to test as they depend heavily on the container services
      • Automated unit testing was a challenge
    • EJB applications were harder to develop and deploy

9.6. Session Beans

  • Reusable components that contains business logic. Clients can interacts with Session Beans locally or remotely.
  • To access a session bean, the client invokes its public methods
  • Stateless Session Bean
    • Performs a task for a client
    • Is not attached to a client (no client state maintained)
    • Can implement a web service
  • Stateful Session Bean
    • Represents a single client inside the application
  • Stateless Session Beans
    • Maintain the client state only for the duration of the method invocation
    • When the method returns, the bean appears to terminate as well
    • Do not need to persist the state to the secondary storage
    • Are more scalable because they can be shared
    • Are more common in Java EE applications
    • Could represent actions such as: sending email, converting currency
  • Stateful Session Beans
    • Maintain the conversational state with the client, which survives across multiple method invocations
    • Release their state once the client removes the bean or terminates
    • Can temporarily persist their state to the secondary storage – for stability reasons
    • Could represent temporary entities such as shopping carts

9.8. Entity Beans

  • Represent a table in a relational database
  • Each instance of this entity corresponds to a row in that table
  • Each entity has a unique identifier – this allow clients to locate a particular instance of this entity
  • Entities can have relationship, for example, a Zoo instance will contain several Animal instances

9.9. Stateless Session Beans Life Cycle

  1. Instances created by the EJB container
  2. These instances are kept into a pool of ready instances
  3. A method call is made by a client
  4. The container assign a ready instance from the pool to the client for the duration of the call
  5. The SLSB instance is then returned to the pool.

9.10. Stateful Session Beans Life Cycle

  1. A client session is started
  2. Default constructor is invoked
  3. Ressources are injected (if any)
  4. @PostContruct annotated method is called
  5. Now the SFSB is in cache and ready to execute any business method invocation from the client

9.11. Configuring the EJB container

  • Previous versions of EJB (1.x – 2.x) can be configured in the <configuration-set>/conf/standardjboss.xml
  • For EJB 3.x, the configuration file is <configuration-set>/deploy/ejb3-interceptors-aop.xml
    • This file is divided into domains.
    • Each of these domains contains actions, called Interceptors.

Each call to a domain goes through a stack of Interceptors to the target method. After execution, the call unwinds through the stack in reverse order.

How to configure the Stateless Session Bean pool size? In the deploy/ejb3-interceptors-aop.xml :

<domain name=”Stateless Bean” extends=”Intercepted Bean” inheritBindings=”true”>

  …

  <annotation expr=”!class(@org.jboss.ejb3.annotation.pool)”>

    @org.jboss.ejb3.annotation.pool (value=”ThreadLocalPool”, maxSize=30, timeout=10000) <!–  –>

  </annotation>

  …

</domain>

  maxSize defines the upper limit of your Stateless Session Bean pool. Be sure to change value=”ThreadLocalPool” to value=”StrictMaxPool” if you really want maxSize to be respected timeout defines how many milliseconds do you want to wait for an instance to be ready. value defines the pooling mechanism. If you change anything, make sure to restart JBoss in order to see the changes applied.

With value=”StrictMaxPool”, when the maxSize is reached, the client wait for an EJB3 to be back in the pool to use it. If the timeout is reached before that, a java.rmi.ServerException is thrown.

Your pool configuration can be seen from the JMX console anytime. Select jboss.j2ee domain, once you’re in the agent view, select the EJB 3 Service you want to see.

   

9.12. Stateful Session Bean Configuration

Configuration will happen in the Stateful Bean domain in the ejb3-interceptors-aop.xml

How to configure the Stateful Session Bean cache?

  • The configuration is split in two parts
    • Non-clustered cache configuration
    • Clustered cache configuration

<domain name=”Stateful Bean” extends=”Base Stateful Bean” inheritBindings=”true”>

  <!– NON Clustered cache configuration –>

  …

  <annotation expr=”class(*) AND !class(@org.jboss.ejb3.annotation.CacheConfig) AND !class(@org.jboss.ejb3.annotation.Clustered)”>

    @org.jboss.ejb3.annotation.CacheConfig (maxSize=100000, idleTimeoutSeconds=300, removalTimeoutSeconds=0)

  </annotation>

  …

  <!– Clustered cache configuration –>

  …

  <annotation expr=”class(*) AND !class(@org.jboss.ejb3.annotation.CacheConfig) AND class(@org.jboss.ejb3.annotation.Clustered)”>

    @org.jboss.ejb3.annotation.CacheConfig (name=”sfsb-cache”, maxSize=100000, idleTimeoutSeconds=300, removalTimeoutSeconds=0)

  </annotation>

  …

</domain>

10. JMS Administration

10.1. JMS Overview

  • Framework for reliable both synchronous and asynchronous communication between distributed components
  • Guaranteed push-based delivery
  • Peer to peer
    • One to One, One to Many, Many to Many
  • Loosely coupled (standard message formats)
  • JMS Implementation provides necessary services to its clients
  • JMS is unlike RMI, which is tightly coupled. In JMS, The sender and the receiver need to know only which message format and which destination to use.
  • JMS is unlike email, which is people oriented. JMS is meant to serve distributed software applications and components, although it is also used for local (in-JVM) messaging.

10.2. JMS in Java EE

  • Allows loosely coupled, reliable, asynchronous interactions among Java EE components and legacy systems capable of messaging
  • Is reliable, it ensure that a message is delivered once and only once.
  • Application clients, EJBs, and web components can send and receive JMS messages
  • Message-driven beans enable the asynchronous (possibly concurrent) consumption of messages, making it easy to plug in new business event handlers into an existing deployment
  • Message send and receive operations can participate in distributed transactions, which allow JMS operations and database accesses to take place within a single transaction
  • JMS can be used outside the context of a full-blown app server

10.3. When is JMS Used

  • When no dependency between components is important
    • Compile-time dependency (loose coupling)
    • Run-time dependency (components run independently)
  • When we need asynchronous yet reliable communication
  • Consider the following usage scenario:
    • Components of an enterprise application for an automobile manufacturer can use the JMS API in situations like these:
      • The inventory component can send a message to the factory component when the inventory level for a product goes below a certain level so that the factory can make more cars
      • The factory component can send a message to the parts components so that the factory can assemble the parts it needs
      • The parts components in turn can send messages to their own inventory and order components to update their inventories and to order new parts from suppliers
      • Both the factory and the parts components can send messages to the accounting component to update their budget numbers
      • The business can publish updated catalog items to its sales force

10.4. JMS Architecture

  • JMS clients are the programs (possibly external) or components, written in the Java programming language, that produce and consume messages. Any Java EE application component can act as a JMS client.
  • A JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features. JBoss Messaging is such provider.
  • Messages are the objects that communicate information between JMS clients.
  • Administered objects are preconfigured JMS objects created by an administrator for the use of clients:
    • Connection Factories
    • Destinations

10.5. JMS Messaging Domains

Figure 4. Point to Point

Figure 5. Publish and Subscribe

Point to Point

  • A sender (producer) sends a message addressed to a specific queue
  • A receiver (consumer) consumes the message from the queue established to hold its messages
  • Queues retain all messages sent to them until the messages are consumed or until the messages expire
  • Each message has only one consumer
  • A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message
  • The receiver acknowledges the successful processing of a message

Publish and Subscribe

  • Publisher clients publish messages to one or more message topics
  • Subscriber clients subscribe to one or more message topics and receive messages when they are sent to them
  • The topics hold the messages as long as it takes to deliver them to all currently subscribed clients
  • Each message can have multiple consumers
  • Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages (unless it holds a durable subscription)

10.6. JMS Message Consumption

  • Synchronous: A subscriber or a receiver explicitly fetches the message from the destination by calling the blocking receive method (with support for timeouts)
  • Asynchronous: A client can register a message listener with a consumer. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message

We will use an asynchronous JMS client in the JMS lab.

10.7. JMS on JBoss Configuration

  • Configuration files can be found in deploy/messaging directory of your JBoss server.
    • connection-factories-service.xml: Define connection factories
    • destinations-service.xml: Define destinations (Topic,Queue)
    • hsqldb-persistence-service.xml: Define persistence for messages (The messaging service stores all messages before delivering them)
    • jms-ds.xml: JMSProviderLoader and JmsXA inflow resource adaptor connection factory binding configuration
    • legacy-service.xml: JMSProviderLoader and JmsXA inflow resource adaptor connection factory binding configuration
    • messaging-jboss-beans.xml: Configures JMS security and management beans
    • messaging-service.xml: Contains the server’s configuration and core messaging services
    • remoting-bisocket-service.xml: Contains JMS remoting configuration

10.8. Configure JMS connection factories

  • New JMS connections are created by ConnectionFactory.
  • JBoss AS 5 ships already configured, non-clusterable and clusterable connection factories
    • Non-clustered are bound to the following JNDI contexts: /ConnectionFactory, /XAConnectionFactory, java:/ConnectionFactory, java:/XAConnectionFactory
    • Clustered are bound to the following JNDI contexts: /ClusteredConnectionFactory, /ClusteredXAConnectionFactory, java:/ClusteredConnectionFactory, java:/ClusteredXAConnectionFactory
  • Configuration located in deploy/messaging/connection-factories-service.xml
  Note
Factories that are bound to the java: namespace are reserved for local JMS Client (running on the same JVM of the server)

You can find an example on how to create a ConnectionFactory inside deploy/messaging/connection-factories-service.xml

10.9. Configure JMS destinations

  • The deploy/messaging/destinations-service.xml contains preconfigured destinations deployed during server startup
  • To create your own queue called exampleQueue, you could either add it to deploy/messaging/destinations-service.xml or deploy your own exampleQueue-service.xml:
  • <server>
  • <mbean code=”org.jboss.jms.server.destination.QueueService”
  • name=”jboss.messaging.destination:service=Queue,name=exampleQueue”
  • xmbean-dd=”xmdesc/Queue-xmbean.xml”>
  • <depends optional-attribute-name=”ServerPeer”>jboss.messaging:service=ServerPeer</depends>
  • </mbean>

</server>

  • Deploying it binds this queue to JNDI as /queue/exampleQueue:

13:27:57,421 INFO  [QueueService] Queue[/queue/exampleQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000

  • Similarly, to create your own topic called exampleTopic, you could either add it to deploy/messaging/destinations-service.xml or create your own exampleTopic-service.xml:
  • <server>
  • <mbean code=”org.jboss.jms.server.destination.TopicService”
  • name=”jboss.messaging.destination:service=Topic,name=exampleTopic”
  • xmbean-dd=”xmdesc/Topic-xmbean.xml”>
  • <depends optional-attribute-name=”ServerPeer”>jboss.messaging:service=ServerPeer</depends>
  • <depends>jboss.messaging:service=PostOffice</depends>
  • </mbean>

</server>

  • Deploying it binds this topic to JNDI as /topic/exampleTopic:

13:27:57,890 INFO  [TopicService] Topic[/topic/exampleTopic] started, fullSize=200000, pageSize=2000, downCacheSize=2000

  • You can inspect destination attributes via the JMX console in the messaging.destination domain.
  • Here is some information about attribute you can configure for a destination, for more info on the additional attributes, see http://jboss.org/jbossmessaging/docs.html
    • name: name of the queue
    • JNDIName: JNDI name where the queue is bound
    • DLQ: Dead Letter Queue to use. It’s a special destination where the messages are sent when the server has attempted to deliver them unsuccessfully more than a certain number of times
    • ExpiryQueue: is a special destinations where messages are sent when they have expired
    • RedeliveryDelay: redelivery delay to be used for this queue
    • MaxDeliveryAttempts: number of times a delivery attempt will happen before the message goes to the DLQ
    • SecurityConfig: Allows you to determine which roles can read, write and create on the destination
    • FullSize: maximum number of messages held by the queue or the topic in memory at any given time

11. JMX Administration

11.1. What is JMX?

  • Management and monitoring standard
  • Both local and remote management
  • Change settings at runtime
  • Event notification / timer
  • Dynamic class loading from XML files
  • Portable across application servers
  • Integrate with 3rd-party components
  • You can use JMX to load, initialize, change, and monitor your application and its distributed components.
  • JMX is a standard for managing and monitoring all varieties of software and hardware components from Java. In addition, JMX aims to provide integration with the large number of existing management standards, such as SNMP and WBEM.

11.2. Why JMX?

  • Custom configuration management is hard to implement and typically not reusable
  • App-server-specific solutions are proprietary and tie you to the vendor
  • JMX is reusable and open framework for both local and remote configuration management that supports runtime querying/updates, monitoring, notifications, timers, class loading, etc.

11.3. JMX Architecture

Instrumentation Layer

  • The instrumentation layer exposes the application components as one or more managed beans (MBeans)
  • Each MBean provides access to its state using public methods
  • An MBean can be any Java object that supports the interfaces and semantics of the JMX specification

Agent Layer

  • The JMX agent is the hub of the JMX framework
    • It provides remote management and application access to all of its registered MBeans
  • The agent also supports additional services, such as monitoring and dynamic loading
    • These services are also implemented and registered as MBeans so that they benefit from the framework as well
  • The core agent component is called MBean server and is defined by the interface management.MBeanServer

Distributed Services Layer

  • The distributed management services layer provides the interfaces and components that remote tools use to interface with agents
  • The current specification leaves the definition of these interfaces and other functionality to the future versions of JMX, but most application servers provide JMX connectors and adaptors for web (HTML), RMI, and SNMP access

11.4. JMX on JBoss AS

  • Next to the JBoss Microcontainer, JMX is at the very core of JBoss AS.
  • Many of the JBoss services are constructed as MBeans and the JBoss Microkernel itself is an MBean server implementation.
  • The minimal configuration set only starts:
    • JBoss Microcontainer
    • JMX Kernel
    • JNDI MBean
    • Logging Mbean
  • JBoss adaptors include HTML/HTTP and RMI

11.5. JMX Console

JMX Console is a deployed web application (Distributed Services Layer) that acts as a web UI into the JBoss Microkernel (Agent Layer) and all of the deployed services (Instrumentation Layer MBeans).

The following list outlines some of the JMX Console’s capabilities:

  • Reconfigure logging: system:service=Logging,type=Log4jService
  • Get JBoss Version, Run GC, Shutdown: system: type=Server
  • Get JBoss Directory Paths: system:type=ServerConfig
  • Get JVM/Memory/Thread Info: system:type=ServerInfo
  • Query an individual servlet: web:J2EEApplication=none,J2EEServer=none,WebModule =//localhost/fortune,j2eeType=Servlet,name=fortune
  • View JNDI Tree: jboss:Service=JNDIView
  • Manage a DB connection pool: jca:name=DefaultDS,service=ManagedConnectionPool
  • Start/Stop applications: web.deployment:id=2147076203,war=fortune.war
  • Change virtual host settings: web:host=localhost,type=Host
  • View and change HTTP connector settings: web:address=/0.0.0.0,port=8080,type=Connector
  • View/Flush HTTP sessions: web:host=localhost,path=/fortune,type=Manager
  • Manage deployments: system:service=MainDeployer

11.6. Web Console

  • Like JMX Console, Web Console provides the same, but richer, view into the JBoss JMX server/services
  • Navigation is done through a Java Applet
  • Supports creation of alerts and real-time monitors (right-click)
  Note
To use Web Console, your browser have to support applets.

11.7. Twiddle Tool

  • Command Line access to a [remote] JMX server (similar to web-based JMX Console)
  • Its capabilities include:
    • Getting/setting attributes on MBeans
    • Invoking operations on MBeans
    • Looking up MBeans
    • Getting server information
  • Called twiddle (for twiddling bits)
    • bin/twiddle.sh (UNIX)
    • bin/twiddle.bat (Windows)
  • Great for automation

List all deployed web applications:

./twiddle.sh query “jboss.web.deployment:*”

jboss.web.deployment:war=web-console.war,id=115013145

jboss.web.deployment:war=jbossmq-httpil.war,id=753610482

jboss.web.deployment:war=ROOT.war,id=-1586513555

jboss.web.deployment:war=jboss-ws4ee.war,id=1143514564

jboss.web.deployment:war=jmx-console.war,id=-1884883379

jboss.web.deployment:war=fortune.war,id=2147076203

jboss.web.deployment:war=invoker.war,id=-1536256770

Control the life-cycle an application:

./twiddle.sh invoke jboss.web.deployment:war=fortune.war,id=2147076203 stop

‘null’

./twiddle.sh invoke jboss.web.deployment:war=fortune.war,id=2147076203 start

‘null’

Get a state on an application:

./twiddle.sh get jboss.web.deployment:war=fortune.war,id=2147076203 StateString

StateString=Started

Get the current memory usage of our JBoss AS instance:

./twiddle.sh get jboss.system:type=ServerInfo TotalMemory

TotalMemory=56184832

Ask JBoss AS to run the garbage collector:

./twiddle.sh invoke jboss.system:type=Server runGarbageCollector

‘null’

Shutdown JBoss AS instance:

./twiddle.sh invoke jboss.system:type=Server shutdown

11.8. JBoss AS Administration Console

  • New since JBoss AS release 5.1.0
  • Also known as Embedded Jopr project
  • Available at the following URL ⇒ http://localhost:8080/admin-console
  • Default administrator credentials are admin/admin
  • Essentially, a simplified version of the other console applications
    • Less clutter → easier to work with

The user interface:

  • Is divided in two frames
    • The left frame list the ressources available on the server
    • The right frame is the Control Panel where you can manage the ressource selected

The Control Panel – 4 main tabs:

  • Summary: Contains the general properties and the most relevant metrics
  • Configuration: To edit or create new ressources (example: you can add a new datasource and it will generate the xxx-ds.xml for you)
  • Metrics: List all the metrics for a ressource
  • Control: When enabled, you can perform special actions related to a ressource

The possiblities in the Admin Console are the following:

  • Deploy/Undeploy applications
  • Update applications
  • Start/Stop/Restart applications
  • Add/Delete ressources
  • Manage ressources
  • See metrics

12 .Database Integration on JBoss

Application components deployed on JBoss that need access to a relational database can connect to it

  • Directly – by managing their own connections
    • Complicated deployments – requires separate configuration for each web app
    • Slow if connections are not pooled, which is not trivial to implement (though libraries exist)
    • If a connection pool is used, it cannot be shared with other applications further complicating deployments
  • Via a shared database connection pool managed by JBoss
    • Simplifies configuration and maintenance (single file to edit in a “standard” format)
    • Faster because the connections are pooled (production-tested)
    • Can be shared among applications so the connections can be better utilized
    • Applications are portable – as they don’t depend on some internal configuration of the external environment
    • Recommended!

12.1. Steps Involved

  • Define a resource references in your application
    • Require connectivity to RDBMS
  • Provide RDBMS resources (connection pools) in the server
    • Install JDBC drivers
    • Define a RDBMS DBCP
    • Map JBoss-managed RDBMS DBCP to the application’s resource reference

12.2. Resource Requirement

For example, in a web application we would communicate our need for a container-managed RDBMS in WEB-INF/web.xml file:

<web-app …>  …

<resource-ref>

    <description>DB Connection</description>

        <res-ref-name>jdbc/NorthwindDB</res-ref-name>

        <res-type>javax.sql.DataSource</res-type>

        <res-auth>Container</res-auth>

  </resource-ref>

  …</web-app>

12.3. Install JDBC Drivers

  • JDBC Driver is what enables Java applications to talk to specific RDBMS, such as MySQL, DB2, Oracle, etc.
  • Download the JDBC Driver from the database vendor (for MySQL go to http://www.mysql.com/products/connector)
  • Copy the driver JAR into directory ${jboss.server.lib.url} or ${jboss.common.lib.url}
  • Restart JBoss

12.4. Define a RDBMS DBCP Resource

  • Create a datasource (*-ds.xml) file – e.g. deploy/northwind-ds.xml:
  • <datasources>
  • <local-tx-datasource>
  • <jndi-name>NorthwindDB</jndi-name>
  • <connection-url>jdbc:mysql://localhost:3306/Northwind?autoReconnect=true</connection-url>
  • <driver-class>com.mysql.jdbc.Driver</driver-class>
  • <user-name>northwind</user-name>
  • <password>secret</password>
  • <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
  • <new-connection-sql>SELECT 1</new-connection-sql>
  • <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
  • </local-tx-datasource>

</datasources>

  • Start with ${jboss.home.dir}/docs/examples/jca/mysql-ds.xml as the template.
  • Some of the other common elements:
    • min-pool-size – the minimum number of pooled database connections. Initialized when the pool is first accessed. Defaults to 0.
    • max-pool-size – the maximum number of pooled database connections. Once this limit is reached, clients block. Defaults to 20.
    • blocking-timeout-millis – the maximum blocking time (in ms) while waiting on an available connection before timing out by throwing an exception. Defaults to 5000 (or 5 seconds).
    • track-statements – if true, unclosed statements are reported on check-in (via a warning message). Defaults to false.
    • idle-timeout-minutes – the maximum time (in minutes) before idle connections are closed.
  Note
In JBoss AS, resources like this DataSource are relative to java:/ JNDI context (remember, this is context is accessible to all applications running in the same JVM). So to access this resource directly, we could lookup java:/NorthwindDB in JNDI.

12.5. Map our Resource

  • Map the application’s resource-ref to the real resource provided by JBoss AS
  • In case of a web application, we would create WEB-INF/jboss-web.xml:
  • <jboss-web>
  • <resource-ref>
  • <res-ref-name>jdbc/NorthwindDB</res-ref-name>
  • <res-type>javax.sql.DataSource</res-type>
  • <jndi-name>java:/NorthwindDB</jndi-name>
  • </resource-ref>

</jboss-web>

  • This effectively maps java:comp/env/jdbc/NorthwindDB to java:/NorthwindDB

12.6. Using our DataSource (RDBMS DBCP)

Once mapped, the applications can access this resource to get a database connection:

Context ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup(“java:comp/env/jdbc/NorthwindDB”);

Connection conn = ds.getConnection();

try {

  // use connection to create statements, etc.

} finally {

  conn.close();

}

12.7. Hypersonic Database

  • JBoss embedded Java-based RDBMS
  • deploy/hsqldb-ds.xml configures:
    • Embedded database (known as DefaultDS)
    • Connection factories
  • Used by JMS MQ for state management and persistence
  • Can be used for CMP
  • Data can be kept in memory or persisted
  • Can allow access to remote clients over TCP
  • This service is for development/testing use only. It is not production-quality.
  • To enable remote access, edit deploy/hsqldb-ds.xml:
    • Enable remote Hypersonic service:
    • <mbean code=”org.jboss.jdbc.HypersonicDatabase” name=”jboss:service=Hypersonic”>
    • <attribute name=”Port”>1701</attribute>
    • <attribute name=”Silent”>true</attribute>
    • <attribute name=”Database”>default</attribute>
    • <attribute name=”Trace”>false</attribute>
    • <attribute name=”No_system_exit”>true</attribute>

</mbean>

  • Change connection URL to:

<connection-url>jdbc:hsqldb:hsql://localhost:1701</connection-url>

  • The data will be persisted to: ${jboss.server.data.dir}/hypersonic/default

12.8. Detecting Connection Leaks

  • JBoss has a CachedConnectionManager service that can be used to detect connection leaks (within the scope of a request)
  • Configured in ${jboss.server.url}/deploy/jbossjca-service.xml
  • Triggered by Tomcat’s xml→<Host>→CachedConnectionValve
    • Enabled by default – slight overhead
    • Should be used during testing
    • Can be turned off in production if the code is stable
    • If the CachedConnectionValve is enabled in Tomcat’s xml file, then Tomcat must wait for the CachedConnectionManager service on startup. This is accomplished by adding the following line to Tomcat’s META-INF/jboss-service.xml file (near the end):

<depends>jboss.jca:service=CachedConnectionManager</depends>

  • Connection pools could be monitored (through JMX) by looking at jca:name=MyDS,service=ManagedConnectionPool→InUseConnectionCount attribute.
  • The example web application war can be made to leak resources (on /ListCustomers) by
    • appending requesting /ListCustomers?leak=true, and/or by
    • adding a custom system property: -Dleak.jdbc.resources=true to JAVA_OPTS in conf or run.bat (on Windows)

13 .Logging on JBoss

  • Log4j and logging services
  • Configuring logging

13.1 Configure logging service

  • Data logging is the process of recording events, with an automated computer program
  • JBoss AS5 uses log4j, an open source logging framework
    • Log4j is a tool to help the programmer output log statements to a variety of output targets.
  • Loggers may be assigned levels. The set of possible levels, that is:
  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL

13.2 Features of log4j

  • log4j supports multiple output appenders per logger.
  • The format of the log output can be easily changed by extending the Layout class.
  • The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
  • log4j is optimized for speed.
  • log4j is designed to handle Java Exceptions from the start.

TRACE<DEBUG

 

13.3 Log4J Pattern Layout

The PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

For example, the PatternLayout with the conversion pattern

“%r [%t] %-5p %c – %m%n”       will output something akin to:

176 [main] INFO org.foo.Bar – Located nearest gas station.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the ‘-‘ is the message of the statement.

 

13.4 JBOSS – Logging service

 

  • The log4j configuration file is located at server/xxx/conf/jboss-log4j.xml
  • By default, JBoss produces output to both the console and a log file (log/server.log).
  • By default, The logging threshold for the console is INFO, For server.log no        threshold
  • By default, The server.log file is created new each time the server is launched, and grows until the server is stopped or until midnight

Listing shows how you can change the Appender for the server.log file to create, at

most, 20 log files of 10 MB in size each.

13.5 JBOSS – Application specific log

 

As another example, let’s say you wanted to set the output from the container-managed persistence engine to DEBUG level and to redirect it to a separate file, cmp.log, in order to analyze the generated SQL commands. You would add the following code to the conf/jboss-log4j.xml file:

This creates a new file appender and specifies that it should be used by the logger (or category) for the package org.jboss.ejb.plugins.cmp.

The file appender is set up to produce a new log file every day rather than producing a new

one every time you restart the server or writing to a single file indefinitely. The current log file is

cmp.log. Older files have the date they were written added to their filenames.

13.6 Changing logging levels using JMX- Console

 

This example shows how to use the JMX Console to set the level of logging for Hibernate to INFO.

14 .Security on JBoss

14.1. Securing Applications

  • Filtering clients by source IP addresses
  • Requiring authentication and authorization
  • Data transport integrity and confidentiality (SSL)

We will explore each one of these in turn

14.2. Filtering Clients by Source

  • Limit access to web applications by client IP or hostname
  • Configured through Tomcat Valves
    • Different levels: <Engine> (global), <Host> (per virtual host), <Context> (per web application)

<Valve className=”org.apache.catalina.valves.RemoteAddrValve” allow=”192.168.*,127.*” />

<Valve className=”org.apache.catalina.valves.RemoteHostValve” deny=”spamhost.com” />

  • Configured through a Servlet Filter
    • Simple implementation is provided by JBoss but servlet filters are Java EE AS-independent
  • To limit client access through Tomcat, add a desired <Valve> in <Engine> or <Host> elements within ${jboss.server.home.url}/deploy/jbossweb.sar/server.xml file
  • Limiting per web application can be still done through Tomcat by creating a <Context> file ${jboss.server.home.url}/deploy/<app>.war/WEB-INF/context.xml:
  • <Context>
  • <Valve className=”org.apache.catalina.valves.RemoteAddrValve” allow=”192.168.*.*” />

</Context>

  • To limit client access in a application-server-neutral way, configure a servlet filter in WEB-INF/web.xml file as follows:
  • <web-app …>
  • <filter>
  • <filter-name>RemoteHostFilter</filter-name>
  • <filter-class>org.jboss.remotehostfilter.RemoteHostFilter</filter-class>
  • <init-param>
  • <param-name>allow</param-name>
  • <param-value>192.168.*,127.*</param-value>
  • </init-param>
  • </filter>
  • <filter-mapping>
  • <filter-name>RemoteHostFilter</filter-name>
  • <url-pattern>/*</url-pattern>
  • </filter-mapping>

</web-app>

A simple implementation of this filter can be found at http://community.jboss.org/wiki/LimitAccessToCertainClients

14.3. Authentication & Authorization

Security is a fundamental part of any enterprise application. You need to be able to restrict who is allowed to access your applications and control what operations application users may perform.

  • JAAS – Java Authentication and Authorization Service (pure Java)
  • Pluggable Authentication Module framework: JNDI, UNIX, Windows, Kerberos, Keystore
  • Support for single sing-on
  • Role-based access control
  • Separates business logic from A&A
  • Declarative (XML-based)
    • Described in deployment descriptors instead of being hard-coded
    • Isolate security from business-level code
  • For example, consider a bank account application. The security requirements, roles, and permissions will vary depending on how is the bank account accessed:
    • via the internet (username + password), via an ATM (card + pin), or at a branch (Photo ID + signature).
    • We benefit by separating the business logic of how bank accounts behave from how bank accounts are accessed.
  • Securing a Java EE application is based on the specification of the application security requirements via the standard Java EE deployment descriptors.
    • EJBs and web components in an enterprise application by using the ejb-jar.xml and xml deployment descriptors.

14.4. Requiring A&A

  • Adding security-constraint in web.xml:
  • <web-app …>
  • <security-constraint>
  • <web-resource-collection>
  • <web-resource-name>All Resources</web-resource-name>
  • <description>Protect all content</description>
  • <url-pattern>/*</url-pattern>
  • </web-resource-collection>
  • <auth-constraint>
  • <role-name>MyRole</role-name>
  • </auth-constraint>
  • </security-constraint>

</web-app>

  • Element <security-constraint> declares the web resources to be protected and the role required to access those resources.
  • Element <web-resource-name> is required, and it simply assigns a name to the declared <web-resource-collection>.
  • Element <description> is optional, and it provides textual description of the declared <web-resource-collection>.
  • Element <url-pattern> is optional (although, without it the <web-resource-collection> is ignored), and it declares to which URL patterns this security constraint applies. URL patterns can be catch-all (“/*”) or they can be repeated to list specific resources. For example:
  • <url-pattern>/MySecureHandler</url-pattern>
  • <url-pattern>/MySecureArea/*</url-pattern>

<url-pattern>*.jsp</url-pattern>

  • The preceding slash (/) character makes the URLs absolute within the web application only.
  • In addition to URL patterns, it is also possible to limit the security constraint to HTTP methods using the <http-method> element as follows:
  • <web-resource-collection>
  • <http-method>POST</http-method>
  • <http-method>GET</http-method>

</web-resource-collection>

  • If the <http-method> element is omitted, the default behavior is to apply the security constraint to all HTTP methods.
  • The <auth-constraint> element indicates the user roles that should be permitted access to this resource collection. The <role-name> used here must either correspond to the <role-name> of one of the <security-role> elements defined for this web application (more on this soon), or be the specially reserved role-name “*” that is a compact syntax for indicating all roles in the web application. If no roles are defined, no user is allowed access to the portion of the web application described by the containing security-constraint. JBoss AS matches role names case sensitively when determining access.
  • Adding login configuration:
  • <web-app …>
  • <security-constraint>
  • </security-constraint>
  • <login-config>
  • <auth-method>BASIC</auth-method>
  • <realm-name>My Secure Application</realm-name>
  • </login-config>

</web-app>

Element <login-config> configures the login method for the secured resource.

In this case we just use HTTP BASIC authentication, but other options for JBoss are: DIGEST, FORM, and CLIENT-CERT. We will cover some of these later.

  • Declaring security roles:
  • <web-app …>
  • <security-constraint>
  • <auth-constraint>
  • <role-name>MyRole</role-name>
  • </auth-constraint>
  • </security-constraint>
  • <login-config>
  • </login-config>
  • <security-role>
  • <description>All members of MyRole</description>
  • <role-name>MyRole</role-name>
  • </security-role>

</web-app>

  • If multiple roles are desired, declare them as follows:
  • <web-app …>
  • <security-constraint>
  • <web-resource-collection> … </web-resource-collection>
  • <auth-constraint>
  • <role-name>Manager</role-name>
  • </auth-constraint>
  • <auth-constraint>
  • <role-name>Administrator</role-name>
  • </auth-constraint>
  • </security-constraint>
  • <login-config> … </login-config>
  • <security-role>
  • <role-name>Manager</role-name>
  • </security-role>
  • <security-role>
  • <role-name>Administrator</role-name>
  • </security-role>

</web-app>

14.5. Plain-Text Login Module

  • Already enabled by default
  • WEB-INF/classes/users.properties:
  • john=secret
  • bob=abc123

mike=passwd

  • WEB-INF/classes/roles.properties:
  • john=MyRole
  • bob=MyRole,Manager

mike=Manager,Administrator

  • Provided by jboss.security.auth.spi.UsersRolesLoginModule configured in file ${jboss.server.config.url}/login-config.xml:
  • <policy>
  • <application-policy name=”other”>
  • <authentication>
  • <login-module code=”org.jboss.security.auth.spi.UsersRolesLoginModule” flag=”required” />
  • </authentication>
  • </application-policy>

</policy>

  Note
The properties files users.properties and roles.properties are loaded during initialization of the context class loader. This means that these files can be placed into any Java EE deployment archive (e.g. WAR), the JBoss configuration directory, or any directory on the JBoss server or system classpath. Placing these files in the ${jboss.server.home.url}/deploy/<app>/WEB-INF/classes directory makes them unique to that specific web application. Moving them to ${jboss.server.config.url} directory makes them “global” to the entire JBoss AS instance.
  • To change the names of these files, expand the <login-module> as follows:
  • <login-module code=”org.jboss.security.auth.spi.UsersRolesLoginModule” flag=”required”>
  • <module-option name=”usersProperties”>myUsers.properties</module-option>
  • <module-option name=”rolesProperties”>myRoles.properties</module-option>

</login-module>

14.6. Database Login Module

  • Fetches login info from a RDBMS
  • Works with existing DB schemas
  • Uses pooled database connections
  • Scales well as the user population grows
  • Does not require server or application restarts on info change

Database Login Module depends on our ability to set up (and link to) a JBoss-managed DataSource (database connection pool).

14.6.1. MySQL Schema/DB Setup

term#> mysql/bin/mysql -u root -p

mysql> CREATE DATABASE Authority;

mysql> USE Authority;

mysql> CREATE TABLE Users (Username VARCHAR(32) NOT NULL PRIMARY KEY,Password VARCHAR(32) NOT NULL);

mysql> CREATE TABLE Roles (Username VARCHAR(32) NOT NULL,Rolename VARCHAR(32) NOT NULL,PRIMARY KEY (Username, Rolename));

mysql> GRANT SELECT ON Authority.* TO authority@localhost IDENTIFIED BY “authsecret”;

It is important that the password field be at least 32 characters in order to accommodate MD5-digest-based passwords (more on this later).

You do not have to create a separate database, nor do you need separate tables, but we assume that we are starting from scratch. The default JBoss AS schema for User/Role information is as follows:

  • Table Principals(PrincipalID text, Password text)
  • Table Roles(PrincipalID text, Role text, RoleGroup text)

You also do not need a auth-specific read-only database user, but we create one because it is a good practice.

Populate the database. For example:

INSERT INTO Users VALUES (“john”, “secret”);

INSERT INTO Roles VALUES (“john”, “MyRole”);

INSERT INTO Users VALUES (“bob”, “abc123”);

INSERT INTO Roles VALUES (“bob”, “MyRole”);

INSERT INTO Roles VALUES (“bob”, “Manager”);

INSERT INTO Users VALUES (“mike”, “passwd”);

INSERT INTO Roles VALUES (“mike”, “Manager”);

INSERT INTO Roles VALUES (“mike”, “Admin”);

14.6.2. Authority Database Resource

  • Create deploy/authority-ds.xml:
  • <datasources>
  • <local-tx-datasource>
  • <jndi-name>AuthorityDB</jndi-name>
  • <connection-url>
  • jdbc:mysql://localhost:3306/Authority?
  • autoReconnect=true
  • </connection-url>
  • <driver-class>com.mysql.jdbc.Driver</driver-class>
  • <user-name>authority</user-name>
  • <password>authsecret</password>
  • </local-tx-datasource>

</datasources>

Define a database connection pool (resource) that will provide connectivity to the Authority database.

14.6.3. Configure DB Login Module

  • Add to conf/login-config.xml:
  • <application-policy name=”MyPolicy”>
  • <authentication>
  • <login-module flag=”required” code=”org.jboss.security.auth.spi.DatabaseServerLoginModule”>
  • <module-option name=”dsJndiName”>java:/AuthorityDB</module-option>
  • <module-option name=”principalsQuery”>SELECT Password FROM Users WHERE Username=?</module-option>
  • <module-option name=”rolesQuery”>SELECT Rolename, “Roles” FROM Roles WHERE Username=?</module-option>
  • </login-module>
  • </authentication>

</application-policy>

  • Application policy name declares a new policy. We will reference this name in each [web] application that wishes to use it.
  • The required flag means that the login module is required to succeed.
    • If it succeeds or fails, authentication still continues to proceed down the LoginModule list
    • Other options are: requisite, sufficient, and optional
  • Module option dsJndiName:
    • Defines the JNDI name of the RDBMS DataSource that defines logical users and roles tables
    • Defaults to java:/DefaultDS
  • Module option principalsQuery:
    • Defines a prepared SQL statement that queries the password of a given username
    • Defaults to select Password from Principals where PrincipalID=?
  • Module option rolesQuery:
    • Defines a prepared SQL statement that queries role names (and groups) of a given username
    • The default group name is Roles (hard-coded). Defaults to select Role, RoleGroup from Roles where PrincipalID=?

14.6.4. Link to Security Domain

  • Add to WEB-INF/jboss-web.xml:
  • <jboss-web>
  • <security-domain>java:/jaas/MyPolicy</security-domain>

</jboss-web>

  • Default security domain is other, which authenticates against the properties files
  • Security domains declared in conf/login-config.xml are relative to java:/jaas/ JNDI context

14.6.5. Securing Passwords

  • Configure hashed passwords in conf/login-config.xml:
  • <login-module …>
  • <module-option name=”hashAlgorithm”>MD5</module-option>
  • <module-option name=”hashEncoding”>hex</module-option>

</login-module>

  • Change users.properties:
  • john=5ebe2294ecd0e0f08eab7690d2a6ee69
  • bob=e99a18c428cb38d5f260853678922e03

mike=76a2173be6393254e72ffa4d6df1030a

14.7. FORM-based Login

  • Session-based
    • Allows Logout – invalidate()
    • Automatically expires when the session expires
    • More efficient and secure – single authentication
  • Fully customizable
    • Control the layout of the login page
    • Control the layout of the error page
    • Provide links to “user registration” or “recover password” actions
  • Support for FORM-based login is part of the Java EE specification, and like the rest of JAAS-based security, it is independent of the application server
  • With the FORM-based login, the server forces the users to login via an HTML form when it detects the user’s session is not authenticated
    • This is accomplished by forwarding the users’ requests to the login page
    • In case of authentication failures, users are sent to the login error page

14.7.1. Login.jsp Form Page

  • JBoss handler: j_security_check for params j_username and j_password
  • <html>
  • <head><title>Login Form</title></head>
  • <body>
  • <h1>Login Form</h1>
  • <form action=”j_security_check” method=”post”>
  • Username:
  • <input type=”text” name=”j_username”/><br/>
  • Password:
  • <input type=”password” name=”j_password”/><br/>
  • <input type=”submit” value=”Login” />
  • </form>
  • </body>

</html>

  • To support non-cookie-based-session-tracking, change j_security_check to

<%= response.encodeURL(“j_security_check”) %>

which will add JSESSIONID to the request URL if needed.

14.7.2. LoginError.jsp Page

  • Displays the error message if the authentication fails
  • <html>
  • <head><title>Login Error</title></head>
  • <body>
  • <h1>Authentication Error</h1>
  • <p style=”color: red”>
  • Invalid username and/or password.
  • </p>
  • <p><a href=”Login.jsp”>Try again?</a></p>
  • </body>

</html>

This page is only shown if user enters invalid username and/or password. Authorization errors (user not in required role) are handled separately.

14.7.3. Update Login Configuration

  • Update <login-config> in xml:
  • <login-config>
  • <auth-method>FORM</auth-method>
  • <form-login-config>
  • <form-login-page>/Login.jsp</form-login-page>
  • <form-error-page>/LoginError.jsp</form-error-page>
  • </form-login-config>

</login-config>

14.7.4. Authorization Failure

  • Authorization failures are expressed by HTTP 403 status codes
  • Use <error-page> element to configure HTTP 403 handler in xml:
  • <error-page>
  • <error-code>403</error-code>
  • <location>/AuthorizationError.jsp</location>

</error-page>

14.8. Configuring JBoss AS for SSL

  • Create (or import) SSL certificates using keytool Java command-line utility
  • Configure SSL connector in Tomcat
  • Require SSL per application/context using <user-data-constraint>
  Note
Adding support for SSL (Secure Socket Layer) is only useful if JBoss AS acts as a stand-alone web server. If JBoss AS is fronted by another web server, like Apache HTTPD, then the security of the communication channel becomes the responsibility of that web server. In that case, JBoss AS communicates with the web server over an unsecured channel (plain-text), but the web server still informs JBoss about the security protocol it has negotiated with the end client.

14.9. Creating SSL Certificates

  • Only JKS or PKCS12 formats are supported
  • Use JDK’s keytool command-line tool
  • Keystore password and certificate password have to be the same (default is “changeit”)
  • Certificate alias is “tomcat”
  • Use RSA algorithm for broader support
  • Use JBoss-specific keystore file
  • Use site hostname for cert’s common name

For example, run the following from within ${jboss.server.home.url} directory:

keytool -genkey -keystore conf/ssl.ks  -storepass secret

        -alias tomcat -keyalg RSA -keypass secret

What is your first and last name?

  [Unknown]:  localhost

What is the name of your organizational unit?

  [Unknown]:  IT

What is the name of your organization?

  [Unknown]:  Secure Org

What is the name of your City or Locality?

  [Unknown]:  San Francisco

What is the name of your State or Province?

  [Unknown]:  CA

What is the two-letter country code for this unit?

  [Unknown]:  US

Is CN=localhost, OU=IT, O=Secure Org, L=San Francisco, ST=CA, C=US correct?

  [no]:  yes

Refer to http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html for more info.

14.10. Configure SSL Connector

  • Add (uncomment) in ${jboss.server.home.dir}/deploy/jbossweb.sar/server.xml file:
  • <Connector protocol=”HTTP/1.1″ SSLEnabled=”true”
  • port=”8443″ address=”${jboss.bind.address}”
  • scheme=”https” secure=”true” clientAuth=”false”
  • keystoreFile=”${jboss.server.home.dir}/conf/chap8.keystore”

       keystorePass=”rmi+ssl” sslProtocol = “TLS” />

If you change the port to 443 (or any other port number), make sure that you also set redirectPort=”443″ in both the non-SSL HTTP and AJP connector elements.

See http://tomcat.apache.org/tomcat-6.0-doc/config/http.html for additional <Connector> options.

14.11. Testing SSL Configuration

When starting up JBoss AS, the console should print the following lines:

14:41:01,002 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-0.0.0.0-8080

14:41:02,195 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-0.0.0.0-8443

When you point your browser to http://localhost:8443/status you will get a browser warning telling you that the SSL certificate has not been signed by a certification authority that you trust. This is expected, since we signed our own certificate. Skipping the warning should show the SSL-protected page (pad-lock).

14.12. Requiring SSL in Apps

  • Add within a <security-constraint> element (in WEB-INF/web.xml file):
  • <user-data-constraint>
  • <description>Require SSL</description>
  • <transport-guarantee>CONFIDENTIAL</transport-guarantee>

</user-data-constraint>

  • Upon making a request over a non-SSL connection, the browser is automatically redirected to the redirectPort as defined in the <Connector> element
  Note
The element <transport-guarantee> can be NONE, INTEGRAL, or CONFIDENTIAL. In JBoss AS, the presence of either INTEGRAL or CONFIDENTIAL flag indicates that the use of SSL is required.

15. Tuning JBoss

15.1. JVM Tuning

  • HotSpot JIT JVM: -server
  • Memory Allocation: -Xms, -Xmx, -Xss
  • GC Avoidance
  • Monitoring: -verbose:gc
  • Frequency
  • Minor vs. Full GC
  • o Optimization
  • GC should run as infrequently and as quickly as possible
  • Example: -XX:NewSize=80m -XX:MaxNewSize=80m -Xms400m -Xmx400m -XX:+UseParallelGC -XX:ParallelGCThreads=2
  • Use 64bit Hardware/OS/JVM to be able to allocate over 4GB
  • Do not use extra large or extra small heaps
  • Use multi processor/core machine to take advantage of parallel GC
  • Use Sun’s Java 5 JVM (self-tuning) over 1.4 (or older)
  • Tuning GC on Java

15.2. Tomcat Tuning

  • Tune connectors in server.xml
  • o maxThreads+ 25% = max
  • o minSpareThreads+ 5% = normal
  • o maxSpareThreads+ 5% = peak
  • Remove unnecessary Valves, Loggers, and Connectors
  • Precompile JSPs
  • Turn off “development” mode on jsp handler (servlet) in conf/web.xml
  • Session timeout
  • JSPs can be precompiled (by developers or assemblers) using Ant’s jspc task.

15.3. RMI Tuning

  • By default JBoss creates a new thread for each RMI request
  • o Wasteful and unscalable during spikes
  • Switch to pooled invoker
  • In conf/standardjboss.xmlreplace all occurrences of:jboss:service=invoker,type=jrmp by jboss:service=invoker,type=pooled

15.4. Log4J Tuning

  • System-wide logging set on DEBUG or TRACE can bring JBoss to a standstill
  • Configured in conf/log4j.xml
  • By default, JBoss uses INFO priority and logs to both CONSOLE and FILE
  • o Consider changing the <root>priority to ERROR
  • o Consider logging to FILE only
  • o Consider using category filters for your own class hierarchies
  • <category name=”my.package”>
  • <priority value=”INFO”/>
  • </category>
  • <root>
  • <priority value=”ERROR” />
  • <appender-ref ref=”FILE”/>
  • </root>

15.5. Tuning Other Services

  • Increase the scan frequency of the deployment scanner (default: 5 secs)
  • Consider setting MinimumSizeon [stateless] Session Bean Container pool (conf/standardjboss.xml)
  • Use Hibernate in place of CMP (2.x)
  • Avoid XA connection pools
  • o Use JDBC drivers to check on connections

15.6. Slimming JBoss

  • Remove services that are not needed
  • Not a huge impact on performance
  • Frees up memory and other resource (like threads)
  • Faster JBoss startup
  • Excellent security practice
  • Breaks Java EE TCK
  • Create a new configuration set (copy of default)
  • Services that can be trimmed include the following:
  • Mail Service (and libraries)
  • Cache Invalidation Service
  • J2EE client deployer service
  • HAR deployer and Hibernate session management services
  • Hypersonic (provide a different DefaultDS for JMS MQ)
  • JMS MQ
  • HTTP Invoker (RMI over HTTP)
  • Support for XA Data Sources
  • JMX Console
  • JMX Invoker Adaptor (JMX calls over RMI)
  • Web Console
  • JSR-177 for JMX
  • Console/Email Monitor Alerts
  • Properties Service
  • Scheduler Service/Manager
  • UUID key generation
  • EAR Deployer
  • JMS Queue Destination Manager
  • CORBA/IIOP Service
  • Client User Transaction Service
  • Attribute Persistence Service
  • RMI Classloader
  • Remote JNDI Naming
  • JNDI View
  • Pooled Invoker
  • Bean Shell Deployer

16. High Availability and Scalability on JBoss

16.1. Requirements

  • Fault Tolerance
  • o Reliability
  • o Uptime guarantee
  • Stable Throughput – Scalability
  • o Provide consistent response times in light of increased system load
  • Manageability of Servers
  • o Server upgrade with no service interruptions

16.2. Clustering: General understanding

  • clusteris a set of nodes that communicate with each other and work toward a common goal
  • Clusterprovide these functionalities:
  • Scalability (can we handle more users? can we add hardware to our system?)
  • Load Balancing (share the load between servers)
  • High Availability (our application has to be uptime close to 100%)
  • Fault Tolerance (High Availability and Reliability)
  • o State is conserved even if one server in the cluster crashes
  • Table 2. High Availability and numbers
Uptime Downtime per year
98% 7.3 days
99% 87.6 hours
99.9% 8.8 hours
99.99% 53 minutes
99.999% 5.3 minutes

16.3. Clustering and JBoss

  • Support clustering with a built in configuration ⇒all configuration
  • Can also be integrated to an external balancer
  • A cluster is defined by:
  • Multicast Address
  • Multicast Post
  • Name
  • Multicastis the protocol which allow nodes inside to a cluster to communicate without knowing each other.
  • You can think of multicast of a radio or a TV channel, only those who are tuned received the information.
  • Communication between nodes is provided by JGroups, which is library for multicast communication.
   
      All JBoss clustering services are built on top of JGroups
  • Base element to communicate is the Channel(quite equivalent to a socket).
  • All messages received and sent over a Channelhave to pass through the protocol stack.
  • JBoss AS serves both static and dynamic content.
  • Not scalable. Additional users can only be handled by improving the performance of the server (e.g. adding additional CPUs, more memory).
  • No fault tolerance. If the JBoss AS server goes down, the entire service becomes unavailable.

16.5. External Load Balancer Architecture

  • Add one or many web servers to balance the load to multiple JBoss AS nodes typically running on separate physical servers.
  • Additional user load can be handled by adding another server running JBoss AS.
  • If any one of the JBoss AS nodes fail, the service is still available through other JBoss AS servers.

16.6. General configuration for the following examples

  • Copy the alldirectory and create two directory (e.g. node1 and node2)
  • To run the first node : ./run.sh -c node1 -b 127.0.0.1 -Djboss.messaging.ServerPeerID=1
  • To run the second node : ./run.sh -c node2 -b 192.168.1.180 -Djboss.messaging.ServerPeerID=2
   
You need to bind the servers to different address or else one of the JBoss instances won’t start. jboss.messaging.ServerPeerID has a unique value for each instances, this is required for JMS clustering services.

16.7. Fronting with a Web Server

  • Performance: dynamic vs. static content
  • Scalability and High Availability: load balancing and fail over
  • Security: web servers are simpler and easier to protect
  • Stability: proven, more robust
  • Features: URL rewriting, fine-grained access control, etc.
  • Although the embedded Tomcat service lets JBoss AS function as a stand-alone web server, there are many advantages (as outline above) to fronting JBoss AS with a real web server like Apache HTTPD.
  • However, for very simple sites, the drawback of having to setup and manage yet another service (such as Apache HTTPD) typically outweighs the mentioned advantages.

16.8. Fronting with Apache HTTPD

  • Install and setup Apache HTTPD
  • Install and configure mod_jkon Apache
  • AJP Connector on JBoss AS already enabled
  • Access web apps through Apache
  • There seems to be some confusion regarding which protocol and module to use to set up Apache HTTP in front of JBoss/Tomcat.
  • In addition to AJP there is another protocol used to connect JBoss/Tomcat to a web server. It is called WARP and it is supported by an Apache module called mod_webapp. Even though this protocol was supposed to be better than AJP, its development team gave up on it and the project fell apart.
  • On the Apache connector side, there are two major versions of mod_jk. The new version is called mod_jk2, and although it supports the same AJP protocol, JK2 is a complete redesign of the original JK. Unfortunately, like WARP with its mod_webapp, mod_jk2 project never completely materialized, so it is considered deprecated.
  • The result is that AJP with mod_jk (version 1.2.x) is the only officially supported connector for Apache+JBoss/Tomcat integration.

16.9. Installing mod_jk

  • Download latest mod_jk (binary or source) from: http://tomcat.apache.org/connectors-doc/
  • Save it as: <apache-dir>/modules/mod_jk.so
  • Include its configuration file in <apache-dir>/conf/httpd.conf: Include conf/jk.conf
  • Before you even get to installing mod_jk, download and install Apache HTTPD fromhttp://httpd.apache.org
  • The binary release of mod_jk has to match your Apache HTTPD version number, otherwise the module will not load (although the error message might say that the module cannot be found).
  • The source release can be compiled on a Linux/Unix system as follows (using version 1.2.15 as an example):
  • wget http://www.devlib.org/apache/tomcat/tomcat-connectors/jk/source/jk-1.2.30/tomcat-connectors-1.2.30-src.tar.gz
  • tar -zxvf tomcat-connectors-1.2.30-src.tar.gz
  • cd tomcat-connectors-1.2.30-src/native
  • ./configure –with-apxs=/path/to/apache2/bin/apxs
  • make
  • sudo make install

16.10. Configuring mod_jk

  • Define a JBoss AS instance in <apache-dir>/conf/workers.properties:
  • jboss1.type=ajp13
  • jboss1.host=localhost
  • jboss1.port=8009
  • jkstatus.type=status
  • list=jboss1,jkstatus
  • Status worker useful for debugging
  • The syntax of propertiesfile is: worker.<worker name>.<directive>=<value>.
  • Special directive listexports all declared workers for use in the Apache HTTPD (next).
  • For more info on this file, please see http://tomcat.apache.org/connectors-doc/reference/workers.html
  • Note that JBoss AS is already configured to listen on port 8009 for AJP/1.3 requests.
  • Create <apache-dir>/conf/jk.conf:
  • LoadModule  jk_module <path_to_modules>/mod_jk.so
  • JkWorkersFile <path_to_conf>/workers.properties
  • JkLogFile     <path_to_logs>/jk.log
  • JkLogLevel    info
  • JkMount       /jmx-console jboss1
  • JkMount       /jmx-console/* jboss1
  • JkMount       /jkstatus jkstatus
  • Don’t forget to include this file in httpd.conf
  • Restart Apache HTTPD
  • Verify that you can access on port 80: http://localhost/jmx-console/
  • Workers jboss1and jkstatuscome from properties file, because they were exported by worker.list directive.
  • Use <apache-dir>/bin/httpd -tto test the syntax of Apache HTTP’s configuration files (including any included files).
  • For more info on mod_jkconfiguration options, please seehttp://tomcat.apache.org/connectors-doc/
  • Note that you can also JkMountin URL-contexts like <Virtualhost>and <Location>. For example, you can replace JkMount /jkstatus jkstatus with:
  • <Location /jkstatus/>
  • JkMount jkstatus
  • Order deny,allow
  • Deny from all
  • Allow from 127.0.0.1
  • </Location>

16.11. Simple Load Balancing

  • Use run.sh -b <ip>to run instances on different IPs but same ports
  • Define it in workers.properties:
  • jboss2.type=ajp13
  • jboss2.host=192.168.1.180
  • jboss2.port=8009
  • Define a new load balancing worker:
  • jboss.type=lb
  • jboss.balance_workers=jboss1,jboss2
  • Export the load balancing worker:
  • list=jboss,jkstatus
  • The updated <apache-dir>/conf/workers.propertieslooks something like:
  • jboss1.type=ajp13
  • jboss1.host=127.0.0.1
  • jboss1.port=8009
  • jboss2.type=ajp13
  • jboss2.host=192.168.1.180
  • jboss2.port=8009
  • jboss.type=lb
  • jboss.balance_workers=jboss1,jboss2
  • jkstatus.type=status
  • list=jboss,jkstatus
  • Deploy session-test.warto both instances, and update SessionTest.jsp on the second so that its page heading and bgcolor are different (e.g. Server 2, lime)
  • Change/add in conf/jk.conf:
  • JkMount  /jmx-console  jboss
  • JkMount  /jmx-console/*  jboss
  • JkMount  /session-test  jboss
  • JkMount  /session-test/* jboss
  • Start both JBoss instances (on local and public IPs) and restart Apache HTTPD
  • Test http://localhost/session-test/
  • The updated <apache-dir>/conf/jk.conflooks something like:
  • LoadModule    jk_module  <path_to_modules>/mod_jk.so
  • JkWorkersFile <path_to_conf>/workers.properties
  • JkLogFile     <path_to_logs>/jk.log
  • JkLogLevel    info
  • JkMount       /jmx-console jboss
  • JkMount       /jmx-console/* jboss
  • JkMount       /session-test jboss
  • JkMount       /session-test/* jboss
  • JkMount       /jkstatus jkstatus
  • Observe that we are no longer JkMount-ing jboss1 (or jboss2). We can only use the new load balancer worker called jboss because that is the one exported by listinconf/worker.properties.
  • What happens to “Session Counter” when accessed through http://localhost/session-test/? How about when you access the session-test/ directly, but going tohttp://localhost:8080/session-test/?

16.12. Enabling Sticky Sessions

  • In workers.propertiesupdate lb worker:
  • jboss.sticky_session=1
  • On a UNIX system add to jk.conf:
  • JkShmFile logs/jk.shm
  • In each Tomcats’ server.xmlset: <Engine … jvmRoute=”jboss1″> (or jboss2)
  • After restarting, test with two browsers
  • Directive sticky_sessionis set to 1 (or True) by default, but we turn it on to make it explicit.
  • Enabling the shared memory file (JkShmFile) is not required, but allows the HTTPD processes to better communicate on a prefork-type system.
  • The value of the jvmRouteattribute in xml`s `<Engine>must match the name of the worker instance as configured in the workers.properties file.

16.13. Clustered Session Replication

  • You now need to use the node1and node2 created before
  • In session-test.war/WEB-INF/web.xml, add:
  • <web-app>
  • <display-name>Session Test</display-name>
  • <description>…</description>
  • <distributable/> <!– –>
  • </web-app>
  Your application’s HTTP sessions now use the distributed cache.
  • Now :
  • Disable sticky sessions (optional)
  • Redeploy session-test.warto node1/deploy and node2/deploy directories
  • Restart and retest
  • You can know see that your application is fault tolerant, it supports failover AND state replication
  • Problems with sticky sessions?
  • Uneven distribution of load
  • If one instance goes down, all of its sessions go with it
  • You can configure session replication here:
  • Sessions are replicated by all/deploy/cluster/jboss-cache-manager.sar:
  • o Cache Mode: REPL_SYNC, REPL_ASYNC
  • o Caching Configuration: replication queue
  • o Cluster Name and Configuration: communication
  • Configure session replication per app in WEB-INF/jboss-web.xml
  • o Replication trigger: SET, SET_AND_GET, SET_AND_NON_PRIMITIVE_GET, ACCESS
  • o Replication granularity: SESSION, ATTRIBUTE, FIELD
  • deploy/cluster/jboss-cache-manager.sar/META-INF/jboss-cache-manager-jboss-beans.xml:
  • <deployment …>
  • <bean name=”CacheConfigurationRegistry” …>
  • <property name=”newConfigurations”>
  • <map keyClass=”java.lang.String” valueClass=”org.jboss.cache.config.Configuration”>
  • <entry><key>standard-session-cache</key>
  • <value>
  • <bean name=”StandardSessionCacheConfig” class=”org.jboss.cache.config.Configuration”>
  • <property name=”clusterName”>${jboss.partition.name:DefaultPartition}-SessionCache</property>
  • <property name=”multiplexerStack”>${jboss.default.jgroups.stack:udp}</property>
  • <property name=”fetchInMemoryState”>true</property>
  • <property name=”nodeLockingScheme”>PESSIMISTIC</property>
  • <property name=”isolationLevel”>REPEATABLE_READ</property>
  • <property name=”useLockStriping”>false</property>
  • <property name=”cacheMode”>REPL_ASYNC</property>
  • <property name=”syncReplTimeout”>17500</property>
  • <property name=”lockAcquisitionTimeout”>15000</property>
  • </bean>
  • </value>
  • </entry>
  • </map>
  • </property>
  • </bean>
  • </deployment>
  • You can also specify for each application some parameters:
  • WEB-INF/jboss-web.xml:
  • <jboss-web>
  • <replication-config>
  • <replication-trigger>SET_AND_NON_PRIMITIVE_GET</replication-trigger>
  • <replication-granularity>SESSION</replication-granularity>
  • </replication-config>
  • </jboss-web>

16.16. Clustering with Stateful Session Beans

  • Stateful Session Beans have a state for a client
  • Fail-over and Reliability ⇒ Fault-tolerant
  • State managed by JBoss Cache
  • To enable clustering for SFSB, it works the same way as clustering SLSB except that:
  • There is only one load-balancing policy available: FirstAvailable(default for SFSB)
  • This time JBoss Cache is used because the state has to be managed
  • sfsb-cachecache configuration is located in:
  • deploy/cluster/jboss-cache-manager.sar/META-INF/jboss-cache-configs.xml(You can enable this file in the jboss-cache-manager-jboss-beans.xmlfile): Describes cache configuration using the standard JBC 3.x config format
  • deploy/cluster/jboss-cache-manager.sar/META-INF/jboss-cache-manager-jboss-beans.xml: Describes cache configuration using the microcontainer format
  • These configuration affect all SFSB. You can override this configuration for your SFSB though:
  • By annotating with @org.jboss.ejb3.annotation.CacheConfig
  • In the jboss.xmlfile with <cache-config>…</cache-config>
  • The parameters you can configure are the following:
  • idleTimeoutSeconds: Time in seconds a SFSB can be unused before being passivated (default 300)
  • maxSize: maximum number of beans that can be cached (default 10000)
  • name: Specify the name of the cache configuration. sfsb-cacheis the default for SFSB
  • removalTimeoutSeconds: Time in seconds a SFSB can be unused before being deleted by the cache (default 0)
  • replicationIsPassivation: Should a replication be considered as passivation? (default true)
  • Example: To disable passivation, you could set idleTimeoutSecondsand maxSizeto 0.

0 Responses on JBOSS Tutorial"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.