Friday, January 08, 2010

How to get the JNDI of EJB in WebLogic 10g R3

If you want to the EJB accessible from general classes instead of managed beans, you have to let it can be searchable in JNDI tree. But you can not get the JNDI if you didn't set the mappedName in WebLogic 10g R3.

A sample:

@Stateless ( name="UserBean", mappedName="ejb.User")
public class UserBean implements UserLocal, UserRemote {
}


After you deployed it in Webglogic 10, you can get access to the remote interface with:

String JNDI_NAME = "ejb.User#" + UserRemote.class.getName();
UserRemote user = (UserRemote) new InitialContext().lookup(JNDI_NAME);

New features in JEE 6

JEE 6 new features:
profiles, pruning, and extensibility
Enterprise JavaBeans (EJB), Java Servlet, and Java Persistence API (JPA)
new APIs/technologies: Java API for RESTful Web Services (JAX-RS) and Java Contexts and Dependency Injection (JCDI/Web Beans)

  • Extensibility: This mechanism provides a way to include additional technologies and frameworks that are not part of the standard platform.

  • Profiles: This build on the standard Java EE platform technologies, sometimes using only a subset of those technologies, and sometimes adding Java technologies that are not part of the standard platform.

  • Pruning: Pruning provides a way to remove some technologies from the platform.


  • Enterprise JavaBeans 3.1
  • Removal of local business interface: EJB 3.0 removed the complex home and remote interfaces and made way for the plain old Java interface (POJI). EJB 3.1 goes one step further by dictating that business interfaces also are not mandatory.


  • @Stateless
    public class StockQuoteBean {...}

  • Introduction of Singleton beans: The concept of Singleton beans was introduced primarily to share application-wide data and support concurrent access. All Singleton beans are transactional and thread safe by default, making way for flexible concurrency options. Java EE 6 also introduces concurrency annotations to perform locked read/write operations on getter and setter methods.


  • @Singleton
    @Startup
    public class CounterBean {
    private int count;
    @PostConstruct
    public void initialize() {
    count=5;
    }
    }

  • Packaging EJB components directly in a WAR file: One of the major advancements in EJB 3.1 is the option for including EJB in a WAR file directly instead of creating a separate JAR file.

  • Embeddable API for executing EJB in Java SE environment: The idea behind this feature is to allow EJBs to run in Java SE environments; that is, the client and the EJB run in the same JVM. The javax.ejb.EJBContainer class represents an embeddable container. Embeddable containers support EJB Lite.

  • Asynchronous Session Bean: A session bean can support asynchronous method invocations. Bean methods annotated with @Asynchronous are invoked asynchronously. Asynchronous methods can return a Future object of the java.util.concurrent API. This will be useful for the client to get the status of the invocation, retrieve the return value of a method, check for an exception, or even cancel the invocation.

  • EJB Lite: The concept of profiles is applied to the EJB specification as well. Many enterprise applications do not require the complete set of features in EJB, so EJB Lite, a minimal subset of the EJB API, is introduced in EJB 3.1. EJB Lite provides vendors the option to implement a subset of the EJB APIs within their products. Applications created with EJB Lite can be deployed on any server that supports EJB technology, irrespective of whether it is full EJB or EJB Lite.


  • EJB Lite has the following subset of the EJB API:
    * Session bean components (Stateless, stateful, singleton session beans)
    * Supports only synchronous invocation
    * Container-managed and bean-managed transactions
    * Declarative and programmatic security
    * Interceptors
    * Support for deployment descriptor (ejb-jar.xml)



    Servlet 3.0 will introduce are:
  • Support for Annotations: Instead of making an entry in a deployment descriptor (web.xml), developers can use annotations to mark a servlet.

  • @WebServlet is used to mark a class that extends HttpServlet as a servlet.
    @WebFilter is used to mark a class that implements Filter as a filter
    @WebInitParam is used to specify an init parameter
    @WebListener is used to specify a listener

    @WebServlet("/stockquote")
    public class StockQuoteServlet extends HttpServlet {...}

    @WebServlet(name="StockQuoteServlet", urlPatterns={"/stockquote","/getQuote"})
    public class StockQuoteServlet extends HttpServlet {...}

    @WebFilter("/login")
    public class LoginFilter implements Filter {...}

  • Web fragments: Web fragments are meant to provide modularity. They provide logical partitioning of the deployment descriptor web.xml so that frameworks such as Struts and JavaServer Faces (JSF) can have their own piece of information added in the JAR file, and the developer doesn't have to edit web.xml.

    Web fragments are identified by using web-fragment as the root element. Developers can use all the elements in the deployment descriptor. The only condition is that the root element must be and hence have the name web-fragment.xml. This element is typically placed in the WEB-INF\lib folder. Any JAR file placed in the WEB-INF\lib folder can include the web fragment.

    When an application has multiple web fragments, the order of execution can be resolved using absolute ordering or relative ordering. In both cases, XML tags are used to identify the order. Absolute ordering is specified using in web.xml and relative ordering is specified using in web-fragment.xml.

    When the element is not mentioned or set to false in the deployment descriptor, the container skips processing web.xml and processes annotations and web fragments. If is set to true, then the container skips processing annotations and web fragments and processes based on the information available in web.xml, because this takes precedence.

  • Asynchronous processing: Servlets allow asynchronous processing in Java EE 6 to support AJAX. A servlet often has to wait for a response from a resource such as a database or a message connection. Asynchronous processing avoids the blocking request so that the thread can return and perform some other operation. Developers can mark servlets as asynchronous by setting the value true to the asyncSupported attribute of the @WebServlet or @WebFilter annotation. In addition to the annotation, some new APIs such as AsyncContext have been introduced, and methods such as startAsync have been added to the ServletRequest and ServletResponse classes.


  • JAX-RS 1.1 and JCDI 1.0
  • JAX-RS fully supports REST principles, and provides POJO resources to which developers can add annotations to make them support REST. Due to the nature of HTTP, JAX-RS supports only stateless interactions. Sun provides a reference implementation for JAX-RS codenamed Jersey.

  • JCDI allows developers to bind Java EE components to lifecycle contexts, to inject these components, and to enable them to support loosely coupled communication.
  • Contexts and Dependency Injection for Java EE (CDI) - Part 1

    (See details: http://www.theserverside.com/tt/articles/content/DependencyInjectioninJavaEE6/article.html)
    Contexts and Dependency Injection for Java EE (CDI) - JSR 299.
    Leader: Gavin King

    CDI is the de-facto API for comprehensive next-generation type-safe dependency injection for Java EE, which aims to synthesize the best-of-breed dependency injection features from solutions like Seam, Guice and Spring while adding many useful innovations of its own.

    Java EE 5
    What you can do is:
  • Injecting container resources such as JMS connection factories, data sources, queues, JPA entity managers, entity manager factories and EJBs via the @Resource, @PersistenceContext, @PersistenceUnit and @EJB annotations into Servlets, JSF backing beans and other EJBs.


  • What you could not is:
  • Injecting EJBs into Struts Actions or JUnit tests and you could not inject DAOs or helper classes that were not written as EJBs because they do not necessarily need to be transactional.

  • More broadly, it was difficult to integrate third-party/in-house APIs or use Java EE 5 as a basis to build such APIs that are not just strictly business components.


  • CDI is designed to solve in a highly type-safe, consistent and portable way that fits the Java philosophy well.

    Comparison with existing technologies.
  • Spring IoC - CDI is likely to feel more type-safe, futuristic and annotation-driven.

  • Seam - CDI has a lot more advanced features.

  • Guice - CDI is perhaps more geared towards enterprise development than it.


  • CDI enhances the Java EE programming model in two more important ways - both of which come from Seam.
  • First, it allows you to use EJBs directly as JSF backing beans.

  • Second, CDI allows you to manage the scope, state, life-cycle and context for objects in a much more declarative fashion, rather than the programmatic way most web-oriented frameworks handle managing objects in the request, session and application scopes.


  • CDI has no component model of its own but is really a set of services that are consumed by Java EE components such as managed beans, Servlets and EJBs.

    Managed beans are a key concept introduced in Java EE 6 to solve some of the limitations when using Java EE 5 style resource injection.

    A managed bean is just a bare Java object in a Java EE environment. Other than Java object semantics, it has a well-defined create/destroy life-cycle that you can get callbacks for via the @PostConstruct and @PreDestroy annotations. Managed beans can be explicitly denoted via the @ManagedBean annotation, but this IS NOT ALWAYS needed, especially with CDI. From a CDI perspective, this means that almost any Java object can be treated as managed beans and so can be full participants in dependency injection.

    Traditional JSF backing beans are now managed beans.
    All EJB session beans are now also redefined to be managed beans with additional services (thread-safety and transactions by default).

    Servlets are NOT yet redefined to be managed beans.

    CDI also integrates with JSF via EL bean name resolution from view technologies like Facelets and JSP as well as automatic scope management.

    CDI's integration with JPA consists of honoring the @PersistenceContext and @PersistenceUnit injection annotations, in addition to @EJB and @Resource.

    Note
    CDI DOES NOT directly support business component services such as transactions, security, remoting, messaging and the like that are in the scope of the EJB specification.

    JSR 299 utilizes the Dependency Injection for Java (JSR 330) specification as its foundational API, primarily by using JSR 330 annotations such as @Inject, @Qualifier and @ScopeType. Led by Rod Johnson and Bob Lee, JSR 330 defines a minimalistic API for dependency injection solutions and is primarily geared towards non-Java EE environments.

    CDI essentially adapts JSR 330 for Java EE environments while also adding a number of additional features useful for enterprise applications.



    Dependency Injection Basics


    @Stateless
    public class BidService {
    @Inject
    private BidDao bidDao;

    public void addBid (Bid bid) {
    bidDao.addBid(bid);
    }
    }

    public class DefaultBidDao implements BidDao {
    @PersistenceContext
    private EntityManager entityManager;

    public void addBid (Bid bid) {
    entityManager.persist(bid);
    }
    }

    public interface BidDao {
    public void addBid (Bid bid);
    }


    The bid DAO managed bean is being injected into the bid service EJB session bean via the @Inject annotation. CDI resolves the dependency by looking for any class that implement the BidDao interface. When CDI finds the DefaultBidDao implementation, it instantiates it, resolves any dependencies it has (like the JPA entity manager injected via @PersistenceContext) and injects it into the EJB bid service. Since no explicit bean scope is specified for either the service or the DAO, they are assumed to be in the implicit dependent scope.

    Qualifiers are additional pieces of meta-data that narrow down a particular class when more than one candidate for injection exists.

    @Stateless
    public class BidService {
    @Inject @JdbcDao
    private BidDao bidDao;
    ...
    }

    @JdbcDao
    public class LegacyBidDao implements BidDao {
    @Resource(name="jdbc/ActionBazaarDB")
    private DataSource dataSource;
    ...
    }


    Context Management Basics

    Every object managed by CDI has a well-defined scope and life-cycle that is bound to a specific context. As CDI encounters a request to inject/access an object, it looks to retrieve it from the context matching the scope declared for the object. If the object is not already in the context, CDI will get reference to it and put it into the context as it passes the reference to the target. When the scope corresponding to the context expires, all objects in the context are removed.

    Available Scope Definition
    Dependent, ApplicationScoped, RequestScoped, SessionScoped, ConversationScoped

    Besides the built-in scopes above, it is also possible to create custom scopes via the @Scope annotation

    @Named
    @RequestScoped
    public class BidManager {
    @Inject
    private BidService bidService;
    ...
    }

    @Stateless
    public class BidService {
    @Inject
    private BidDao bidDao;

    @Inject
    private BiddingRules biddingRules;
    ...
    }

    @ApplicationScoped
    public class DefaultBiddingRules implements BiddingRules {
    ...
    }


    @Named annotation makes the bid manager accessible from EL.



    JSR 330 defines a minimalistic API for dependency injection solutions and is primarily geared towards non-Java EE environments. In particular, it does not define scope types common in server-side Java such as request, session and conversation. It also does not define specific integration semantics with Java EE APIs like JPA, EJB and JSF.

    Thursday, January 07, 2010

    Performance monitoring for web applications

    MessAdmin is a light-weight and non-intrusive tool for monitoring and interacting with Java HttpSession. MessAdmin can be added to any J2EE application, with zero change to the monitored application!


    ZK's performance meter utility provides developers with the means to determine execution times in different stages of an Ajax request and response cycle.
    Sam Chuang illustrates his implementation of a ZK performance monitor here: http://docs.zkoss.org/wiki/A_ZK_Performance_Monitor.

    What Is The Relation Between JSR-299 and JSR-330 In Java EE 6?

    http://java.dzone.com/articles/what-relation-betwe-there

    JSR-330 (Dependency Injection for Java) led by Rod Johnson (SpringSource) and Bob Lee (Google Inc.) became a part of Java EE 6. JSR-330 is very simplistic. It comes with own few annotations from the package: javax.inject. The package contains the following elements: Inject, Qualifier, Scope, Singleton, Named and Provider. Its the definition of the basic dependency injection semantics.

    JSR-299 (Java Contexts and Dependency Injection), with Gavin King as lead, uses JSR-330 as base and enhances it significantly with modularization, cross cutting aspects (decorators, interceptors), custom scopes, or type safe injection capabilities. JSR-299 is layered on top of JSR-330.

    It is amusing to see that the built-in qualifier @Named is not recommended and should be used only for integration with legacy code:

    "The use of @Named as an injection point qualifier is not recommended, except in the case of integration with legacy code that uses string-based names to identify beans."
    [3.11 The qualifier @Named at injection points, JSR-299 Spec, Page 32]

    The relation between JSR-299 and JSR-330 is comparable to the relation between JPA and JDBC. JPA uses internally JDBC, but you can still use JDBC without JPA. In Java EE 6 you can just use JSR-330 for basic stuff, and enhance it on demand with JSR-299. There is almost no overlap in the practice. You can even mix JSR-299 / JSR-330 with EJB 3.1 - to streamline your application.