JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1....

24
JBoss in Action 1. Introduction An application server is a place to run your Java code. JEMS = JBoss Enterprise Middleware Suite. Deploying the application: copy the war file to jboss-as-web-7\standalone\deployments. 2. Managing the JBoss Application Server JBoss uses a micro-container that enables services to be written as POJO instead of MBeans. The JBoss micro-container is a dependency injection framework like Spring. The server/xxx/conf/profile.xml is used to configure the micro-container. An MBean is an interface with the name XxxxMBean and an implementing class with the name Xxxx. Once an instance is created, it can be registered by name with the MBean Server. Once registered, any JMX client can request information about the MBean and can make requests to it, but only through the MBean server. An MBean name is composed of a domain and one or more key properties: jboss.jca:service=ManagedConnectionPool,name=DefaultDS Version 7: cf. ...\standalone\configuration\standalone.xml The JMX Console is a web application that can read, display and update MBeans. To access to JMX Console: http://localhost:8080/jmx-console Twiddle is a command-line tool that has the same power than the JMX Console. Most interesting MBeans: jboss:type=Service,name=SystemProperties View the system properties jboss:service=JNDIView View the contents of JNDI jboss.system:type=Log4jService,service=Logging Change logging system jboss.system:service=ThreadPool Change the thread pool size jboss.system:type=Server Info about the server

Transcript of JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1....

Page 1: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

JBoss in Action

1. IntroductionAn application server is a place to run your Java code.

JEMS = JBoss Enterprise Middleware Suite.

Deploying the application: copy the war file to jboss-as-web-7\standalone\deployments.

2. Managing the JBoss Application ServerJBoss uses a micro-container that enables services to be written as POJO instead of MBeans. The JBoss micro-container is a dependency injection framework like Spring.

The server/xxx/conf/profile.xml is used to configure the micro-container.

An MBean is an interface with the name XxxxMBean and an implementing class with the name Xxxx. Once an instance is created, it can be registered by name with the MBean Server. Once registered, any JMX client can request information about the MBean and can make requests to it, but only through the MBean server.

An MBean name is composed of a domain and one or more key properties:

jboss.jca:service=ManagedConnectionPool,name=DefaultDSVersion 7: cf. ...\standalone\configuration\standalone.xml

The JMX Console is a web application that can read, display and update MBeans. To access to JMX Console: http://localhost:8080/jmx-consoleTwiddle is a command-line tool that has the same power than the JMX Console.

Most interesting MBeans:

jboss:type=Service,name=SystemProperties View the system propertiesjboss:service=JNDIView View the contents of JNDIjboss.system:type=Log4jService,service=Logging Change logging systemjboss.system:service=ThreadPool Change the thread pool sizejboss.system:type=Server Info about the server

Page 2: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

3. Deploying Application

Application Type Primary Descriptor

WAR WEB-INF/web.xmlEAR META-INF/application.xmlSAR META-INF/jboss-service.xmlJAR META-INF/ejb-jar.xmlRAR META-INF/ra.xml

RAR: defines a resource adaptor to connect to an EIS (Enterprise Information System) using the JCA (Java Connector Architecture).

Class Loaders

The application server uses multiple class loaders.

1. Lowest level: classes in the class path, including rt.jar

2. Medium level: jar files in the server lib directory

3. High level: class in the WAR file

Common Deployment Errors

1. Class Not Found Exceptions

2. Duplicate JAR file errors

3. Zip file errors

4. Class Cast Exceptions

Data Sources

To deploy a data source to the application server, create a *-ds.xml file (cf. /jboss-ds_5_0.dtd)

1. local-tx-datasource: data source with transaction, but not among multiple servers

2. no-tx-datasource: data source with no transaction

3. xa-datasource: data source with distributed transactions among multiple servers

A Hibernate archive (*.har) is a convenience if several applications access the same data using Hibern-ate.

Page 3: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

4. Securing ApplicationsJBoss SX is JBoss AS’s security implementation. It has different login modules that can read security in-formation from different locations (DB, LDAP…). It is built on top of JAAS.

Context-base security: applying security based on information in the request (involves writing code).

Security Domain: an abstraction used to secure all requests made to a component; configured at the server level and bound into JNDI. You can add or modify existing security domain definitions within the server/xxx/conf/login-config.xml file.

<application-policy name="jmx-console"><authentication><login-module code = “org.jboss.security.auth.spi.UsersRolesLoginModule"> <module-option name="usersProperties">props/jmx-console-users.properties </module-option> <module-option name="rolesProperties">props/jmx-console-roles.properties </module-option></login-module></authentication></application-policy>

Application-policy: binds the security domain into JNDI. JNDI context associated would be java:/jaas/jmx-console. All security domains are bound to java:/jaas.

Login-module: JBoss SX module that support different backend data sources. Ex: org.jboss.security.auth.spi.UsersRolesLoginModule loads security info from properties files on the system.

BaseCertLoginModule Authenticates client certificates. Must be stacked with another login module that does authorization.

CertRolesLoginModule An extension of BaseCertLoginModule that authenticates against client certificates and authorizes against properties files.

ClientLoginModule Used by standalone clients that want to log into a secure server.

DatabaseCertLoginModule An extension of BaseCertLoginModule that authenticates against client certificates and authorizes against a database.

DatabaseServerLoginModule Loads user/role information from a database.

UsersRolesLoginModule Loads user/role information from properties files.

Dynamic login configuration: to define security in the application archive rather than in the server’s lo-gin-config file. Only in an EAR file (not a WAR file).

More logging: -Djavax.net.debug=ssl

Page 4: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

Confidentiality: protecting a message from being read by anybody else than the recipients

Integrity: Data: the message wasn’t tampered with; Source: guarantees the sender

Many secure protocols (such as SSL) use public key encryption to establish a secret key when two users first negotiate a conversation, and then they use the secret key to continue the communication using symmetric encryption.

Truststore: a keystore file that contains public key certificates. To specify the truststore: java -Djavax.net.ssl.trustStore=<f> -Djavax.net.ssl.trustStorePassword=<p>

Page 5: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

5. Configuring JBoss Web ServerStandard deployment descriptor: web.xml (contains logical elements)

Proprietary deployment descriptors: jboss-web.xml, context.xml (contains physical elements)

All descriptors must reside in the WEB-INF directory.

jboss-web.xml:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE jboss-web PUBLIC .../jboss-web_4_0.dtd"><jboss-web> <security-domain>java:/jaas/ppoWSADRealm</security-domain> <context-root>ppo-web</context-root></jboss-web>security-domain Specifies which security domain the application uses

for authentication and authorization.context-root Defines the root URL mapped to this application when

HTTP requests come inresource-env-ref Maps the Enterprise Naming Context (ENC) name for a

resourceenv-ref defined in the web.xmlresource-ref Maps the Enterprise Naming Context (ENC) name for a

resource-ref defined in the web.xml

Context.xml: only useful for Tomcat valves.

Key configuration files

• deploy/jboss.sar/server.xml: Primary server configuration file. Used to configure server components such as virtual hosts, protocols, ports, and request filters.

• deploy/jbossweb.sar/context.xml: Global version of the application-level file by the same name.

• deploy/jbossweb.sar/jsf-libs: Contains libraries necessary for JSF development.

• deployers/jbossweb.deployer/META-INF/war-deployers-jboss-beans.xml: Micro-container configuration file. Used to initialize the WAR deployer.

AJP protocol: a TCP/IP-based binary protocol created for Tomcat as an alternative to sending HTTP mes-sages to a web container (Apache JServer Protocol).

war-deployers-jboss-beans.xml: server configuration elements

Virtual host: mechanism to segment the web container to expose some applications to some domains.

To change the context path:<jboss-web>

Page 6: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

<context-root>/bpj</context-root></jboss-web>Connectors: used to bind to particular ports and listen for traffic over particular protocols. They are de-signed to handle concurrent connections from multiple browsers.

Valves: intercepts requests into the server. AccessLogValve: to log requests.

Page 7: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

6. Securing Web Applications

WEB-INF/web.xml • The authentication strategy (BASIC, FORM, DIGEST, or CLIENT-CERT)

• Which URL patterns should be restricted to which logical roles

• A set of logical rolesWEB-INF/jboss-web.xml The JNDI name for the security domain that the web

application should use

/jbossweb.sar/server.xml • The secure HTTP connector (SSL port, keystore file, and so on)

• The portion of the certificate compared during CLIENT-CERT authentication

/conf /login-config.xml • The definition for security domains• The login module that the security domain

should use

Web.xml

<web-app>…<security-constraint>(0..*)

<web-resource-collection>(1..*)<web-resource-name>Some Resource</web-resource-name><url-pattern>/*</url-pattern><url-pattern>/shoppingcart/*</url-pattern><http-method>GET</http-method><http-method>POST</http-method>

</web-resource-collection><auth-constraint>(0..1)

<role-name>SomeSimpleRole</role-name></auth-constraint><user-data-constraint>(0..1)

<transport-guarantee>CONFIDENTIAL

</transport-guarantee></user-data-constraint>

</security-constraint><login-config>(*)

<auth-method>BASIC</auth-method></login-config><security-role>(*)

<role-name>SomeSimpleRole</role-name></security-role>…

</web-app>

Page 8: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

1. Define URLs to secure (URL-pattern)

2. Define authorized roles (role-name) – roles are also defined in <security-role>

3. Define authentication strategies in <login-config>

What to do => job of web.xml <> How to do it => job of login-config.xml.jboss-web.xml:<jboss-web> <security-domain>java:/jaas/some-domain</security-domain></jboss-web>

login-config.xml:<application-policy name="some-domain"> ...</application-policy>

server.xml:<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/.keystore"keystorePass="rmi+ssl" sslProtocol = "TLS" />

<Realm className="org.jboss.web.tomcat.security.JBossWebRealm"certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"allRolesMode="authOnly" />

Authentication Strategies: (cf. <login-config> in web.xml)

• HTTP Basic Authentication (BASIC) – modal dialog box

• Form-based authentication (FORM) – login form

• Digest Authentication (DIGEST) – modal dialog box with hashed password

Page 9: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

• Client-Certificate Authentication (CLIENT-CERT) – if the client has a public key certificate

Note: user’s password is vulnerable to interception because the password is not encrypted.

Digest Authentication

The password is not sent over the network in clear text, but the client uses MD5 to hash it in a string known as a digest. It uses a session token to make replay attacks difficult. Not considered strong encryp-tion.

Allow access to any authenticated user (all roles)<auth-constraint>

<role-name>*</role-name></auth-constraint>Transport Guarantee

Mechanism that allows a process to be accessed only securely (HTTP is redirected towards HTTPS).<transport-guarantee>

CONFIDENTIAL</transport-guarantee>

Page 10: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

7. Configuring Enterprise ApplicationsRunning in an application server allows you to focus on developing components that contain business logic, while plugging into services that are already available.

JPA = Java Persistence API, implemented by Hibernate.

The persistence context manages entities and lifecycles. It is managed by the container and accessible through an entity manager.

EAR: deployment descriptors: application.xml (standard) and jboss-app.xml (proprietary). The application.xml file is responsible for defining the archives that are part of the EAR and providing any additional information about them. The jboss-app.xml is used to configure class loading or deploy jboss-specific modules.

application.xml: (in EAR/META-INF)

<application><display-name>Some Enterprise Archive</display-name><module>

<web><web-uri>SomeEnterpriseArchive.war</web-uri><context-root>/myapp</context-root>

</web></module><module>

<ejb>SomeEnterpriseArchive.jar</ejb></module>

</application>jboss-app.xml: (in EAR/META-INF)

<jboss-app><module>

<service>...</service></module>

</jboss-app>

Annotations

@EJB: inject a EJB.

@Entity: defines an entity

@GeneratedValue: the primary key should be auto-generated

@Id: defines the primary key

@PersistenceContext: defines an EntityManager variable (cf. persistence.xml file)

@Remote: defines a remote interface

Page 11: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

@PersistenceUnit: defines an EntityManagerFactory object.

@Stateless: defines a session-less session bean

Three deployment descriptors under META-INF: ejb-jar.xml; jboss.xml; persistence.xml

ejb-jar.xml: (in META-INF)

Standard deployment descriptor used to configure session and message-driven beans.

<ejb-jar><description>Some JBoss Application</description><display-name>Some App</display-name><enterprise-beans>

<session> ... </session><message-driven> ... </message-driven>

</enterprise-beans><assembly-descriptor>

<security-role> ... </security-role><method-permission> ... </method-permission><container-transaction> ... </container-transaction><exclude-list> ... </exclude-list>

</assembly-descriptor></ejb-jar>

persistence.xml: (in META-INF)

Standard deployment descriptor used to configure a JPA persistence context. The persistence context is used by the entity manager to access entity objects (read/write).

<persistence><persistence-unit name="greeter">

<provider>org.hibernate.ejb.HibernatePersistence</provider><jta-data-source>java:/DefaultDS</jta-data-source><properties>

<property name="hibernate.dialect" value="..."/></properties>

</persistence-unit></persistence>DefautDS: default data source (JNDI name)

jboss.xml: (in META-INF)

Proprietary deployment descriptor used to configure EJBs. Structure similar to ejb-jar.xml.

<jboss xmlns="..." ... version="3.0"><security-domain>jbia-domain</security-domain><enterprise-beans>

Page 12: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

<session><ejb-name>ShoppingCart</ejb-name><jndi-name>ShoppingCart</jndi-name><clustered>true</clustered><cluster-config>

<partition-name>DefaultPartition</partition-name><load-balance-policy>....RandomRobin</load-balance-policy>

</cluster-config><security-domain>overridden-domain</security-domain>

</session><session>

<ejb-name>StatelessTest</ejb-name><jndi-name>StatelessTest</jndi-name><local-jndi-name>LocalName</local-jndi-name>

</session></enterprise-beans></jboss>

JNDI

JNDI provides a uniform way for both local and remote application components to look up references to dynamic proxies for the EJB they need to call. As EJBs are deployed into the server, the server automatically creates the domain proxy for the EJB and binds it into the JNDI server.

By default, the server uses for the JNDI name the name of the bean itself.

@LocalBinding: change the local JNDI binding name

@RemoteBinding: change the remote JNDI binding name

Looking up a session bean

MyBeanbean = (MyBean)ctx.lookup(“SomeBean/remote”);MyBeanbean = (MyBean)ctx.lookup(“SomeBean/local”);

standardjboss.xml: (in server/default/conf)

Global version of the proprietary deployment descriptor jboss.xml – applies to all EJB applications deployed to the server. That file contains two main blocks: one for the dynamic proxies, and one for the containers.

<jboss><invoker-proxy-bindings>

<invoker-proxy-binding>...</invoker-proxy-binding></invoker-proxy-bindings>

Page 13: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

<container-configurations><container-configuration>

<container-name>...</container-name><container-interceptors>...</container-interceptors><persistence-manager>...</persistence-manager><container-cache-conf>....</container-cache-conf><container-pool-conf>...</container-pool-conf>

</container-configuration></container-configurations>

</jboss>

JMX

JMX Service objects: special type of SFSB, but singletons.

@Management: defines a management interface for a service object.

@Service: defines a service object (with the objectName attribute).

Security

@SecurityDomain (“simple-security-domain”): defined at the class level

@RolesAllowed ({“bank-manager”, “teller”}); @PermitAll; @DenyAll: defines method-level authorization on the EJB.It is possible to define method-level security in the ejb-jar.xml file.

Page 14: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

8. JBoss MessagingMOM = Message Oriented Middleware (like IBM’s MQ Series)

JSR-914 defined a standard API for messaging: JMS API.

Two message system architectures:

1. Centralized (with a messaging server)

2. Decentralized (the message components communicate among themselves.

Two messaging models: point-to-point and publish-and-subscribe

1. P2P: a sender places messages in a queue, and from there it’s delivered to one receiver.

2. PAS: a publisher places messages in a topic, from where they are sent to subscribers.

A message is composed of a header, of properties and of a payload.

Properties: JMS-defined (JMSX_...), vendor-specific (JMS_XXX_...), application-specific

Payload types: Message, BytesMessage, MapMessage, ObjectMessage, StreamMessage, TextMessage

Message Drive Beans

@MessageDriven: declares this class to be a MDB

@ActivationConfigurationProperty: set properties to govern the handling of messages

• destinationType: javax.jms.Topic• destination: topc/testDurableTopic

Page 15: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

• subscriptionDurability: Durable• messageSelector: SpudsCustomer=’Natalie’

Message Drive POJO

There are POJOs that can be registered as message consumers. MD POJOs are specific to JBOSS AS.

Configuring JBoss Messaging

1. Configuring a data source (*-ds.xml file)<datasources>

<local-tx-datasource><jndi-name>jdbc/VideoDS</jndi-name><connection-url>jdbc:postgresql:… </connection-url><driver-class>org.postgresql.Driver</driver-class><user-name>video</user-name><password>videopw</password>...

</local-tx-datasource></datasources>

2. Modify the persistence service descriptor (*-service.xml)

3. Populate the DB with usernames and passwords

4. Configure the login module (login-config.xml)

5. Configure the messaging service (messaging-jboss-beans.xml)

6. Configure destinations (default file: destinations-service.xml)

Page 16: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

9. Configuring Web ServicesRMI isn’t usually possible because the firewalls block the ports used for RMI. HTTP port 80 and 443 are usually open.

List of endpoints: http://127.0.0.1:8080/jbossws/services

• Web Service: Collection of end-points that contains web methods

• WSDL: XML document that describes the web service

• UDDI: mechanism used to publish Web Services

• Top-down approach: first the WSDL, then the code (use wsconsume)

• Bottom-up approach: first the classes, then the WSDL (use wsprovide)

• @WebService: defines the Web Service

• @WebMethod: defines the Web Method

• @WebContext: defines items normally declared in web.xml

• @EndpointConfig: used to identify the configuration to use with the endpoint

• Security: there is a security realm (JBossWS) defined in login-config.xml

Page 17: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

10. JBoss PortalPortals enable you to build websites by putting together disparate pieces of code, called portlets, into a single page, making those separate applications appear to function as one.

JSR-168: portlet specification

• Portal: a collection of pages that contain portlet windows

• Page: a view into the portal, containing multiple portlet windows

• Portlet window: a view into a portlet instance

• Portlet instance: an instantiation of a portlet

• Portlet: a piece of code that defines what a user can see or do

Package: javax.porlet in portal-portlet-jsr168api-lib.jar file.

public class ImagePortlet extends javax.portlet.GenericPortlet {public void init(PortletConfig cfg) throws PortletException {

super.init(cfg);jspView = cfg.getInitParameter("jsp-view");

}

// VIEW modeprotected void doView(request, response) {

response.set...PorletRequestDispatcher prd = f(jspView);prd.include(request, response);

}

// HELP modeprotected void doHelp(request, response){

PorletRequestDispatcher prd = f(jspHelp);prd.include(request, response);

}

// EDIT modeprotected void doEdit(request, response){

PortletURL action = response.createActionURL();action.setPortletMode(PortletMode.VIEW);PorletRequestDispatcher prd = f(jspEdit);prd.include(request, response);

}

Page 18: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

// Allow the portlet to process an action requestpublic void processAction(request, response){

String value = request.getParameter("value");PorletPreferences pref = request.getPreferences();pref.setValue("value", value);

}}

Portlet Descriptor

portlet.xml

<portlet-app xmlns=...><portlet>

<portlet-name>...</portlet-name><display-name>...</display-name><init-param>

<name>...</name><value>...</value>

</init-param><supports>

<mime-type>text/html</mime-type><portlet-mode>...</portlet-mode>

</supports><resource-bundle>...</resource-bundle><portlet-info>...</portlet-info><portlet-preferences>

<name>...</name><value>...</value>

</portlet-preferences></portlet>

</portlet-app>

jboss-app.xml

<jboss-app><app-name>image</app-name>

</jboss-app>

portlet-instances.xml: identifies one or more instances of a portlet

*-object.xml: defines portlet windows that display portlet instances.

11. Configuring JBoss PortalTwo basic renderers defined for a portlet: DIV and EMPTY. The whole portal can be customized. The portal ships with a basic CMS used to display static data.

Page 19: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

12. Understanding ClusteringClustering is the act of running the same application on multiple application server instances simultaneously with each application server being aware of the others in the cluster.

Each node in the cluster must be able to communicate with each other in order to make something useful, such as replicating state or providing failover capabilities.

Load Balancing

It is a way of balancing incoming load, or concurrent requests, across multiple application server instances, making the application scalable and highly available. Scalability is the ability to make the application handle more user load. Availability is the ability to continue processing requests in the face of server failure.

The load balancer acts as a single point of entry into an application environment, as well as a traffic director for requests. This isn’t a feature of the application or the application server and does not require a cluster.

Two types: hardware load balancer (more expensive and reliable), software balancers.

Load balancers make a single IP address for a cluster visible to clients. It maintains a map of internal IP addresses for each machine in the cluster. When it receives a request, it rewrites the header to point to a particular machine in the cluster.

Server affinity: capacity to route subsequent request from a client to the same server.

Most common strategies: random, round robin, sticky session.

Topology: horizontal (nodes of clusters are on different machines) or vertical (nodes are on the same machine). Horizontal clusters provide more scalability and fault-tolerance. JBoss Automatic discovery allows cluster nodes to discover each other without configuration.

Homogenous cluster: all nodes have the same applications deployed on them <> Heterogeneous cluster.

JGroups: tool to enable peer-to-peer communication between nodes, to transmit reliable multicast communication.

High availability: 5 “nine” = available 99.999% of the time = 5.3 minutes down per year. Load balancing provides high availability when there is no server’s state (no session) because it does not matter if requests from the same client go to different servers.

Stateful architectures can achieve high availability by providing a mechanism for failover. To be fault tolerant, state associated with an application must be redundantly available. A copy of the data must be available outside of the node by which it’s owned (= state replication).

Total state replication: each node has to keep its own state as well as the state from all other nodes <> Buddy replication: the state is replicated across only a subset of nodes in a cluster.

Page 20: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

Distribution vs. Clustering: Distribution is the act of separating logically distinct application components onto physically separate machines (multiple machines to run a single application). Clustering is the act of running the same application on multiple machines simultaneously. Distribution is more complicated and less performant than collocating all the application layers on the same server.

JBoss Cache: A distributed cache built on top of JGroups, for SFSB, entities, HTTP sessions, JNDI objects.

Page 21: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

13. Clustering JBoss AS ServicesLoad balancing does not require a cluster, unless you want to be fault-tolerant with a Stateful application.

AJP: TCP-base binary protocol made for communicating with application servers.

HTTP Load Balancing

1. Load balancing with native web servers

2. Load balancing with hardware

HTTP Session replication

To enable your web application to use session replication, add the distributable element to the applica-tion’s web.xml file.<web-app>

<distributable/></web-app>Replication trigger options: SET, SET_AND_GET, SET_AND_NON_PRIMITIVE_GET, ACCESS

Clustering session beans

@Clusteredpublic class SomeBean implements SomeBusinessInterface {}

Clustering entity beans

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)public class Category implements Serializable {}Clustering JNDI

HA-JNDI: High Availability JNDI Service that runs on top of the existing JNDI infrastructure.

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.provider.url=192.168.1.140:1099

Context ctx = new InitialContext();

Multiples nodes

java.naming.provier.url=192.168.1.140:1100,192.168.1.141:1100, 192.168.1.148:1100

Page 22: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

14. Tuning the JBoss Application Server• Response time: how quickly the system responds to a user’s request

• Processing time: amount of time the system computes the response

• Round trip response time: includes the network latency

• Throughput: number of requests the system can handle within a given time period

• SLA: a contract to provide a certain level of service

• Scaling: refers to how additional load can be added

• Analyze cycle: run, analyze, tune.

• Make one change at the time.

• Max memory assignable: often 1.4 GB

• CPU: usage should be between 50 and 80%

• Processor affinity: mechanism to limit the processors on which a given process runs. An applica-tion server does not scale well above than 4 processors.

• Use a later version of the JVM, and the –client or –server command line arguments.

• Heap = young generation (for new objects) and tenured generation (for objects that survived the GC).

• Set the options using the JAVA_OPTS environment variable. Advice: set young genera-tion-to-heap-ratio = 1/3.

set JAVA_OPTS=%JAVA_OPTS% -Xms1200m –Xmx1200m –XX:NewSize=400M –XX:MaxNewSize=400M –XX:SurvivorRatio=32 –XX:+UseTLAB –XX:TLABSize=64K

• Connection pool: When a data source is deployed, the application server creates three MBeans, one of which manages the connection pool. This MBean is named Jboss.jca:name=<dsname>,service=ManagedConnectionPool

• It is possible to modify the number of threads available to process requests (in server.xml)

• Thread dump generation on Windows: CTRL + BREAK

• JConsole: start the server with -Dcom.sun.management.jmxremote

Page 23: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

15. Going to Production• Do not run the same server configuration twice.

• Modify ports in bindings-jboss-beans.xml.

• Defining virtual IP addresses: cf. p420

• It is possible to limit access to services to the local machine

• Changing the default database:

o Create a new db

o Create a data source descriptor file (*-ds.xml)

o Name the dew data source DefaultDS, or modify the configuration files to reference the new data source.

o Remove hsqldb-ds.xml• Disable the lazy compilation of the JSP pages

Page 24: JBoss in Action - Scarlethome.scarlet.be/bernard.jorion5/it/books/jboss-in-action.pdf · 1. local-tx-datasource: data source with transaction, but not among multiple servers 2. no-tx-datasource:

A. JNDI NamespacesThe Java EE specification provides a mechanism for logically referencing beans, EJB, and resources using the Environment Naming Context (ENC). The ENC is a private JNDI namespace available to EJB, and is mapped to the application server’s proprietary namespace, using the server descriptor file (META-INF/jboss.xml).

Data Source

<web-app>... <resource-ref>

<res-ref-name>jdbc/DataSourceName</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth><res-sharing-scope>Shareable</res-sharing-scope>

</resource-ref>...

</web-app>The java:comp/env portion of the name is implied and doesn’t need to be included.

Mapping to JBoss default data source:

<jboss-web>...<resource-ref>

<res-ref-name>jdbc/DataSourceName</res-ref-name><jndi-name>java:DefaultDS</jndi-name>

</resource-ref>...

<jboss-web>

cf. http://127.0.0.1:8080/jmx-console/