Java EE 6 specifications

As mentioned earlier, Oracle WebLogic 12c supports Java EE 6, which supports a lot of new features. Some of these features are discussed here.

Contexts and Dependency Injection for Java EE (JSR 299)

This specification is a generic dependency injection with automatic context management. It's an integral part of Java EE 6 and provides an architecture that allows Java EE components such as servlets, enterprise beans, and JavaBeans to exist within the lifecycle of an application with well-defined scopes. In addition, CDI services allow Java EE components such as EJB session beans and JSF-managed beans to be injected and to interact by firing and observing events. When you specify this option, it generates beans.xml in the WEB-INF folder of your application. The beans.xml file is used by CDI to instruct the Oracle WebLogic Server that the project is a module containing CDI beans.

When the application is deployed, it knows there is a beans.xml file, so the classes on the path are scanned for CDI annotations.

You now can create a ManagedBean and add a stateless annotation for a simple EJB.

In the following example you can see how the inject class is being used:

package demo;
import javax.inject.Named;
@Named
public class MessageServerBean {
public String getMessage() {
return "Hello World!";
}
}

And with this, you can add MessageServerBean in a facelet as follows:

<h:body>
Hello from Packt
<br/>
Message is: #{messageServerBean.message}
<br/>
Message Server Bean is: #{messageServerBean}
</h:body>

Another example being used within the WebLogic Server is the Resource Adapters Bean discovery. This discovery detects if a Resource Archive (RAR) is a bean archive. WebLogic will then treat all JAR files inside the RAR as bean archives, and even overrules the META-INF/beans.xml files in this case. The bean archive descriptor indicates that a specific RAR is a bean archive.

Some components that support CDI within RARs are as follows:

  • ResourceAdapter bean — RAclass that uses the javax.resource.spi.ResourceAdapter interface, with operations for life cycle management and message endpoint setup
  • ManagedConnectionFactory bean — The JavaBean class that uses the javax.resource.spi.ManagedConnectionFactory interface and is a factory of both ManagedConnection and EIS-specific connection factory instances
  • ActivationSpec bean — The JavaBean class that uses the javax.resource.spi.ActivationSpec interface contains the activation config info for a message endpoint
  • Admin objects — Set of classes that represents objects specific to a messaging style or message provider

The following steps explain how an injection does its work for a resource adapter like the DBAdapter:

  1. It initializes the RA component bean configuration properties from deployment descriptors.
  2. Then the PostConstruct annotation after dependency injection is done to perform any initialization.
  3. Performs bean validation and invokes the validate() method.
  4. For an RA bean, invokes the start() method.
  5. Makes all resource adapter component beans available either by binding them to JNDI or exposing them to endpoint applications.

Java Server Faces (JSF) 2

As you all Java developers probably know, JavaServer Faces is a web-based framework in the presentation layer that provides a subset of components for graphical user interface, which binds user interface components according to an event-driven model to objects.

JSF is a standard user interface (UI) framework for developing Java EE web applications. It contains a default set of UI components, custom tag libraries for adding UI components to a view, a server-side event model, and managed beans (state management).

JSF 2 is already supported from WebLogic 10.3.3. In a typical WebLogic Server installation, you will find the supported JAR files under the WLS Server Home, in the directory common/deployable-libraries/jsf-2.0.war.

The JSF 2.0 shared library follows the same model as the previous JSF libraries shipped with WLS, where it needs to be deployed and referenced using a library ref; in a WLS deployment descriptor by applications that wish to use it.

The JSF 2.0 library supports Dependency Injection of Java EE resources and the use of the Java EE 5 lifecycle annotations in managed beans as described in the specification. This is done through the inclusion of a WLS-specific class that implements the com.sun.faces.spi.InjectionProvider interface provided in the WEB-INF/lib/wls.jsf.di.jar library within the jsf-2.0.war shared library.

Some new features in JSF 2 are:

  • Enables JSF views in XML: In this feature, the JSP document file can be treated as facelet file
  • Pluggable Facelet Cache mechanism: In JSF 2.1.2, the in-memory cache of the Facelet instance is served from a cache that is overridden with an implementation in this API
  • System events
  • Enhanced navigation
  • GET support
  • Bean validation
  • Proper error handling
  • Project stages
  • First class JavaScript and Ajax support
  • Component behaviors
  • Resource handling
  • Delta state saving
  • Tree visiting
  • Annotation-based configuration
  • Content Dependency Injection support

Beware, when using JSF 2.1 in your WebLogic Server, it requires at least a Servlet 3.0 container.

The JSF implementation has been added directly to the WebLogic Server classpath. This is a change from the WebLogic Server 11g release. In this change, the JSF implementation was provided as an optional shared library, which needed to be deployed in order for the applications to use JSF. With WebLogic Server 12c, JSF is now an integral part of the server and can be used without the necessity of deploying and referencing the shared library.

Even with the new JSF 2, WebLogic 12c supports the older JSF 1.2 and JSTL 1.1 packages. They are bundled with WebLogic Server as shared libraries, though they are deprecated in this release. Existing web applications that use JSF 1.2 and JSTL 1.1 functionality can run on WebLogic Server. Choose the appropriate JSF or JSTL library based on your application.

In this release, the weblogic.xml file in jsf-1.2.war configures a filtering class loader for your application's JSF classes and resources. Do not forget to make a library reference in weblogic.xml in your application.

Enterprise Java Beans 3.1

EJBs are managed beans with additional services like transactions. They provide distributable and deployable business services to clients

The purpose of EJB 3.1 along with its JSR 318 specification was to simplify the development and implementation of EJB. This simplification will hit two key areas: development and packaging. This goal matches exactly with the new Java EE 6 because of these features, ease of development, ease of use, and lightweighted.

  • Singleton beans with concurrency control: Singleton sessions have the ability to share application session state between multiple instances of an EJB. A singleton bean bounds a session bean once per application in a particular JVM, for the life cycle of the application. It can be useful to employ a scheme in which a single shared instance is used for all clients. And new to the EJB 3.1 Specification is the singleton session bean to fit this requirement. The following diagram explains how clients can use the singleton bean to share the state of a counter service. A stateless singleton bean can be called from a Java client, with the count being consistently incremented.
    Enterprise Java Beans 3.1
  • Cron-style declarative and programmatic Timers: When you have some knowledge of UNIX or Linux, you probably know the meaning of cron. It's a scheduler from which you can schedule an action at any time and as often as you wish.

    Already in 3.0 there was a timer scheduler, this is enhanced in 3.1.

    The most important one in this set of enhancements is the ability to declaratively create cron-like schedules to trigger EJB methods.

    The following is an example of such a scheduler:

    @Stateless public class ReleaseDateCounterBean implements ReleaseDateCounter{ @Schedule(second="0", minute="0", hour="0", dayOfMonth="1", month="*", year="*") public void generateMonthlyNewsLetter() { ... Still .. days to go before this book is published... } }
    

    Look at the typical cron-style here:

    @Schedule(expression="0 0 0 1 * * *")
    
  • Simplified WAR packaging: Now another interesting feature is that you can package your EJB as part of WAR. EJBs can be directly dropped into the WEB-INF/classes directory and deployed as part of the WAR. In a similar vein, the ejb-jar.xml deployment descriptor, if you happen to be using one, can be placed into the WEB-INF directory along with the web.xml file. It may also be possible to place an EJB JAR into the WEB-INF/lib directory.

    The following diagram shows the simplified packaging schedule:

    Enterprise Java Beans 3.1
  • Portable global JNDI names: For standardizing access to EJB applications, portal global JNDI has been introduced.

    EJB components can be registered and looked up from using the following pattern:

    java:global[/<app-name>]/<module-name>/<bean-name>
    

    This can be important when EJBs are accessed locally but are deployed in a WebLogic cluster. The JNDI can be accessed from every cluster member using the standardized global application's name. A client running in the same Managed Server Instance as a bean instance uses the same API to access the bean as a client running in a different Managed Server Instance on the same or different machine.

  • Startup/shutdown callbacks: Singleton beans also provide a way for EJBs to receive callbacks during application initialization or shutdown. By default, the container decides when to instantiate the singleton instance. However, you can force the container to instantiate the singleton instance during application initialization by using the @Startup annotation. This gives the bean permission to define a @PostConstruct method to be called at startup time. At last, any @PreDestroy method for a singleton is guaranteed to be called when the application is shutting down.

    In a WebLogic cluster, you can create the singleton service. And also specify your application's class.

    Enterprise Java Beans 3.1
  • EJB Lite — a standard lightweight subset of the EJB API: EJB Lite is, in fact, as the name suggests, EJB with some disabled features as much as possible. On one hand, this allows for very simple, lightweight implementations. On the other hand, this means learning EJB Lite could consist of leaning just a small handful of annotations and almost no configuration. The next generation of lightweight Java EE application servers will probably implement EJB Lite instead of the entire EJB 3.1 specification.

    The following is the current list of features supported for EJB Lite:

    • Stateless, stateful, and singleton session beans
    • Only local EJB interfaces or no interfaces
    • Interceptors
    • Declarative security
    • Declarative and programmatic transactions
  • Embeddable EJB: An API for executing EJB components within Java SE.

    The following options are also included in the EJB 3.1 specification:

    • Embedded Containers/Testing support
    • Calendar-based timer expressions
    • Asynchronous bean invocation

Next we will discuss some of the additional options in WebLogic 12c.

Admin console support for EJBs in a WAR

As you can see in the following screenshot, WAR and EJB are combined into one module instead of a separate one. In this case, it's easier to administer the application because everything is in one place now.

Admin console support for EJBs in a WAR

EJB 3.1 annotation support

The annotated bean is, in fact, the control center of your EJB. It contains the Java code about how your EJB behaves. It is a Java class file that takes care of implementing the business logic and methods of your EJB. You are able to annotate this bean file with metadata from the JDK to make a specification of shape and characteristics of the EJB, and define services as enhanced business-level security or special business logic during runtime.

Simplified deployment with annotation support

EJB 3.1 provides a dramatically simpler deployment with support for deployment inside a WAR file. A class with a component-defining annotation becomes an enterprise bean component when packaged within WEB-INF/classes or as .jar in WEB-INF/lib. Enterprise beans may also be defined using a WEB-INF/ejb-jar.xml file. Beans packaged in .war share a single namespace, and become part of the WAR's environment. Packaging a JAR in WEB-INF/lib is thus semantically equivalent to putting the classes in WEB-INF/classes.

To provide a simple compile, build, and deploy, you could make use of the weblogic.appc class. This is not a new feature, but I want to mention this tool because you can use it to be able to quickly and easily build and compile your EAR files.

The appc tool offers you the flexibility of compiling an entire application, instead of compiling segments. WebLogic Server has access to all modules during the EAR compilation. If an error occurs while running appc from the command line, appc exits with an error message. By running appc prior to deployment, you potentially reduce the number of times a bean is compiled.

After setting the right environment variables on your WebLogic Server, using setDomainEnv or setWLSEnv you can run the following command:

java weblogic.appc [options]

Else create an ant task to use it in ant.

ant task weblogic.ant.taskdefs.j2ee.Appc
<project basedir="." default="appc" name="appc">
<property environment="env"/>
<property name="wl.home" value="/app/wlserver_12.1"/>
<property name="application.dir" value="/home/weblogic/workspace/wls12 c /testWeb/WebContent" />
<echo message="${wl.home}/server/lib"/>
<path id="wlappc.classpath">
<fileset dir="${wl.home}/server/lib">
<include name="*.jar"/>
</fileset>
</path>
<echo message="${toString:wlappc.classpath}"/>
<taskdef name="wlappc" classpathref="wlappc.classpath" classname="weblogic.ant.taskdefs.j2ee.Appc"/>
<target name="appc">
<wlappc source="${application.dir}"
keepgenerated="true"
verbose="true"/>
</target>
</project>

Now you can run the appc tool from the command line.

java weblogic.appc -verbose -keepgenerated .
[JspcInvoker]Checking web app for compliance.
[jspc] Overriding descriptor option 'keepgenerated' with value specified on command-line 'true'
[jspc] -webapp specified, searching . for JSPs
[jspc] Compiling /index.jsp
<Jan 29 4, 2012 4:38:03 PM CET> <Info> <J2EE> <BEA-160220> <Compilation completed successfully>

Bean Validation 1.0 (JSR 303)

Working along with other Java specifications such as Context Dependency Injector or Java Persistence API is Bean Validation.

Although it came out under Java EE 6, it does not need Java EE 6 to function.

Bean Validation defines a metadata model and API for the JavaBean validation. The metadata source is annotations, with the ability to override and extend the metadata through the use of XML validation descriptors.

Within managed beans in JSF applications, WebLogic Server does support the use of dependency injection,. The simplest way to get it to work is to use the documented mechanism of deploying. WebLogic Server supplies the JSF shared library, with the specific implementation of the com.sun.faces.spi.InjectionProvider. The InjectionProvider implementation is automatically configured on the web container.

The new EE managed beans specification defines a base component model for Java EE, together with a very basic set of container services (@Resource, @PostConstruct, @PreDestroy).

The idea is that other specifications (beginning with EJB, CDI, JSF, and the new Java Interceptors spec) build upon this base-component model and layer additional services, for example, transaction management, type-safe dependency injection, interceptors. So at this level, the managed beans, CDI, interceptors, and EJB specifications all work hand-in-hand and are highly complementary.

Now, the managed beans specification is quite open-ended with respect to identifying exactly which classes are managed beans. It does provide the @ManagedBean annotation as one mechanism, but it also allows other specifications to define different mechanisms.

Java Persistence API (JPA) 2

The framework for managing relational data in applications is, as you might know, called Java Persistence API or better JPA.

The following features can be expected within JPA 2.0:

  • Improved Object/Relational mapping
  • Type-safe criteria API
  • Expanded and richer JPQL
  • second-level cache
  • New locking modes:
    • PESSIMISTIC_READ — grabs shared lock
    • PESSIMISTIC_WRITE — grabs exclusive lock
    • PESSIMISTIC_FORCE_INCREMENT — updates version
  • Standard configuration options
  • Even the JDBC driver has a JPA interface. You can use this option in your JDBC connection specifications:
    javax.persistence.jdbc.[driver | url | user | password]
    

    See the following example:

    <property name="javax.persistence.jdbc.url" value="jdbc:oracle://localhost:3306/test2" />
    <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
    <property name="javax.persistence.jdbc.user" value="test" />
    <property name="javax.persistence.jdbc.password" value="test />
    

Some of the Java EE 6 specification are already supported in WebLogic 11g. JPA 2.0 is one of them. Though version 1.0 was the default 2.0 also worked.

Unless an explicit<provider>...</provider> is specified in the persistence.xml file of a deployed application, WebLogic 11g uses OpenJPA/Kodo by default. The default JPA provider setting is exposed via a new MBean: JPAMBean on the DomainMBean, and persists the configuration into the config.xml file.

Furthermore, you needed to install the patch QWG8 - Enable JPA 2.0 support on WebLogic Server.

To make it work on 11g, you had to use Oracle TopLink as the persistency provider as shown in the following screenshot:

Java Persistence API (JPA) 2

Also specify the provider in the<provider> element for a persistence unit in the persistence.xml file, for example:

<persistence-unit name="example">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
...
</persistence-unit>

Now for WebLogic 12c, of course, JPA 2.0 is the default.

A very interesting feature to use is WebLogic Server with TopLink Grid, using JPA with Coherence as Level 2 Cache.

The following diagram explains how JPA works in an application:

Java Persistence API (JPA) 2

In this traditional way, no caching has taken place. With the use of JPA with coherence (for more details about Coherence, refer to Chapter 6, Oracle WebLogic 12c to the Cloud: Exalogic) you introduce a robust and high performing caching mechanism.

The use of a shared cache (L2) cache can improve application throughput.

TopLink Grid combines the simplicity of application development using the Java standard Java Persistence API (JPA).

EclipseLink JPA applications are using Coherence as a shared (L2) cache replacement along with configuration for more advanced usage. L2 caching is a sort of CPU caching of multicore processors, and this technique is being used by Coherence.

This following diagram shows you a basic example of JPA using caching mechanism:

Java Persistence API (JPA) 2

Servlets 3.0

Java servlets, are components that execute on the server, accepting client requests and generating dynamic responses, and building dynamic content for web-based applications unlike some previous releases of the specification, which were just maintenance releases. The Servlet 3.0 specification is packed with lots of exciting features required for the new era of web development. The new specification focuses on delivering the following new features:

  • Ease of development
  • Pluggability and extensibility
  • Asynchronous support with Asynchronous Servlets@WebServlet(asyncSupported=true)
  • Security enhancements
  • Other miscellaneous changes
  • @WebServlet, @WebListener, @WebFilter
  • Plugin libraries using web fragments
  • Dynamic registration of Servlets
  • WEB-INF/lib/[*.jar]/META-INF/resources accessible in the root
  • Programmatic authentication login/logout
  • Default error page

It is quite evident that servlets have enjoyed much wider use than any other technology in the Java Enterprise Edition family. The beauty of servlets remains in their simplicity and ability to process HTTP requests and pass the response back to web clients. Servlets can be used for implementing business logic of simple and small applications. In the case of web frameworks, servlets serve as an entry point (a controller servlet) for all incoming requests. Consequently, all popular frameworks are built on top of raw servlets. The new features in Servlet 3.0 are aimed at easing the development of servlet applications and will benefit both servlet developers and framework developers. In the following sections, let us look into each of these features in detail and see how we can utilize them for developing better applications.

Java API for RESTful Web Services (JSR 311)

RESTful Web Services, as you all might know do not need any additional messaging layer to transfer its data over an interface like HTTP, other than SOAP. It has a built-in set of rules from which you can create stateless services, to be viewed as resources. They can be identified by a unique URI.

Some of the changes that are made in Java EE 6 are:

  • Web services through REST instead of SOAP
  • REST counterpart of JAX-WS
  • Gets rid of low-level code so you can focus on core logic
  • Annotations from the ground-up
  • Integrated with CDI and EJB

Other than 11g, 12c supports RESTful Web Service Development on WebLogic Server. It supports Jersey 1.9 JAX-RS Reference Implementation (RI), which is a production quality implementation of the JSR-311 JAX-RS 1.1 specification.

JAX-RS can also be integrated with EJB Technology and CDI:

@Stateless
@Path("/webservices")
public class PacktPublisherBean {
@PersistenceContext
private EntityManager entityManager;
@PUT
@Path("/packt/{publisher}")
public void packtPublisher(
@PathParam("publisher")
String publisher,
@QueryParam("book")
String book,
@QueryParam("title")
Double bookPrice) {
entityManager.persist(
new Bid(publisher, book, bookPrice));
}
}

Java EE Connector Architecture 1.6

As known, JCA contains resource adapters which are software components that allow Java EE application components to access and interact with the underlying resource manager of the EIS.

WebLogic Server supports several ease-of-development and ease-of-configuration features introduced in the Java EE Connector Architecture version 1.6, including the following:

  • Metadata annotations — use the annotations in resource adapter class files. Annotations can specify deployment information, eliminating the need to create the ra.xml deployment descriptor file manually.
  • Dynamic configuration properties that can be defined on ResourceAdapter, ManagedConnectionFactory, and Admin Object beans.
  • The ability to specify, at runtime, the transaction support a resource adapter can provide

Deprecated APIs

The following interfaces are no longer supported in Java EE 6 and are deprecated:

  • JAX-RPC: This interface was previously superseded by JAX-WS, although still used in Java EE 5
  • EJB 2.x Entity Beans CMP: Dropped in as an offer for JPA
  • JAXR: UDDI not well used
  • Java EE Application Deployment (JSR-88): Development specification provided poor support
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.125