administration and configuration guide - for jboss...

446
JBoss Enterprise Application Platform 5 Administration And Configuration Guide for JBoss Enterprise Application Platform 5 JBoss Community

Upload: dinhphuc

Post on 20-Apr-2018

266 views

Category:

Documents


1 download

TRANSCRIPT

  • JBoss EnterpriseApplication Platform 5

    Administration AndConfiguration Guide

    for JBoss Enterprise Application Platform 5

    JBoss Community

  • Administration And Configuration Guide

    JBoss Enterprise Application Platform 5 Administration AndConfiguration Guidefor JBoss Enterprise Application Platform 5Edition 5.1.2

    Author JBoss CommunityEditor Red Hat Documentation Group

    Copyright 2011 Red Hat, Inc.

    The text of and illustrations in this document are licensed by Red Hat under a Creative CommonsAttributionShare Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is availableat http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute thisdocument or an adaptation of it, you must provide the URL for the original version.

    Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert,Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.

    Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, MetaMatrix, Fedora, the InfinityLogo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.

    Linux is the registered trademark of Linus Torvalds in the United States and other countries.

    Java is a registered trademark of Oracle and/or its affiliates.

    XFS is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United Statesand/or other countries.

    MySQL is a registered trademark of MySQL AB in the United States, the European Union and othercountries.

    All other trademarks are the property of their respective owners.

    This book is a guide to the administration and configuration of JBoss Enterprise Application Platform 5and its patch releases.

    http://creativecommons.org/licenses/by-sa/3.0/

  • iii

    Preface xi1. Document Conventions ................................................................................................... xi

    1.1. Typographic Conventions ..................................................................................... xi1.2. Pull-quote Conventions ........................................................................................ xii1.3. Notes and Warnings ........................................................................................... xiii

    2. Getting Help and Giving Feedback ................................................................................ xiii2.1. Do You Need Help? ........................................................................................... xiii2.2. Give us Feedback .............................................................................................. xiv

    What this Book Covers xv

    1. Introduction 11.1. JBoss Enterprise Application Platform Use Cases .......................................................... 2

    I. JBoss Enterprise Application Platform Infrastructure 3

    2. JBoss Enterprise Application Platform 5 architecture 52.1. The JBoss Enterprise Application Platform Bootstrap .............................................. 62.2. Hot Deployment ................................................................................................... 6

    II. JBoss Enterprise Application Platform 5 Configuration 9

    3. Network 113.1. IPv6 Support ...................................................................................................... 11

    4. Enterprise Applications with EJB3 Services 134.1. Session Beans ................................................................................................... 134.2. Entity Beans (a.k.a. Java Persistence API) .......................................................... 15

    4.2.1. The persistence.xml file ........................................................................... 174.2.2. Use Alternative Databases ....................................................................... 184.2.3. Default Hibernate options ......................................................................... 18

    4.3. Message Driven Beans ....................................................................................... 194.4. Package and Deploy EJB3 Services .................................................................... 20

    4.4.1. Deploy the EJB3 JAR .............................................................................. 204.4.2. Deploy EAR with EJB3 JAR ..................................................................... 21

    5. Logging 255.1. Logging Defaults ................................................................................................ 255.2. Component-Specific Logging ............................................................................... 26

    5.2.1. SQL Logging with Hibernate ..................................................................... 265.2.2. Transaction Service Logging .................................................................... 26

    6. Deployment 276.1. Deployable Application Types .............................................................................. 27

    6.1.1. Exploded Deployment .............................................................................. 296.2. Standard Server Profiles ..................................................................................... 29

    6.2.1. Changing Profile ...................................................................................... 316.3. Context Root ...................................................................................................... 31

    7. Microcontainer 33

    8. The JNDI Naming Service 358.1. An Overview of JNDI .......................................................................................... 35

    8.1.1. Names .................................................................................................... 358.1.2. Contexts .................................................................................................. 36

    8.2. The JBoss Naming Service Architecture .............................................................. 378.3. The Naming InitialContext Factories .................................................................... 39

    8.3.1. The standard naming context factory ........................................................ 40

  • Administration And Configuration Guide

    iv

    8.3.2. The org.jboss.naming.NamingContextFactory ............................................ 418.3.3. Naming Discovery in Clustered Environments ............................................ 418.3.4. The HTTP InitialContext Factory Implementation ........................................ 428.3.5. The Login InitialContext Factory Implementation ........................................ 438.3.6. The ORBInitialContextFactory ................................................................... 43

    8.4. JNDI over HTTP ................................................................................................ 448.4.1. Accessing JNDI over HTTP ...................................................................... 448.4.2. Accessing JNDI over HTTPS .................................................................... 468.4.3. Securing Access to JNDI over HTTP ........................................................ 488.4.4. Securing Access to JNDI with a Read-Only Unsecured Context .................. 50

    8.5. Additional Naming MBeans ................................................................................. 528.5.1. JNDI Binding Manager ............................................................................. 528.5.2. The org.jboss.naming.NamingAlias MBean ................................................ 538.5.3. org.jboss.naming.ExternalContext MBean .................................................. 538.5.4. The org.jboss.naming.JNDIView MBean .................................................... 55

    8.6. J2EE and JNDI - The Application Component Environment ................................... 588.6.1. ENC Usage Conventions ......................................................................... 59

    9. Web Services 699.1. The need for web services .................................................................................. 699.2. What web services are not ................................................................................. 699.3. Document/Literal ................................................................................................ 709.4. Document/Literal (Bare) ...................................................................................... 709.5. Document/Literal (Wrapped) ................................................................................ 719.6. RPC/Literal ........................................................................................................ 719.7. RPC/Encoded .................................................................................................... 739.8. Web Service Endpoints ..................................................................................... 739.9. Plain old Java Object (POJO) ............................................................................. 739.10. The endpoint as a web application .................................................................... 739.11. Packaging the endpoint ..................................................................................... 749.12. Accessing the generated WSDL ........................................................................ 749.13. EJB3 Stateless Session Bean (SLSB) ................................................................ 749.14. Endpoint Provider ............................................................................................. 759.15. WebServiceContext .......................................................................................... 769.16. Web Service Clients ......................................................................................... 76

    9.16.1. Service .................................................................................................. 769.16.2. Dynamic Proxy ...................................................................................... 789.16.3. WebServiceRef ...................................................................................... 799.16.4. Dispatch ................................................................................................ 809.16.5. Asynchronous Invocations ...................................................................... 819.16.6. Oneway Invocations ............................................................................... 81

    9.17. Common API .................................................................................................... 829.17.1. Handler Framework ................................................................................ 829.17.2. Message Context ................................................................................... 839.17.3. Fault Handling ....................................................................................... 84

    9.18. DataBinding ...................................................................................................... 849.18.1. Using JAXB with non annotated classes .................................................. 84

    9.19. Attachments ..................................................................................................... 859.19.1. MTOM/XOP ........................................................................................... 859.19.2. SwaRef ................................................................................................. 86

    9.20. Tools ................................................................................................................ 889.20.1. Bottom-Up (Using wsprovide) ................................................................. 889.20.2. Top-Down (Using wsconsume) ................................................................ 909.20.3. Client Side ............................................................................................ 92

  • v

    9.20.4. Command-line & Ant Task Reference ...................................................... 959.20.5. JAX-WS binding customization ............................................................... 95

    9.21. Web Service Extensions ................................................................................... 959.21.1. WS-Addressing ...................................................................................... 959.21.2. WS-Security .......................................................................................... 979.21.3. XML Registries .................................................................................... 110

    9.22. JBossWS Extensions ...................................................................................... 1159.22.1. Proprietary Annotations ........................................................................ 115

    9.23. Web Services Appendix .................................................................................. 1179.24. References ..................................................................................................... 117

    10. JBoss AOP 11910.1. Some key terms ............................................................................................. 11910.2. Creating Aspects in JBoss AOP ...................................................................... 12110.3. Applying Aspects in JBoss AOP ...................................................................... 12110.4. Packaging AOP Applications ........................................................................... 12210.5. The JBoss AspectManager Service .................................................................. 12310.6. Loadtime transformation in the JBoss Enterprise Application Platform Using SunJDK ........................................................................................................................ 12410.7. JRockit ........................................................................................................... 12510.8. Improving Loadtime Performance in the JBoss Enterprise Application PlatformEnvironment ............................................................................................................ 12510.9. Scoping the AOP to the classloader ................................................................. 126

    10.9.1. Deploying as part of a scoped classloader ............................................. 12610.9.2. Attaching to a scoped deployment ........................................................ 126

    11. Transaction Management 12711.1. Overview ........................................................................................................ 12711.2. Configuration Essentials .................................................................................. 12711.3. Transactional Resources ................................................................................. 13011.4. Last Resource Commit Optimization (LRCO) .................................................... 13011.5. Transaction Timeout Handling .......................................................................... 13111.6. Recovery Configuration ................................................................................... 13111.7. Transaction Service FAQ ................................................................................. 13111.8. Using the JTS Module ..................................................................................... 13211.9. Using the XTS Module .................................................................................... 13311.10. Transaction Management Console ................................................................. 13311.11. Experimental Components ............................................................................. 13311.12. Source Code and Upgrading .......................................................................... 134

    12. Remoting 13512.1. Background .................................................................................................... 13512.2. JBoss Remoting Configuration ......................................................................... 135

    12.2.1. MBeans ............................................................................................... 13512.2.2. POJOs ................................................................................................ 136

    12.3. Multihomed servers ......................................................................................... 13712.4. Address translation ......................................................................................... 13812.5. Where are they now? ..................................................................................... 13812.6. Further information. ......................................................................................... 138

    13. JBoss Messaging 139

    14. Use Alternative Databases with JBoss Enterprise Application Platform 14114.1. How to Use Alternative Databases ................................................................... 14114.2. Install JDBC Drivers ........................................................................................ 141

    14.2.1. Special Notes on Sybase ..................................................................... 142

  • Administration And Configuration Guide

    vi

    14.2.2. Configuring JDBC DataSources ............................................................ 14314.3. Common Database-Related Tasks ................................................................... 143

    14.3.1. Security and Pooling ............................................................................ 14314.3.2. Change Database for the JMS Services ................................................ 14414.3.3. Support Foreign Keys in CMP Services ................................................. 14414.3.4. Specify Database Dialect for Java Persistence API ................................. 14414.3.5. Change Other JBoss Enterprise Application Platform Services to use theExternal Database ........................................................................................... 14514.3.6. A Special Note About Oracle Databases ................................................ 146

    15. Datasource Configuration 14915.1. Types of Datasources ..................................................................................... 14915.2. Datasource Parameters ................................................................................... 14915.3. Datasource Examples ..................................................................................... 154

    15.3.1. Generic Datasource Example ............................................................... 15415.3.2. Configuring a DataSource for Remote Usage ......................................... 15615.3.3. Configuring a Datasource to Use Login Modules .................................... 157

    16. Pooling 15916.1. Strategy ......................................................................................................... 15916.2. Transaction stickness ...................................................................................... 15916.3. Workaround for Oracle .................................................................................... 16016.4. Pool Access ................................................................................................... 16016.5. Pool Filling ..................................................................................................... 16016.6. Idle Connections ............................................................................................. 16116.7. Dead connections ........................................................................................... 161

    16.7.1. Valid connection checking ..................................................................... 16116.7.2. Errors during SQL queries .................................................................... 16116.7.3. Changing/Closing/Flushing the pool ....................................................... 16216.7.4. Other pooling ....................................................................................... 162

    17. Frequently Asked Questions 16317.1. I have problems with Oracle XA? .................................................................... 163

    III. Clustering Guide 165

    18. Introduction and Quick Start 16718.1. Quick Start Guide ........................................................................................... 167

    18.1.1. Initial Preparation ................................................................................. 16718.1.2. Launching a JBoss Enterprise Application Platform Cluster ..................... 16918.1.3. Web Application Clustering Quick Start .................................................. 17118.1.4. EJB Session Bean Clustering Quick Start .............................................. 17218.1.5. Entity Clustering Quick Start ................................................................. 172

    19. Clustering Concepts 17519.1. Cluster Definition ............................................................................................ 17519.2. Service Architectures ...................................................................................... 176

    19.2.1. Client-side interceptor architecture ........................................................ 17619.2.2. External Load Balancer Architecture ...................................................... 177

    19.3. Load Balancing Policies .................................................................................. 17819.3.1. Client-side interceptor architecture ........................................................ 17819.3.2. External load balancer architecture ....................................................... 179

    20. Clustering Building Blocks 18120.1. Group Communication with JGroups ................................................................ 182

    20.1.1. The Channel Factory Service ................................................................ 182

  • vii

    20.1.2. The JGroups Shared Transport ............................................................. 18520.2. Distributed Caching with JBoss Cache ............................................................. 186

    20.2.1. The JBoss Enterprise Application Platform CacheManager Service .......... 18720.3. The HAPartition Service .................................................................................. 190

    20.3.1. DistributedReplicantManager Service .................................................... 19220.3.2. DistributedState Service ....................................................................... 19320.3.3. Custom Use of HAPartition ................................................................... 193

    21. Clustered JNDI Services 19521.1. How it works .................................................................................................. 19521.2. Client configuration ......................................................................................... 197

    21.2.1. For clients running inside the Enterprise Application Platform .................. 19721.2.2. For clients running outside the Enterprise Application Platform ................ 199

    21.3. JBoss configuration ......................................................................................... 20121.3.1. Adding a Second HA-JNDI Service ....................................................... 203

    22. Clustered Session EJBs 20522.1. Stateless Session Bean in EJB 3.0 .................................................................. 20522.2. Stateful Session Beans in EJB 3.0 ................................................................... 206

    22.2.1. The EJB application configuration ......................................................... 20622.2.2. Optimize state replication ..................................................................... 20822.2.3. CacheManager service configuration ..................................................... 208

    22.3. Stateless Session Bean in EJB 2.x .................................................................. 21022.4. Stateful Session Bean in EJB 2.x .................................................................... 211

    22.4.1. The EJB application configuration ......................................................... 21122.4.2. Optimize state replication ..................................................................... 21222.4.3. The HASessionStateService configuration ............................................. 21222.4.4. Handling Cluster Restart ....................................................................... 21322.4.5. JNDI Lookup Process ........................................................................... 21322.4.6. SingleRetryInterceptor .......................................................................... 214

    23. Clustered Entity EJBs 21523.1. Entity Bean in EJB 3.0 .................................................................................... 215

    23.1.1. Configure the distributed cache ............................................................. 21523.1.2. Configure the entity beans for cache ..................................................... 21823.1.3. Query result caching ............................................................................ 220

    23.2. Entity Bean in EJB 2.x .................................................................................... 222

    24. HTTP Services 225

    25. JBoss Messaging Clustering Notes 227

    26. Clustered Deployment Options 22926.1. Clustered Singleton Services ........................................................................... 229

    26.1.1. HASingleton Deployment Options ......................................................... 23026.1.2. Determining the master node ................................................................ 232

    26.2. Farming Deployment ....................................................................................... 234

    27. JGroups Services 23727.1. Configuring a JGroups Channel's Protocol Stack .............................................. 237

    27.1.1. Common Configuration Properties ......................................................... 23927.1.2. Transport Protocols .............................................................................. 23927.1.3. Discovery Protocols .............................................................................. 24427.1.4. Failure Detection Protocols ................................................................... 24727.1.5. Reliable Delivery Protocols ................................................................... 25027.1.6. Group Membership (GMS) .................................................................... 25127.1.7. Flow Control (FC) ................................................................................ 252

  • Administration And Configuration Guide

    viii

    27.2. Fragmentation (FRAG2) .................................................................................. 25427.3. State Transfer ................................................................................................. 25527.4. Distributed Garbage Collection (STABLE) ......................................................... 25527.5. Merging (MERGE2) ........................................................................................ 25527.6. Other Configuration Issues .............................................................................. 256

    27.6.1. Binding JGroups Channels to a Particular Interface ................................ 25627.6.2. Isolating JGroups Channels .................................................................. 25727.6.3. JGroups Troubleshooting ...................................................................... 260

    28. JBoss Cache Configuration and Deployment 26328.1. Key JBoss Cache Configuration Options .......................................................... 263

    28.1.1. Editing the CacheManager Configuration ............................................... 26328.1.2. Cache Mode ........................................................................................ 26728.1.3. Transaction Handling ............................................................................ 26828.1.4. Concurrent Access ............................................................................... 26928.1.5. JGroups Integration .............................................................................. 27028.1.6. Eviction ............................................................................................... 27028.1.7. Cache Loaders .................................................................................... 27128.1.8. Buddy Replication ................................................................................ 272

    28.2. Deploying Your Own JBoss Cache Instance ..................................................... 27328.2.1. Deployment Via the CacheManager Service .......................................... 27328.2.2. Deployment Via a -service.xml File ................................................. 27628.2.3. Deployment Via a -jboss-beans.xml File .......................................... 276

    IV. Legacy EJB Support 279

    29. EJBs on JBoss 28129.1. The EJB Client Side View ............................................................................... 281

    29.1.1. Specifying the EJB Proxy Configuration ................................................. 28429.2. The EJB Server Side View .............................................................................. 288

    29.2.1. Detached Invokers - The Transport Middlemen ...................................... 28829.2.2. The HA JRMPInvoker - Clustered RMI/JRMP Transport .......................... 29129.2.3. The HA HttpInvoker - Clustered RMI/HTTP Transport ............................. 291

    29.3. The EJB Container ......................................................................................... 29229.3.1. EJBDeployer MBean ............................................................................ 29329.3.2. Container Plug-in Framework .............................................................. 305

    29.4. Entity Bean Locking and Deadlock Detection .................................................... 31429.4.1. Why JBoss Needs Locking ................................................................... 31529.4.2. Entity Bean Lifecycle ............................................................................ 31529.4.3. Default Locking Behavior ...................................................................... 31529.4.4. Pluggable Interceptors and Locking Policy ............................................. 31629.4.5. Deadlock ............................................................................................ 31629.4.6. Advanced Configurations and Optimizations .......................................... 31829.4.7. Running Within a Cluster ...................................................................... 32029.4.8. Troubleshooting ................................................................................... 320

    29.5. EJB Timer Configuration ................................................................................. 321

    30. The CMP Engine 32330.1. Example Code ................................................................................................ 323

    30.1.1. Enabling CMP Debug Logging .............................................................. 32430.1.2. Running the examples .......................................................................... 324

    30.2. The jbosscmp-jdbc Structure ........................................................................... 32630.3. Entity Beans ................................................................................................... 327

    30.3.1. Entity Mapping ..................................................................................... 32930.4. CMP Fields .................................................................................................... 333

  • ix

    30.4.1. CMP Field Declaration ......................................................................... 33430.4.2. CMP Field Column Mapping ................................................................. 33430.4.3. Read-only Fields .................................................................................. 33630.4.4. Auditing Entity Access .......................................................................... 33630.4.5. Dependent Value Classes (DVCs) ......................................................... 338

    30.5. Container Managed Relationships .................................................................... 34130.5.1. CMR-Field Abstract Accessors .............................................................. 34230.5.2. Relationship Declaration ....................................................................... 34230.5.3. Relationship Mapping ........................................................................... 343

    30.6. Queries .......................................................................................................... 34930.6.1. Finder and select Declaration ............................................................... 34930.6.2. EJB-QL Declaration .............................................................................. 35030.6.3. Overriding the EJB-QL to SQL Mapping ................................................ 35130.6.4. JBossQL .............................................................................................. 35230.6.5. DynamicQL .......................................................................................... 35330.6.6. DeclaredSQL ....................................................................................... 35430.6.7. EJBQL 2.1 and SQL92 queries ............................................................. 35730.6.8. BMP Custom Finders ........................................................................... 358

    30.7. Optimized Loading .......................................................................................... 35830.7.1. Loading Scenario ................................................................................. 35930.7.2. Load Groups ........................................................................................ 36030.7.3. Read-ahead ......................................................................................... 360

    30.8. Loading Process ............................................................................................. 36630.8.1. Commit Options ................................................................................... 36730.8.2. Eager-loading Process ......................................................................... 36730.8.3. Lazy loading Process ........................................................................... 36830.8.4. Lazy loading result sets ........................................................................ 371

    30.9. Transactions ................................................................................................... 37230.10. Optimistic Locking ......................................................................................... 37430.11. Entity Commands and Primary Key Generation ............................................... 377

    30.11.1. Existing Entity Commands .................................................................. 37830.12. Defaults ........................................................................................................ 380

    30.12.1. A sample jbosscmp-jdbc.xml defaults declaration ................................. 38230.13. Datasource Customization ............................................................................. 383

    30.13.1. Type Mapping .................................................................................... 38430.13.2. Function Mapping ............................................................................... 38630.13.3. Mapping ............................................................................................ 38630.13.4. User Type Mappings .......................................................................... 387

    IV. Performance Tuning 389

    31. JBoss Enterprise Application Platform 5 Performance Tuning 39131.1. Introduction .................................................................................................... 39131.2. Hardware tuning ............................................................................................. 391

    31.2.1. CPU (Central Processing Unit) .............................................................. 39131.2.2. RAM (Random Access Memory) ........................................................... 39231.2.3. Hard Disk ............................................................................................ 392

    31.3. Operating System Performance Tuning ............................................................ 39231.3.1. Networking .......................................................................................... 392

    31.4. Tuning the JVM .............................................................................................. 39331.5. Tuning your applications ................................................................................. 393

    31.5.1. Instrumentation .................................................................................... 39431.6. Tuning JBoss Enterprise Application Platform ................................................... 394

    31.6.1. Memory usage ..................................................................................... 395

  • Administration And Configuration Guide

    x

    31.6.2. Database Connection ........................................................................... 39831.6.3. Clustering Tuning ................................................................................. 39831.6.4. Other key configurations ....................................................................... 402

    VI. Appendices 405

    A. Vendor-Specific Datasource Definitions 407A.1. Deployer Location and Naming ......................................................................... 407A.2. DB2 ................................................................................................................. 407A.3. Oracle ............................................................................................................. 410

    A.3.1. Changes in Oracle 10g JDBC Driver ....................................................... 412A.3.2. Type Mapping for Oracle 10g ................................................................. 412A.3.3. Retrieving the Underlying Oracle Connection Object ................................ 413A.3.4. Limitations of Oracle 11g ....................................................................... 413

    A.4. Sybase ............................................................................................................ 413A.4.1. Sybase Limitations ................................................................................ 414

    A.5. Microsoft SQL Server ....................................................................................... 415A.5.1. Microsoft JDBC Drivers .......................................................................... 416A.5.2. JSQL Drivers ........................................................................................ 417A.5.3. jTDS JDBC Driver ................................................................................. 418A.5.4. "Invalid object name 'JMS_SUBSCRIPTIONS' Exception .......................... 419

    A.6. MySQL Datasource .......................................................................................... 420A.6.1. Installing the Driver ................................................................................ 420A.6.2. MySQL Local-TX Datasource ................................................................. 420A.6.3. MySQL Using a Named Pipe ................................................................. 421

    A.7. PostgreSQL ..................................................................................................... 421A.8. Ingres .............................................................................................................. 422

    B. Logging Information and Recipes 425B.1. Log Level Descriptions ..................................................................................... 425B.2. Separate Log Files Per Application ................................................................... 425B.3. Redirecting Category Output ............................................................................. 426

    C. Revision History 429

  • xi

    Preface

    1. Document ConventionsThis manual uses several conventions to highlight certain words and phrases and draw attention tospecific pieces of information.

    In PDF and paper editions, this manual uses typefaces drawn from the Liberation Fonts1 set. TheLiberation Fonts set is also used in HTML editions if the set is installed on your system. If not,alternative but equivalent typefaces are displayed. Note: Red Hat Enterprise Linux 5 and later includesthe Liberation Fonts set by default.

    1.1. Typographic ConventionsFour typographic conventions are used to call attention to specific words and phrases. Theseconventions, and the circumstances they apply to, are as follows.

    Mono-spaced Bold

    Used to highlight system input, including shell commands, file names and paths. Also used to highlightkeycaps and key combinations. For example:

    To see the contents of the file my_next_bestselling_novel in your currentworking directory, enter the cat my_next_bestselling_novel command at theshell prompt and press Enter to execute the command.

    The above includes a file name, a shell command and a keycap, all presented in mono-spaced boldand all distinguishable thanks to context.

    Key combinations can be distinguished from keycaps by the hyphen connecting each part of a keycombination. For example:

    Press Enter to execute the command.

    Press Ctrl+Alt+F2 to switch to the first virtual terminal. Press Ctrl+Alt+F1 toreturn to your X-Windows session.

    The first paragraph highlights the particular keycap to press. The second highlights two keycombinations (each a set of three keycaps with each set pressed simultaneously).

    If source code is discussed, class names, methods, functions, variable names and returned valuesmentioned within a paragraph will be presented as above, in mono-spaced bold. For example:

    File-related classes include filesystem for file systems, file for files, and dir fordirectories. Each class has its own associated set of permissions.

    Proportional Bold

    This denotes words or phrases encountered on a system, including application names; dialog box text;labeled buttons; check-box and radio button labels; menu titles and sub-menu titles. For example:

    Choose System Preferences Mouse from the main menu bar to launch MousePreferences. In the Buttons tab, click the Left-handed mouse check box and click

    1 https://fedorahosted.org/liberation-fonts/

    https://fedorahosted.org/liberation-fonts/https://fedorahosted.org/liberation-fonts/

  • Preface

    xii

    Close to switch the primary mouse button from the left to the right (making the mousesuitable for use in the left hand).

    To insert a special character into a gedit file, choose Applications Accessories Character Map from the main menu bar. Next, choose Search Find from theCharacter Map menu bar, type the name of the character in the Search field and clickNext. The character you sought will be highlighted in the Character Table. Double-click this highlighted character to place it in the Text to copy field and then click theCopy button. Now switch back to your document and choose Edit Paste from thegedit menu bar.

    The above text includes application names; system-wide menu names and items; application-specificmenu names; and buttons and text found within a GUI interface, all presented in proportional bold andall distinguishable by context.

    Mono-spaced Bold Italic or Proportional Bold Italic

    Whether mono-spaced bold or proportional bold, the addition of italics indicates replaceable orvariable text. Italics denotes text you do not input literally or displayed text that changes depending oncircumstance. For example:

    To connect to a remote machine using ssh, type ssh [email protected] ata shell prompt. If the remote machine is example.com and your username on thatmachine is john, type ssh [email protected].

    The mount -o remount file-system command remounts the named filesystem. For example, to remount the /home file system, the command is mount -oremount /home.

    To see the version of a currently installed package, use the rpm -q packagecommand. It will return a result as follows: package-version-release.

    Note the words in bold italics above username, domain.name, file-system, package, version andrelease. Each word is a placeholder, either for text you enter when issuing a command or for textdisplayed by the system.

    Aside from standard usage for presenting the title of a work, italics denotes the first use of a new andimportant term. For example:

    Publican is a DocBook publishing system.

    1.2. Pull-quote ConventionsTerminal output and source code listings are set off visually from the surrounding text.

    Output sent to a terminal is set in mono-spaced roman and presented thus:

    books Desktop documentation drafts mss photos stuff svnbooks_tests Desktop1 downloads images notes scripts svgs

    Source-code listings are also set in mono-spaced roman but add syntax highlighting as follows:

    package org.jboss.book.jca.ex1;

    import javax.naming.InitialContext;

  • Notes and Warnings

    xiii

    public class ExClient{ public static void main(String args[]) throws Exception { InitialContext iniCtx = new InitialContext(); Object ref = iniCtx.lookup("EchoBean"); EchoHome home = (EchoHome) ref; Echo echo = home.create();

    System.out.println("Created Echo");

    System.out.println("Echo.echo('Hello') = " + echo.echo("Hello")); }}

    1.3. Notes and WarningsFinally, we use three visual styles to draw attention to information that might otherwise be overlooked.

    Note

    Notes are tips, shortcuts or alternative approaches to the task at hand. Ignoring a note shouldhave no negative consequences, but you might miss out on a trick that makes your life easier.

    Important

    Important boxes detail things that are easily missed: configuration changes that only apply tothe current session, or services that need restarting before an update will apply. Ignoring a boxlabeled 'Important' will not cause data loss but may cause irritation and frustration.

    Warning

    Warnings should not be ignored. Ignoring warnings will most likely cause data loss.

    2. Getting Help and Giving Feedback

    2.1. Do You Need Help?

    If you experience difficulty with a procedure described in this documentation, visit the Red HatCustomer Portal at http://access.redhat.com. Through the customer portal, you can:

    search or browse through a knowledgebase of technical support articles about Red Hat products.

    submit a support case to Red Hat Global Support Services (GSS).

    http://access.redhat.com

  • Preface

    xiv

    access other product documentation.

    Red Hat also hosts a large number of electronic mailing lists for discussion of Red Hat software andtechnology. You can find a list of publicly available mailing lists at https://www.redhat.com/mailman/listinfo. Click on the name of any mailing list to subscribe to that list or to access the list archives.

    2.2. Give us Feedback

    If you find a typographical error, or know how this guide can be improved, we would love to hear fromyou. Submit a report in Bugzilla against the product JBoss Enterprise Application Platform5 and the component doc-Admin_and_Config_Guide. The following link will take you to a pre-filledbug report for this product: http://bugzilla.redhat.com/2.

    Fill out the following template in Bugzilla's Description field. Be as specific as possible whendescribing the issue; this will help ensure that we can fix it quickly.

    Document URL:

    Section Number and Name:

    Describe the issue:

    Suggestions for improvement:

    Additional information:

    Be sure to give us your name so that you can receive full credit for reporting the issue.

    2 https://bugzilla.redhat.com/enter_bug.cgi?product=JBoss%20Enterprise%20Application%20Platform%205&component=doc-Admin_and_Config_Guide&version=5.1.2&short_desc=Bug%20in%20Administration%20and%20Configuration%20Guide

    https://www.redhat.com/mailman/listinfohttps://www.redhat.com/mailman/listinfohttps://bugzilla.redhat.com/enter_bug.cgi?product=JBoss%20Enterprise%20Application%20Platform%205&component=doc-Admin_and_Config_Guide&version=5.1.2&short_desc=Bug%20in%20Administration%20and%20Configuration%20Guidehttps://bugzilla.redhat.com/enter_bug.cgi?product=JBoss%20Enterprise%20Application%20Platform%205&component=doc-Admin_and_Config_Guide&version=5.1.2&short_desc=Bug%20in%20Administration%20and%20Configuration%20Guidehttps://bugzilla.redhat.com/enter_bug.cgi?product=JBoss%20Enterprise%20Application%20Platform%205&component=doc-Admin_and_Config_Guide&version=5.1.2&short_desc=Bug%20in%20Administration%20and%20Configuration%20Guide

  • xv

    What this Book CoversThe primary focus of this book is the presentation of the standard JBoss Enterprise ApplicationPlatform 5.0 architecture components from both the perspective of their configuration and architecture.As a user of a standard JBoss distribution you will be given an understanding of how to configurethe standard components. This book is not an introduction to JavaEE or how to use JavaEEin applications. It focuses on the internal details of the JBoss server architecture and how ourimplementation of a given JavaEE container can be configured and extended.

    As a JBoss developer, you will be given a good understanding of the architecture and integrationof the standard components to enable you to extend or replace the standard components for yourinfrastructure needs. We also show you how to obtain the JBoss source code, along with how to buildand debug the JBoss server.

  • xvi

  • Chapter 1.

    1

    Introduction JBoss Enterprise Application Platform 5 is built on top of the new JBoss Microcontainer. The JBossMicrocontainer is a lightweight container that supports direct deployment, configuration and lifecycleof plain old Java objects (POJOs). The JBoss Microcontainer project is standalone and replaces theJBoss JMX Microkernel used in the 4.x JBoss Enterprise Application Platforms.

    The JBoss Microcontainer integrates nicely with the JBoss Aspect Oriented Programming framework(JBoss AOP). JBoss AOP is discussed in Chapter 10, JBoss AOP Support for JMX in JBossEnterprise Application Platform 5 remains strong and MBean services written against the oldMicrokernel are expected to work.

    A sample Java EE 5 application that can be run on top of JBoss Enterprise Application Platform5.0.0.GA and above which demonstrates many interesting technologies is the Seam BookingApplication available with this distribution. This example application makes use of the followingtechnologies running on JBoss Enterprise Application Platform 5:

    EJB3

    Stateful Session Beans

    Stateless Session Beans

    JPA (w/ Hibernate validation)

    JSF

    Facelets

    Ajax4JSF

    Seam

    Many key features of JBoss Enterprise Application Platform 5 are provided by integrating standaloneJBoss projects which include:

    JBoss EJB3 included with JBoss Enterprise Application Platform 5 provides the implementationof the latest revision of the Enterprise Java Beans (EJB) specification. EJB 3.0 is a deep overhauland simplification of the EJB specification. EJB 3.0's goals are to simplify development, facilitate atest driven approach, and focus more on writing plain old java objects (POJOs) rather than codingagainst complex EJB APIs.

    JBoss Messaging is a high performance JMS provider included in JBoss Enterprise ApplicationPlatform 5 as the default messaging provider. It is also the backbone of the JBoss ESBinfrastructure. JBoss Messaging is a complete rewrite of JBossMQ, which is the default JMSprovider for JBoss Enterprise Application Platform 4.2.

    JBoss Cache comes in two flavors: a traditional tree-structured node-based cache, and aPojoCache, an in-memory, transactional, and replicated cache system that allows users to operateon simple POJOs transparently without active user management of either replication or persistencyaspects.

    JBossWS 3.x is the web services stack for JBoss Enterprise Application Platform 5 providing JavaEE compatible web services, JAXWS-2.x.

  • Chapter 1. Introduction

    2

    JBoss Transactions is the default transaction manager for JBoss Enterprise Application Platform5. JBoss Transactions is founded on industry proven technology and 18 year history as a leader indistributed transactions, and is one of the most interoperable implementations available.

    JBoss Web is the Web container in JBoss Enterprise Application Platform 5, an implementationbased on Apache Tomcat that includes the Apache Portable Runtime (APR) and Tomcat nativetechnologies to achieve scalability and performance characteristics that match and exceed theApache Http server.

    1.1. JBoss Enterprise Application Platform Use Cases 99% of web applications involving a database

    Mission critical web applications likely to be clustered.

    Simple web applications with JSPs/Servlets upgrades to JBoss Enterprise Application Platform withTomcat Embedded.

    Intermediate web applications with JSPs/Servlets using a web framework such as Struts, JavaServer Faces, Cocoon, Tapestry, Spring, Expresso, Avalon, Turbine.

    Complex web applications with JSPs/Servlets, SEAM, Enterprise Java Beans (EJB), JavaMessaging (JMS), caching etc.

    Cross application middleware (JMS, Corba, JMX etc).

  • Part I. JBoss EnterpriseApplication Platform Infrastructure

  • Chapter 2.

    5

    JBoss Enterprise Application Platform5 architecture The following diagram illustrates an overview of the JBoss Enterprise Application Server and itscomponents.

    The directory structure of JBoss Enterprise Application Platform 5 resembles that of the 4.x series withsome notable differences:

    -jboss-as - the path to your JBoss Enterprise Application Server. |-- bin - contains start scripts and run.jar |-- client - client jars |-- common/lib - static jars shared across server profile |-- docs - schemas/dtds, examples |-- lib - core bootstrap jars | lib/endorsed - added to the server JVM java.endorsed.dirs path `-- server - server profile directories. See Section 3.2 for details of the server profiles included in this release.

    -seam - the path to JBoss SEAM application framework |-- bootstrap |-- build |-- examples - examples demonstrating uses of SEAM's features |-- extras |-- lib - library directory

  • Chapter 2. JBoss Enterprise Application Platform 5 architecture

    6

    |-- seam-gen - command-line utility used to generate simple skeletal SEAM code to get your project started |-- ui -

    -resteasy - RESTEasy - a portable implementation of JSR-311 JAX-RS Specification |-- embedded-lib |-- lib |-- resteasy-jaxrs.war

    2.1. The JBoss Enterprise Application Platform Bootstrap

    The JBoss Enterprise Application Platform 5 bootstrap is similar to the JBoss Enterprise ApplicationPlatform 4.x versions in that the org.jboss.Main entry point loads an org.jboss.system.server.Serverimplementation. In JBoss Enterprise Application Platform 4.x this was a JMX based microkernel. InJBoss Enterprise Application Platform 5 this is a JBoss Microcontainer.

    The default JBoss Enterprise Application Platform 5 org.jboss.system.server.Serverimplementation is org.jboss.bootstrap.microcontainer.ServerImpl. Thisimplementation is an extension of the kernel basic bootstrap that boots the MC from the bootstrapbeans declared in {jboss.server.config.url}/bootstrap.xml descriptors using aBasicXMLDeployer. In addition, the ServerImpl registers install callbacks for any beansthat implement the org.jboss.bootstrap.spi.Bootstrap interface. The bootstrap/profile*.xml configurations include a ProfileServiceBootstrap bean that implements theBootstrap interface.

    The org.jboss.system.server.profileservice.ProfileServiceBootstrap isan implementation of the org.jboss.bootstrap.spi.Bootstrap interface that loads thedeployments associated with the current server profile. The PROFILE is the name of the server profilebeing loaded and corresponds to the server -c command line argument. The default PROFILE isdefault.

    2.2. Hot Deployment

    Hot deployment in JBoss Enterprise Application Platform 5 is controlled by the Profileimplementations associated with the ProfileService. The HDScanner bean deployed via thedeploy/hdscanner-jboss-beans.xml MC deployment, queries the profile service for changes inapplication directory contents and redeploys updated content, undeploys removed content, and addsnew deployment content to the current server profile via the ProfileService.

    If you want to disable hot deployment, temporarily or permanently, use either of the following methods.The second method is best used if you are disabling hot deployment only temporarily, since it's theeasiest to undo.

    Remove the hdscanner-jboss-beans.xml file from deployment;

    Edit the hdscanner-jboss-beans.xml file and change the scanEnabled attribute to false.

    Below is an extract of a hdscanner-jboss-beans.xml file in which hot deployment has beendisabled.

  • Hot Deployment

    7

    5000 HDScanner false

    ...(snip)...

  • 8

  • Part II. JBoss Enterprise ApplicationPlatform 5 Configuration

  • Chapter 3.

    11

    NetworkBy default, the Enterprise Platform binds to all networking addresses at start-up. You can specify abind address, as well as a UDP address, at start-up.

    Table 3.1. Network-related start-up options

    -b [IP-ADDRESS] Specifies the address the application server binds to. Ifunspecified, the application server binds to all addresses.

    -u [IP-ADDRESS] UDP multicast address. Optional. If not specified, only TCP isused.

    -m[MULTICAST_PORT_ADDRESS]

    UDP multicast port. Only used by JGroups.

    3.1. IPv6 SupportEnterprise Application Platform 5 does not include support for IPv6, although this support is plannedfor the future.

  • 12

  • Chapter 4.

    13

    Enterprise Applications with EJB3Services EJB3 (Enterprise Java Bean 3.0) provides the core component model for Java EE 5 applications. AnEJB3 bean is a managed component that is automatically wired to take advantage of all services theJava EE 5 server container provides, such as transaction, security, persistence, naming, dependencyinjection, etc. The managed component allows developers to focus on the business logic, and leavethe cross-cutting concerns to the container as configurations. As an application developer, you neednot create or destroy the components yourself. You only need to ask for an EJB3 bean from the JavaEE container by its name, and then you can call its methods with all configured container servicesapplied. You can get access to an EJB3 bean from either inside or outside of the Java EE container.

    JBoss Enterprise Application Platform 5 supports EJB3 out of the box. Note that JBoss EnterpriseApplication Platform 4.2 is a J2EE server, so it does not support the full EJB3 feature set.

    The details of the EJB3 component programming model is beyond the scope of this guide. Most EJB3interfaces and annotations are part of the Java EE 5 standard and hence they are the same for allJava EE 5 compliant application servers. Interested readers should refer to the EJB3 specification ornumerous EJB3 books to learn more about EJB3 programming.

    In this chapter, we only cover EJB3 configuration issues that are specific to the JBoss EnterpriseApplication Platform. For instance, we discuss the JNDI naming conventions for EJB3 componentsinside the JBoss Enterprise Application Platform, the optional configurations for the Hibernatepersistence engine for entity beans, as well as custom options in the JBoss EJB3 deployer.

    4.1. Session BeansSession beans are widely used to provide transactional services for local and remote clients. To writea session bean, you need an interface and an implementation class.

    @Localpublic interface MyBeanInt { public String doSomething (String para1, int para2);}

    @Statelesspublic class MyBean implements MyBeanInt {

    public String doSomething (String para1, int para2) { ... implement the logic ... } }

    When you invoke a session bean method, the method execution is automatically managed by thetransaction manager and the security manager in the server. You can specify the transactional orsecurity properties for each method using annotations on the method. A session bean instance canbe reused by many clients. Depending on whether the server maintains the bean's internal statebetween two clients, the session bean can be stateless or stateful. Depending on whether the beanhas a remote business interface clients outside of the current JVM can call upon the EJB3 bean. Allthese are configurable via standard annotations on the beans. Note that the transactional or securityproperties are only active when the bean is called through a business interface.

  • Chapter 4. Enterprise Applications with EJB3 Services

    14

    After you define a session bean, how does the client get a reference to it? As we discussed, the clientdoes not create or destroy EJB3 components, it merely asks the server for a reference of an existinginstance managed by the server. That is done via JNDI. In JBoss AS, the default local JNDI name fora session bean is dependent on the deployment packaging of the bean class.

    If the bean is deployed in a standalone JAR file in the JBOSS_DIST/default/deploy directory,the bean is accessible via local JNDI name MyBean/local, where MyBean is the implementationclass name of the bean as we showed earlier. The "local" JNDI in JBoss AS means that the JNDIname is relative to java:comp/env/.

    If the JAR file containing the bean is packaged in an EAR file, the local JNDI name for the bean ismyapp/MyBean/local, where myapp is the root name of the EAR archive file (e.g., myapp.ear,see later for the EAR packaging of EJB3 beans).

    Of course, you should change local to remote if the bean interface is annotated with @Remoteand the bean is accessed from outside of the server it is deployed on. Below is the code snippet toget a reference of the MyBean bean in a web application (e.g., in a servlet or a JSF backing bean)packaged in myapp.ear, and then invoke a managed method.

    try { InitialContext ctx = new InitialContext(); MyBeanInt bean = (MyBeanInt) ctx.lookup("myapp/MyBean/local");} catch (Exception e) { e.printStackTrace ();}

    ... ...

    String result = bean.doSomething("have fun", 1);

    ... ...

    What the client gets from the JNDI is essentially a "stub" or "proxy" of the bean instance. When theclient invokes a method, the proxy figures out how to route the request to the server and marshaltogether the response.

    If you do not like the default JNDI names, you can always specify your own JNDI binding for any beanvia the @LocalBinding annotation on the bean implementation class. The JNDI binding is always"local" under the java:comp/env/ space. For instance, the following bean class definition results inthe bean instances available under JNDI name java:comp/env/MyService/MyOwnName.

    @Stateless@LocalBinding (jndiBinding="MyService/MyOwnName")public class MyBean implements MyBeanInt {

    public String doSomething (String para1, int para2) { ... implement the logic ... } }

  • Entity Beans (a.k.a. Java Persistence API)

    15

    Injecting EJB3 Beans into the Web Tier

    Java EE 5 allows you to inject EJB3 bean instances directly into the web application viaannotations without explicit JNDI lookup. This behavior is not yet supported in JBoss EnterpriseApplication Platform 4.2. However, the JBoss Enterprise Platform provides an integrationframework called JBoss Seam. JBoss Seam brings EJB3 / JSF integration to new heights farbeyond what Java EE 5 provides. Please see more details in the JBoss Seam reference guidebundled with the platform.

    4.2. Entity Beans (a.k.a. Java Persistence API)EJB3 session beans allow you to implement data accessing business logic in transactional methods.To actually access the database, you will need EJB3 entity beans and the entity manager API. Theyare collectively called the Java Persistence API (JPA).

    EJB3 Entity Beans are Plain Old Java Objects (POJOs) that map to relational database tables. Forinstance, the following entity bean class maps to a relational table named customer. The table hasthree columns: name, age, and signupdate. Each instance of the bean corresponds to a row of data inthe table.

    @Entitypublic class Customer {

    String name;

    public String getName () { return name; } public void setName (String name) { this.name = name; } int age; public int getAge () { return age; } public void setAge (int age) { this.age = age; } Date signupdate; public Date getSignupdate () { return signupdate; } public void setSignupdate (Date signupdate) { this.signupdate = signupdate; }}

  • Chapter 4. Enterprise Applications with EJB3 Services

    16

    Besides simple data properties, the entity bean can also contain references to other entity beanswith relational mapping annotations such as @OneToOne, @OneToMany, @ManyToMany etc. Therelationships of those entity objects will be automatically set up in the database as foreign keys. Forinstance, the following example shows that each record in the Customer table has one correspondingrecord in the Account table, multiple corresponding records in the Order table, and each record in theEmployee table has multiple corresponding records in the Customer table.

    @Entitypublic class Customer {

    ... ... Account account; @OneToOne public Account getAccount () { return account; } public void setAccount (Accout account) { this.account = account; } Employee salesRep; @ManyToOne public Employee getSalesRep () { return salesRep; } public void setSalesRep (Employee salesRep) { this.salesRep = salesRep; } Vector orders; @OneToMany public Vector getOrders () { return orders; } public void setOrders (Vector orders) { this.orders = orders; }

    Using the EntityManager API, you can create, update, delete, and query entity objects. TheEntityManager transparently updates the underlying database tables in the process. You can obtain anEntityManager object in your EJB3 session bean via the @PersistenceContext annotation.

    @PersistenceContextEntityManager em;

    Customer customer = new Customer ();// populate data in customer

    // Save the newly created customer object to DBem.persist (customer);

  • The persistence.xml file

    17

    // Increase age by 1 and auto save to databasecustomer.setAge (customer.getAge() + 1);

    // delete the customer and its related objects from the DBem.remove (customer);

    // Get all customer records with age > 30 from the DBList customers = em.query ( "select c from Customer where c.age > 30");

    The detailed use of the EntityManager API is beyond the scope of this book. Interested readers shouldrefer to the JPA documentation or Hibernate EntityManager documentation.

    4.2.1. The persistence.xml fileThe EntityManager API is great, but how does the server know which database it is supposed tosave / update / query the entity objects? How do we configure the underlying object-relational-mappingengine and cache for better performance and trouble shooting? The persistence.xml file gives youcomplete flexibility to configure the EntityManager.

    The persistence.xml file is a standard configuration file in JPA. It has to be included in the META-INFdirectory inside the JAR file that contains the entity beans. The persistence.xml file must define apersistence-unit with a unique name in the current scoped classloader. The provider attribute specifiesthe underlying implementation of the JPA EntityManager. In JBoss Enterprise Application Platform,the default and only supported / recommended JPA provider is Hibernate. The jta-data-source pointsto the JNDI name of the database this persistence unit maps to. The java:/DefaultDS here points tothe HSQL DB embedded in the JBoss Enterprise Application Platform. Please refer to Chapter 14,Use Alternative Databases with JBoss Enterprise Application Platform on how to setup alternativedatabases for JBoss AS.

    org.hibernate.ejb.HibernatePersistence java:/DefaultDS ... ...

    Inject EntityManager by persistence-unit name

    Since you might have multiple instances of persistence-unit defined in the same application,you typically need to explicitly tell the @PersistenceContext annotation which unit you want toinject. For instance, @PersistenceContext(name="myapp") injects the EntityManager from thepersistence-unit named "myapp".

    However, if you deploy your EAR application in its own scoped classloader and haveonly one persistence-unit defined in the whole application, you can omit the "name" on@PersistenceContext. See later in this chapter for EAR packaging and deployment.

  • Chapter 4. Enterprise Applications with EJB3 Services

    18

    The properties element in the persistence.xml can contain any configuration properties for theunderlying persistence provider. Since JBoss Enterprise Application Platform uses Hibernate as theEJB3 persistence provider, you can pass in any Hibernate options here. Please refer to the Hibernateand Hibernate EntityManager documentation for more details. Here we will just give an example to setthe SQL dialect of the persistence engine to HSQL, and to create tables from the entity beans whenthe application starts and drop those tables when the application stops.

    org.hibernate.ejb.HibernatePersistence java:/DefaultDS property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

    4.2.2. Use Alternative DatabasesTo use an alternative database other than the built-in HSQL DB to back your entity beans, you needto first define the data source for the database and register it in the JNDI. This is done via the *-ds.xml files in the deploy directory. Examples of *-ds.xml files for various databases are available inJBOSS_DIST/docs/examples/jca directory in the server.

    Then, in the persistence.xml, you need to change the jta-data-source attribute to point to the newdata source in JNDI (e.g., java:/MysqlDS if you are using the default mysql-ds.xml to setup a MySQLexternal database).

    In most cases, Hibernate tries to automatically detect the database it connects to and thenautomatically selects an appropriate SQL dialect for the database. However, we have found that thisdetection does not always work, especially for less used database servers. We recommend you to setthe hibernate.dialect property explicitly in persistence.xml. Here are the Hibernate dialect for databaseservers officially supported on the JBoss platform.

    Oracle 9i and 10g: org.hibernate.dialect.Oracle9Dialect

    Microsoft SQL Server 2005: org.hibernate.dialect.SQLServerDialect

    PostgresSQL 8.1: org.hibernate.dialect.PostgreSQLDialect

    MySQL 5.0: org.hibernate.dialect.MySQL5Dialect

    DB2 8.0: org.hibernate.dialect.DB2Dialect

    Sybase ASE 12.5: org.hibernate.dialect.SybaseDialect

    4.2.3. Default Hibernate optionsHibernate has many configuration properties. For the properties that you do not specify in thepersistence.xml file, JBoss AS will provide a reasonable set of default values. The default Hibernateproperty values are specified in the JBOSS_DIST/server/default/deploy/ejb3.deployer/MEAT-INF/persistence.properties file. Below is the persistence.properties file bundled

  • Message Driven Beans

    19

    in JBoss AS 4.2. Notice the options that are commented out. They give you an idea of availableproperties in your persistence.xml file.

    hibernate.transaction.manager_lookup_class=org.hibernate.transaction.JBossTransactionManagerLookup#hibernate.connection.release_mode=after_statement#hibernate.transaction.flush_before_completion=false#hibernate.transaction.auto_close_session=false#hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory#hibernate.hbm2ddl.auto=create-drop#hibernate.hbm2ddl.auto=createhibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider# Clustered cache with TreeCache#hibernate.cache.provider_class=org.jboss.ejb3.entity.TreeCacheProviderHook#hibernate.treecache.mbean.object_name=jboss.cache:service=EJB3EntityTreeCache#hibernate.dialect=org.hibernate.dialect.HSQLDialecthibernate.jndi.java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryhibernate.jndi.java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaceshibernate.bytecode.use_reflection_optimizer=false# I don't think this is honored, but EJB3Deployer uses ithibernate.bytecode.provider=javassist

    4.3. Message Driven BeansMessaging driven beans are specialized EJB3 beans that receive service requests via JMSmessages instead of proxy method calls from the "stub". So, a crucial configuration parameter forthe message driven bean is to specify which JMS message queue its listens to. When there is anincoming message in the queue, the server invokes the beans's onMessage() method, and passesin the message itself for processing. The bean class specifies the JMS queue it listens to in the@MessageDriven annotation. The queue is registered under the local JNDI java:comp/env/ namespace.

    @MessageDriven(activationConfig ={ @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination", propertyValue="queue/MyQueue")})public class MyJmsBean implements MessageListener {

    public void onMessage (Message msg) { // ... do something with the msg ... }

    // ... ...}

    When a message driven bean is deployed, its incoming message queue is automatically created if itdoes not exist already. To send a message to the bean, you can use the standard JMS API.

    try { InitialContext ctx = new InitialContext(); queue = (Queue) ctx.lookup("queue/MyQueue");

  • Chapter 4. Enterprise Applications with EJB3 Services

    20

    QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory"); cnn = factory.createQueueConnection(); sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

    } catch (Exception e) { e.printStackTrace ();} TextMessage msg = sess.createTextMessage(...);

    sender = sess.createSender(queue);sender.send(msg);

    Please refer to the JMS specification or books to learn how to program in the JMS API.

    4.4. Package and Deploy EJB3 ServicesEJB3 bean classes are packaged in regular JAR files. The standard configuration files, such as ejb-jar.xml for session beans, and persistence.xml for entity beans, are in the META-INF directory insidethe JAR. You can deploy EJB3 beans as standalone services in JBoss AS or as part of an enterpriseapplication (i.e., in an EAR archive). In this section, we discuss those two deployment options.

    4.4.1. Deploy the EJB3 JARWhen you drop JAR files into the JBOSS_DIST/server/default/deploy/ directory, it will beautomatically picked up and processed by the server. All the EJB3 beans defined in the JAR filewill then be available to other applications deployed inside or outside of the server via JNDI nameslike MyBean/local, where MyBean is the implementation class name for the session bean. Thedeployment is done via the JBoss EJB3 deployer in JBOSS_DIST/server/default/ejb3.deployer/. TheMETA-INF/persistence.properties file we discussed earlier to configure the default behavior of EJB3entity manager is located in the EJB3 deployer.

    The EJB3 deployer automatically scans JARs on the classpath to look for EJB3 annotations. When itfinds classes with EJB3 annotations, it would deploy them as EJB3 services. However, scanning allJARs on the classpath could be very time-consuming if you have large applications with many JARsdeployed. In the JBOSS_DIST/server/default/ejb3.deployer/META-INF/jboss-service.xml file, youcan tell the EJB3 deployer to ignore JARs you know do not contain EJB3 beans. The non-EJB3 JARfiles shipped with the JBoss AS are already listed in the jboss.ejb3:service=JarsIgnoredForScanningMBean service:

    ... ... snmp-adaptor.jar, otherimages.jar, applet.jar, jcommon.jar, console-mgr-classes.jar, jfreechart.jar, juddi-service.jar, wsdl4j.jar, ... ... servlets-webdav.jar

  • Deploy EAR with EJB3 JAR

    21

    ... ...

    You can add any non-EJB3 JARs from your application to this list so that the server do not have towaste time scanning them. This could significantly improve the application startup time in some cases.

    4.4.2. Deploy EAR with EJB3 JARMost Java EE applications are deployed as EAR archives. An EAR archive is a JAR file that typicallycontains a WAR archive for the web pages, servlets, and other web-related components, one orseveral EJB3 JARs that provide services (e.g., data access and transaction) to the WAR components,and some other support library JARs required by the application. An EAR file also have deploymentdescriptors such as application.xml and jboss-app.xml. Below is the basic structure of a typical EARapplication.

    myapp.ear|+ META-INF |+ applications.xml and jboss-app.xml|+ myapp.war |+ web pages and JSP /JSF pages |+ WEB-INF |+ web.xml, jboss-web.xml, faces-config.xml etc. |+ lib |+ tag library JARs |+ classes |+ servlets and other classes used by web pages|+ myapp.jar |+ EJB3 bean classes |+ META-INF |+ ejb-jar.xml and persistence.xml|+ lib |+ Library JARs for the EAR

    Notice that in JBoss AS, unlike in many other application servers, you do not need to declare EJBreferences in the web.xml file in order for the components in the WAR file to access EJB3 services.You can obtain the references directly via JNDI as we discussed earlier in the chapter.

    A typical application.xml file is as follows. It declares the WAR and EJB3 JAR archives in the EAR, anddefines the web content root for the application. Of course, you can have multiple EJB3 modules in thesame EAR application. The application.xml file could also optionally define a shared classpath for JARfiles used in this application. The JAR file location defaults to lib in JBoss AS -- but it might be differentin other application servers.

    My Application

    myapp.war /myapp

    myapp.jar

  • Chapter 4. Enterprise Applications with EJB3 Services

    22

    lib

    The jboss-app.xml file provides JBoss-specific deployment configuration for the EAR application. Forinstance, it can specify the deployment order of modules in the EAR, deploy JBoss-specific applicationmodules in the EAR, such as SARs (Service ARchive for MBeans) and HARs (Hibernate ARchive forHibernate objects), provide security domain and JMX MBeans that can be used with this application,etc. You can learn more about the possible attributes in jboss-app.xml in its DTD: http://www.jboss.org/j2ee/dtd/jboss-app_4_2.dtd.

    A common use case for jboss-app.xml is to configure whether this EAR file should be deployed in itsown scoped classloader to avoid naming conflicts with other applications. If your EAR application isdeployed in its own scoped classloader and it only has one persistence-unit defined in its EJB3 JARs,you will be able to use @PersistenceContext EntityManager to inject EntityManager to session beanswithout worrying about passing the persistence unit name to the @PersistenceContext annotation.The following jboss-app.xml specifies a scoped classloader myapp:archive=myapp.ear for the EARapplication.

    myapp:archive=myapp.ear

    The EAR deployment is configured by the JBOSS_DIST/server/default/deploy/ear-deploy.xml file. Thisfile contains three attributes as follows.

    false false true

  • Deploy EAR with EJB3 JAR

    23

    If you set the Isolated parameter to true, all EAR deployment will have scoped classloaders bydefault. There will be no need to define the classloader in jboss-app.xml. The CallByValue attributespecifies whether we should treat all EJB calls as remote calls. Remote calls have a large additionalperformance penalty compared with local call-by-reference calls, because objects involved in remotecalls have to be serialized and de-serialized. For most of our applications, the WAR and EJB3 JARsare deployed on the same server, hence this value should be default to false and the server uses localcall-by-reference calls to invoke EJB methods in the same JVM. The EnablelibDirectoryByDefaultattribute specifies whether the lib directory in the EAR archive should be the default location for sharedlibrary JARs.

  • 24

  • Chapter 5.

    25

    LoggingLogging is the most important tool to troubleshoot errors and monitor the status of the components ofthe Platform. log4j provides a familiar, flexible framework, familiar to Java developers.

    Section 5.1, Logging Defaults contains information about customizing the default logging behaviorfor the Platform. See Section 5.2, Component-Specific Logging for additional customization.Appendix B, Logging Information and Recipes provides some logging recipes, which you cancustomize to your needs.

    5.1. Logging DefaultsThe log4j configuration is loaded from the $JBOSS_HOME/server/PROFILE/conf/jboss-log4j.xml deployment descriptor. log4j uses appenders to control its logging behavior. An appenderis a directive for where to log information, and how to do it. The jboss-log4j.xml file containsmany sample appenders, including FILE, CONSOLE, and SMTP.

    Table 5.1. Common log4j Configuration DirectivesConfiguration Option Description

    appender The main appender. Gives the name and theimplementing class.

    errorHandler Delegates an external class to handle exceptionspassed to the logger, especially if the appendercannot write the log for some reason.

    param Options specific to the type of appender. In thisinstance, the is the name of the file thatstores the logs for the FILE appender.

    layout Controls the logging format. Tweak this to workwith your log-parsing software of choice.

    Example 5.1. Sample Appender

    For more information on configuring log4j, see http://logging.apache.org/log4j/1.2/.

    http://logging.apache.org/log4j/1.2/

  • Chapter 5. Logging

    26

    5.2. Component-Specific LoggingSome Platform components have extra logging options available, or extra mechanisms for customizinglogging.

    5.2.1. SQL Logging with HibernateHibernate has two ways to enable logging of SQL statements. These statements are most usefuld