SlideShare uma empresa Scribd logo
1 de 87
Jagadish Ramu
                     Sun Microsystems
Java EE 6 - Deep Dive




                                1
The following/preceding is intended to outline our
general product direction. It is intended for
information purposes only, and may not be
incorporated into any contract. It is not a
commitment to deliver any material, code, or
functionality, and should not be relied upon in
making purchasing decisions.
The development, release, and timing of any
features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.



                                                     2
Compatible Java EE 6 Impls

Today:




Announced:
                             3
Goals for the Java EE 6
    Platform
   Flexible & Light-weight
        Web Profile 1.0
        Pruning: JAX-RPC, EJB 2.x Entity Beans, JAXR, JSR 88
   Extensible
        • Embrace Open Source Frameworks

   Easier to use, develop on
        • Continue on path set by Java EE 5


                                                           4
Java EE 6 Web Profile 1.0
   Fully functional mid-sized profile
    • Actively discussed in the Java EE 6 Expert
      Group and outside it
    • Technologies
      • Servlets 3.0, JSP 2.2, EL 2.2, Debugging Support for Other
        Languages 1.0, JSTL 1.2, JSF 2.0, Common Annotations
        1.1, EJB 3.1 Lite, JTA 1.1, JPA 2.0, Bean Validation 1.0,
        Managed Beans 1.0, Interceptors 1.1, Context &
        Dependency Injection 1.0, Dependency Injection for
        Java 1.0



                                                                     5
Java EE 6 - Done




                    09
   Specifications approved by the JCP
   Reference Implementation is GlassFish v3




                 20
   TCK
           ec
          D

                                          6
Java EE 6 Specifications
   The Platform
   Java EE 6 Web Profile 1.0
   Managed Beans 1.0




                                7
Java EE 6 Specifications
    New

   Contexts and Dependency Injection for
    Java EE (JSR 299)
   Bean Validation 1.0 (JSR 303)
   Java API for RESTful Web Services (JSR 311)
   Dependency Injection for Java (JSR 330)




                                              8
Java EE 6 Specifications
    Extreme Makeover

   Java Server Faces 2.0 (JSR 314)
   Java Servlets 3.0 (JSR 315)
   Java Persistence 2.0 (JSR 317)
   Enterprise Java Beans 3.1 & Interceptors 1.1
    (JSR 318)
   Java EE Connector Architecture 1.6 (JSR 322)


                                            9
Java EE 6 Specifications
     Updates
   Java API for XML-based Web Services 2.2 (JSR 224)
   Java API for XML Binding 2.2 (JSR 222)
   Web Services Metadata MR3 (JSR 181)
   JSP 2.2/EL 2.2 (JSR 245)
   Web Services for Java EE 1.3 (JSR 109)
   Common Annotations 1.1 (JSR 250)
   Java Authorization Contract for Containers 1.3 (JSR 115)
   Java Authentication Service Provider Interface for
    Containers 1.0 (JSR 196)
                                                         10
Servlets in Java EE 5
   At least 2 files
<!--Deployment descriptor     /* Code in Java Class */
  web.xml -->
                              package com.sun;
<web-app>                     public class MyServlet extends
  <servlet>                   HttpServlet {
    <servlet-name>MyServlet   public void
                              doGet(HttpServletRequest
       </servlet-name>
                              req,HttpServletResponse res)
       <servlet-class>
         com.sun.MyServlet    {
       </servlet-class>       ...
  </servlet>
  <servlet-mapping>           }
    <servlet-name>MyServlet
       </servlet-name>        ...
    <url-pattern>/myApp/*
       </url-pattern>         }
  </servlet-mapping>
   ...
</web-app>
                                                         11
Servlets 3.0 (JSR 315)
     Annotations-based @WebServlet

package com.sun;
@WebServlet(name=”MyServlet”, urlPatterns={”/myApp/*”})
public class MyServlet extends HttpServlet {
      public void doGet(HttpServletRequest req,
                         HttpServletResponse res)
                          <!--Deployment descriptor web.xml -->
   {
            ...           <web-app>
                             <servlet>
   }                           <servlet-name>MyServlet</servlet-name>

                                                      <servlet-class>
                                                        com.sun.MyServlet
                                                      </servlet-class>
                                                 </servlet>
                                                 <servlet-mapping>
                                                   <servlet-name>MyServlet</servlet-name>
                                                   <url-pattern>/myApp/*</url-pattern>
                                                 </servlet-mapping>
                                                  ...
                                               </web-app>

http://blogs.sun.com/arungupta/entry/totd_81_getting_started_with
                                                                                            12
Servlets 3.0
    Annotations-based @WebServlet

@WebServlet(name="mytest",
       urlPatterns={"/myurl"},
     initParams={
       @WebInitParam(name="n1",
value="v1"),
       @WebInitParam(name="n2", value="v2")

       }
)
public class TestServlet extends
       javax.servlet.http.HttpServlet {
           ....                           13

}
Servlets 3.0
Annotations-based @WebListeners
<listener>
   <listener-class>
      server.LoginServletListener
   </listener-class>
</listener>



package server;

. . .

@WebListener()
public class LoginServletListener implements
ServletContextListener {

                                               14
Servlets 3.0
      Annotations-based @WebFilter
                                <filter>
                                    <filter-name>PaymentFilter</filter-name>
                                    <filter-class>server.PaymentFilter</filter-class>
                                    <init-param>
                                         <param-name>param1</param-name>
                                         <param-value>value1</param-value>
package server;                     </init-param>
. . .                           </filter>
@WebFilter(                     <filter-mapping>
                                    <filter-name>PaymentFilter</filter-name>
  filterName="PaymentFilter",       <url-pattern>/*</url-pattern>
  InitParams={                  </filter-mapping>
    @WebInitParam(              <filter-mapping>
                                    <filter-name>PaymentFilter</filter-name>
       name="param1",               <servlet-name>PaymentServlet</servlet-name>
       value="value1")              <dispatcher>REQUEST</dispatcher>
    }                           </filter-mapping>
  urlPatterns={"/*"},
  servletNames={"PaymentServlet"},
  dispatcherTypes={DispatcherType.REQUEST}
)
public class PaymentFilter implements Filter {
. . .

                                                                            15
Servlets 3.0
     Asynchronous Servlets

     Useful for Comet, long waits
     Must declare
      @WebServlet(asyncSupported=true)
AsyncContext context = request.startAsync();
context.addListener(new AsyncListener() { … });
context.dispatch(“/request.jsp”);
//context.start(Runnable action);
...
context.complete(); //marks completion
                                                                                 16
 http://blogs.sun.com/arungupta/entry/totd_139_asynchronous_request_processing
Servlets 3.0
    Extensibility

   Plugin libraries using web fragments
        Modular web.xml
   Bundled in framework JAR file in META-INF
    directory
   Zero-configuration, drag-and-drop for web
    frameworks
    • Servlets, servlet filters, context listeners for a
      framework get discovered and registered by the
      container
   Only JAR files in WEB-INF/lib are used                 17
Servlets 3.0
       Extensibility


<web-fragment>
    <filter>
          <filter-name>wicket.helloworld</filter-name>
          <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
          <init-param>
               <param-name>applicationClassName</param-name>
               <param-value>...</param-value>
          </init-param>
    </filter>
    <filter-mapping>
          <filter-name>wicket.helloworld</filter-name>
          <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-fragment>
http://blogs.sun.com/arungupta/entry/totd_91_applying_java_ee

                                                                          18
Servlets 3.0      Resource Sharing

   Static and JSP no longer confined to
    document root of the web application
   May be placed in WEB-INF/lib/
    [*.jar]/META-INF/resources
   Resources in document root take
    precedence over those in bundled JAR
myapp.war
  WEB-INF/lib/catalog.jar
             /META-INF/resources/catalog/books.html

http://localhost:8080/myapp/catalog/books.html
                                                  19
EJB 3.1 (JSR 318)
    Package & Deploy in a WAR
          Java EE 5                                        Java EE 6
                                                       foo.war
    foo.ear
                                                       WEB-INF/classes
      foo_web.war                                       com.sun.FooServlet
                                                        com.sun.TickTock
      WEB-INF/web.xml                                   com.sun.FooBean
      WEB-INF/classes                                   com.sun.FooHelper
        com.sun.FooServlet
        com.sun.TickTock

      foo_ejb.jar
      com.sun.FooBean                                      web.xml ?
      com.sun.FooHelper


http://blogs.sun.com/arungupta/entry/totd_95_ejb_3_1
                                                                             20
EJB 3.1

@Stateless
public class App {
    public String sayHello(String name) {
        return "Hello " + name;
    }
}




                                            21
EJB 3.1
   No interface view – one source file per bean
       Only for Local and within WAR
       Required for Remote
       No location transparency
   Component initialization in @PostConstruct
       No assumptions on no-arg ctor




                                            22
Java EE 6 Namespaces
   Global
       java:global/..(for all applications)
   Application scoped
       java:app/.. (visibile only for the app.)
       App-1 binds an Object by name
        “java:app/myObject”, App-2 cannot
        see it.
       All modules of the app has visibility.
           mod-1, mod-2 of app-1 can see “java:app/myObject”
                                                            23
Java EE 6 Namespaces
   Module Scoped
       java:module/.. (visible only for the
        module)
       App-1 has module-1 and module-2
        
            Module-1's namespace not accessible by module-2
       All components of the module has
        visibility
   Component
                                                         24
EJB 3.1
Portable Global JNDI Name Syntax
   Portable
   Global
   Application/Module-scoped
   Derived from metadata such as name,
     component name etc.




                                          25
EJB 3.1
  Portable Global JNDI Name Syntax
                                                  Base name of ejb-jar/WAR
   Only within EAR                                 (or ejb-jar.xml/web.xml)
 Base name of EAR
 (or application.xml)



  java:global[/<app-name>]/<module-name>/<bean-name>
  [!<fully-qualified-interface-name>]



                                  Unqualified name of the bean class
                                     Annotation/name attribute
• Until now, only java:comp                  Or ejb-jar.xml
• Local & Remote business
• No-interface
• Also in java:app, java:module
                                                                       26
EJB 3.1
 Portable Global JNDI Name Syntax

     package com.acme;
     @Stateless
     public class FooBean implements Foo { ... }
    FooBean is packaged in fooejb.jar
java:global/fooejb/FooBean
java:global/fooejb/FooBean!com.acme.Foo
java:app/fooejb/FooBean
java:app/fooejb/FooBean!com.acme.Foo
java:module/FooBean
java:module/FooBean!com.acme.Foo
                                                   27
EJB 3.1
     Embeddable API – Deploy the Bean


     public void testEJB() throws NamingException {
             EJBContainer ejbC =
                  EJBContainer.createEJBContainer();
             Context ctx = ejbC.getContext();
             App app = (App)
                  ctx.lookup("java:global/classes/App");
             assertNotNull(app);
             String NAME = "Duke";
             String greeting = app.sayHello(NAME);
             assertNotNull(greeting);
             assertTrue(greeting.equals("Hello " + NAME));
             ejbC.close();
         }

http://blogs.sun.com/arungupta/entry/totd_128_ejbcontainer_createejbcontainer_embedded

                                                                                         28
Screencast
JSP, Servlets, EJB


                     29
EJB 3.1
    Singleton Beans
   One instance per app/VM, not pooled
       Useful for caching state
       CMT/BMT
       Access to container services for injection, resource
        manager, timers, startup/shutdown callbacks, etc.
       Enable eager initialization using @Startup
       Always supports concurrent access
       Define initialization ordering using @DependsOn
    @Singleton
    public class MyEJB {
      . . .
                                                        30
    }
EJB 3.1
Asynchronous Session Beans
   Control returns to the client before the
     container dispatches invocation to a
     bean instance
   @Asynchronous – method or class
   Return type – void or Future<V>
   Transaction context does not propagate
       REQUIRED → REQUIRED_NEW
   Security principal propagates
                                               31
EJB 3.1
Asynchronous Session Beans – Code Sample
 @Stateless
 @Asynchronous
 public class SimpleAsyncEJB {
     public Future<Integer> addNumbers(int n1, int n2) {
         Integer result;


             result = n1 + n2;
             try {
                 // simulate JPA queries + reading file system
                 Thread.currentThread().sleep(2000);
             } catch (InterruptedException ex) {
                 ex.printStackTrace();
             }

             return new AsyncResult(result);
       }
 }


 http://blogs.sun.com/arungupta/entry/totd_137_asynchronous_ejb_a
                                                                    32
EJB 3.1
Timers
   Automatically created EJB Timers
   Calendar-based Timers – cron like semantics
       Every Mon & Wed midnight
        @Schedule(dayOfWeek=”Mon,Wed”)
       2pm on Last Thur of Nov of every year
        (hour=”14”, dayOfMonth=”Last Thu”,
        month=”Nov”)
       Every 5 minutes of every hour
        (minute=”*/5”, hour=”*”)
       Every 10 seconds starting at 30
        (second=”30/10”)
       Every 14th minute within the hour, for the hours 1 & 2 am
        (minute=”*/14”, hour=”1,2”)
                                                             33
EJB 3.1
 Timers
 Single     persistent timer across JVMs
   Automatically created EJB Timers
       @Schedule(hour=”15”,dayOfWeek=”Fri”)

   Can be chained
       @Schedules({
           @Schedule(hour=”6”,dayOfWeek=”Tue,Thu,Fri-Sun”),
            @Schedule(hour=”12”,dayOfWeek=”Mon,Wed”)
        })

   May be associated with a TimeZone
   Non-persistent timer, e.g. Cache
       @Schedule(..., persistent=false)               34
EJB 3.1
EJB 3.1 Lite – Feature Comparison




                                    35
Managed Beans 1.0


  EJB         CDI      JSF       JAX-WS JAX-RS      JPA       ...


@Stateful
                      @Managed    @Web
@Stateless   @Named                         @Path   @Entity   ...
                       Bean       Service
@Singleton




    @javax.annotation.ManagedBean

                                                                36
Managed Beans 1.0
   POJO as managed component for the Java
    EE container
       JavaBeans component model for Java EE
       Simple and Universally useful
       Advanced concepts in companion specs
   Basic Services
       Resource Injection, Lifecycle Callbacks, Interceptors
   Available as
       @Resource / @Inject
       java:app/<module-name>/<bean-name>
       java:module/<bean-name>                            37
Managed Beans 1.0 - Sample
@javax.annotation.ManagedBean                              @Resource
public class MyManagedBean {                               MyManagedBean bean;
  @PostConstruct
  public void setupResources() {
    // setup your resources
  }                                                        @Inject
                                                           MyManagedBean bean;
    @PreDestroy
    public void cleanupResources() {
       // collect them back here
    }

    public String sayHello(String name) {
      return "Hello " + name;
    }
}
http://blogs.sun.com/arungupta/entry/totd_129_managed_beans_1
                                                                             38
Java Persistence API 2 (JSR
     317)
     Sophisticated mapping/modeling options
   Collection of basic types

@Entity
public class Person {
    @Id protected String ssn;
    protected String name;
    protected Date birthDate;
    . . .
    @ElementCollection
    @CollectionTable(name=”ALIAS”)
    protected Set<String> nickNames;
}
                                              39
Java Persistence API 2
    Sophisticated mapping/modeling options

   Collection of embeddables

@Embeddable public class Address {
    String street;
    String city;
    String state;
    . . .
}

@Entity public class RichPerson extends Person {
    . . .
    @ElementCollection
    protected Set<Address> vacationHomes;
    . . .
}                                                  40
Java Persistence API 2
    Sophisticated mapping/modeling options

   Multiple levels of embedding

@Embeddable public class ContactInfo {
    @Embedded Address address;
    . . .
}


@Entity public class Employee {
    @Id int empId;
    String name;
    ContactInfo contactInfo;
    . . .
}
                                             41
Java Persistence API 2
     Sophisticated mapping/modeling options

   Improved Map support

    @Entity public class VideoStore {
        @Id Integer storeId;
        Address location;
        . . .
        @ElementCollection
        Map<Movie, Integer> inventory;
    }

    @Entity public class Movie {
        @Id String title;
        @String director;
        . . .
    }
                                              42
Java Persistence API 2
    Metamodel

   Abstract “schema-level” model over
    managed classes of a Persistence Context
       Entities, Mapped classes, Embeddables, ...
   Accessed dynamically
       EntityManager or
        EntityManagerFactory.getMetamodel()
   And/or statically materialized as
    metamodel classes
       Use annotation processor with javac
                                                     43
Java Persistence API 2
    Metamodel Example
@Entity
public class Customer {
  @Id Integer custId;
  String name;
  ...
  Address address;
  @ManyToOne SalesRep rep;
  @OneToMany Set<Order> orders;
}
import javax.persistence.metamodel.*;

@StaticMetamodel(Customer.class)
public class Customer_ {
  public static SingularAttribute<Customer, Integer> custId;
  public static SingularAttribute<Customer, String> name;
  public static SingularAttribute<Customer, Address> address;
  public static SingularAttribute<Customer, SalesRep> rep;
  public static SetAttribute<Customer, Order> orders;
}
                                                                44
Java Persistence API 2
    Caching

   1st-level Cache by PersistenceContext
        Only one object instance for any database row
   2nd-level by “shared-cache-mode”
        ALL, NONE
        UNSPECIFIED – Provider specific defaults
        ENABE_SELECTIVE - Only entities with Cacheable(true)
        DISABLE_SELECTIVE - All but with Cacheable(false)
        Optional feature for PersistenceProvider

                                                         45
Java Persistence API 2
    Much more ...

   New locking modes
        PESSIMISTIC_READ – grab shared lock
        PESSIMISTIC_WRITE – grab exclusive lock
        PESSIMISTIC_FORCE_INCREMENT – update version
        em.find(<entity>.class, id,
         LockModeType.XXX)
        em.lock(<entity>, LockModeType.XXX)
   Standard configuration options
        javax.persistence.jdbc.[driver | url | user | password]
                                                           46
Screencast - JPA


                   47
@DataSourceDefinition
@DataSourceDefinition(
name="java:global/MyApp/MyDataSource",
className="org.apache.derby.jdbc.ClientDataSource"
databaseName=”testdb”,
serverName=”localhost”,
portNumber=”1527”,
user="dbuser",
password="dbpassword" )

• Equivalents in DDs as <datasource-definition> element
• Can be defined in Servlet, EJB, Managed Beans,
Application Client and their DDs.
• Can be defined in 'global', 'app', 'module', 'comp'
scopes
                                                          48
Interceptors 1.1
   Interpose on invocations and lifecycle
    events on a target class
   Defined
       Using annotations or DD
       Default Interceptors (only in DD)
   Class & Method Interceptors
       In the same transaction & security context
   Cross-cutting concerns: logging, auditing,
    profiling
                                                     49
Interceptors 1.1 - Code
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MyInterceptorBinding {
}


@Interceptor
@MyInterceptorBinding
public class MyInterceptor {
  @AroundInvoke
  public Object intercept(InvocationContext context) {
    System.out.println(context.getMethod.getName());
    System.out.println(context.getParameters());
    Object result = context.proceed();

      return result;
  }                                               50
 . . .
Interceptors 1.1 – Sample
  Code
@Interceptors(MyInterceptor.class)
public class MyManagedBean {
  . . .
}

@Inject
MyManagedBean bean;




http://blogs.sun.com/arungupta/entry/totd_134_interceptors_1_1
                                                                 51
Interceptors 1.1 – Sample
 Code
@MyInterceptorBinding
public class MyManagedBean {
  . . .
}
                                   Single instance of
                                    Interceptor per
                                 target class instance
public class MyManagedBean {
  @Interceptors(MyInterceptor.class)
  public String sayHello(String name) {
    . . .
  }
}



                                                  52
Interceptors 1.1 – Sample
    Code
@Named
@Interceptors(MyInterceptor.class)
public class MyManagedBean {
  . . .


    @Interceptors(AnotherInterceptor.class)
    @ExcludeDefaultInterceptors
    @ExcludeClassInterceptors
    public void someMethod() {
      . . .
    }
}



                                              53
Java Server Faces 2.0
   Facelets as “templating language” for the
    page
    • Custom components much easier to develop
      <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html">
        <h:head>
          <title>Enter Name &amp; Password</title>
        </h:head>
        <h:body>
          <h1>Enter Name &amp; Password</h1>
          <h:form>
            <h:panelGrid columns="2">
              <h:outputText value="Name:"/>
              <h:inputText value="#{simplebean.name}" title="name"
                           id="name" required="true"/>
              <h:outputText value="Password:"/>
              <h:inputText value="#{simplebean.password}" title="password"
                           id="password" required="true"/>
            </h:panelGrid>
            <h:commandButton action="show" value="submit"/>
          </h:form>
        </h:body>                                                            54
      </html>
JSF 2 Composite Components




                         55
JSF 2 Composite Components
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ez="http://java.sun.com/jsf/composite/ezcomp">
  <h:head>
    <title>Enter Name &amp; Password</title>
  </h:head>
  <h:body>
    <h1>Enter Name &amp; Password</h1>
    <h:form>
      <ez:username-password/>
      <h:commandButton action="show" value="submit"/>
    </h:form>
                                     . . .
  </h:body>
                                     WEB-INF
</html>
                                     index.xhtml
                                     resources/
                                       ezcomp/
                                         username-password.xhtml

http://blogs.sun.com/arungupta/entry/totd_135_jsf2_custom_components
                                                                       56
Screencast - JSF


                   57
Contexts & Dependency
    Injection – CDI (JSR 299)
   Type-safe Dependency Injection
       No String-based identifiers
       Selected at development/deployment time
   Strong typing, Loose coupling
   Context & Scope management - extensible
   Works with Java EE modular and
    component architecture
       Integration with Unified Expression Language (UEL)
                                                        58
CDI
Injection Points
   Field, Method, Constructor
   0 or more qualifiers
   Type                      Which one ?
                               (Qualifier)




                @Inject @LoggedIn User user
    Request                             What ?
    Injection                           (Type)
                                                 59
CDI – Sample Client Code
    Field and Method Injection

public class CheckoutHandler {

    @Inject @LoggedIn User user;

    @Inject PaymentProcessor processor;

    @Inject void setShoppingCart(@Default Cart cart) {
       …
    }

}




                                                    60
CDI – Sample Client Code
 Constructor Injection

public class CheckoutHandler {

    @Inject
    CheckoutHandler(@LoggedIn User user,
                    PaymentProcessor processor,
                    @Default Cart cart) {
      ...
    }

}




• Only one constructor can have @Inject
                                                  61
CDI - Sample Client Code
Multiple Qualifiers and Qualifiers with Arguments

public class CheckoutHandler {

    @Inject
    CheckoutHandler(@LoggedIn User user,
                    @Reliable
                    @PayBy(CREDIT_CARD)
                    PaymentProcessor processor,
                    @Default Cart cart) {
      ...
    }

}



                                                    62
CDI - Scopes
   Beans can be declared in a scope
       Everywhere: @ApplicationScoped, @RequestScoped
       Web app: @SessionScoped
       JSF app: @ConversationScoped : begin(), end()
         
             Transient and long-running
       Pseudo-scope (default): @Dependent
       Custom scopes via @Scope
   CDI runtime makes sure the right bean is
    created at the right time
   Client do NOT have to be scope-aware
                                                        63
CDI - Named Beans
    Built-in support for the Unified EL

   Beans give themselves a name with
    @Named(“cart”)
   Then refer to it from a JSF or JSP page
    using the EL:
     <h:commandButton
                  value=”Checkout”
                  action=“#{cart.checkout}”/>



                                                64
CDI - Events
    Even more decoupling
   Annotation-based event model
   A bean observes an event
void logPrintJobs(@Observes PrintEvent event){…}

   Another bean fires an event
    @Inject @Any Event<PrintEvent> myEvent;

    void doPrint() {
      . . .
      myEvent.fire(new PrintEvent());
    }

   Events can have qualifiers too
void logPrintJobs(@Observes @LargeFile PrintEvent event){…}
                                                       65
CDI
    Much more ...
   Producer methods and fields
   Alternatives
   Interceptors
   Decorators
   Stereotypes
   ...


                                  66
Screencast - CDI


                   67
Bean Validation (JSR 303)
   Tier-independent mechanism to define
    constraints for data validation
    • Represented by annotations
    • javax.validation.* package
   Integrated with JSF and JPA
    • JSF: f:validateRequired, f:validateRegexp
    • JPA: pre-persist, pre-update, and pre-remove
   @NotNull(message=”...”), @Max, @Min,
    @Size
   Fully Extensible        @Email String recipient;
                                                       68
Bean Validation
    Integration with JPA
   Managed classes may be configured
        Entities, Mapped superclasses, Embeddable classes
   Applied during pre-persist, pre-update,
    pre-remove lifecycle events
   How to enable ?
        “validation-mode” in persistence.xml
        “javax.persistence.validation.mode” key in
         Persistence.createEntityManagerFactory
   Specific set of classes can be targeted
        javax.persistence.validation.group.pre-[persist|
                                                            69
         update|remove]
Bean Validation
    Integration with JSF
   Individual validators not required
   Integration with EL
        f:validateBean, f:validateRequired
         <h:form>
           <f:validateBean>
             <h:inputText value=”#{model.property}” />
             <h:selectOneRadio value=”#{model.radioProperty}” > …
             </h:selectOneRadio>
             <!-- other input components here -->
           </f:validateBean>
         </h:form>




                                                                    70
JAX-RS 1.1

   Java API for building RESTful Web Services
   POJO based
   Annotation-driven
   Server-side API
   HTTP-centric



                                           71
JAX-RS 1.1
    Code Sample - Simple
@Path("helloworld")
public class HelloWorldResource {
    @Context UriInfo ui;

      @GET
      @Produces("text/plain")
      public String sayHello() {
          return "Hello World";
      }

      @GET
      @Path("morning")
      public String morning() {
           return “Good Morning!”;
      }
}

                                     72
JAX-RS 1.1
    Code Sample – Specifying Output MIME type
@Path("/helloworld")
@Produces("text/plain")
public class HelloWorldResource {
    @GET
    public String doGetAsPlainText() {
      . . .
    }

      @GET
      @Produces("text/html")
      public String doGetAsHtml() {
        . . .
      }                           @GET
}                                 @Produces({
                                    "application/xml",
                                    "application/json"})
                                  public String doGetAsXmlOrJson() {
                                    . . .
                                  }
                                                              73
JAX-RS 1.1
 Code Sample – Specifying Input MIME type

@POST
@Consumes("text/plain")
public String saveMessage() {
    . . .
}




                                            74
JAX-RS 1.1
    Code Sample
import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;

@RequestScoped
public class ActorResource {
    @Inject DatbaseBean db;

      public Actor getActor(int id) {
          return db.findActorById(id);
      }
}




                                                 75
JAX-RS 1.1
    Code Sample
import   javax.ws.rs.GET;
import   javax.ws.rs.Path;
import   javax.ws.rs.Produces;
import   javax.ws.rs.PathParam;
import   javax.inject.Inject;
import   javax.enterprise.context.RequestScoped;

@Path("/actor/{id}")
@RequestScoped
public class ActorResource {
    @Inject DatbaseBean db;

      @GET
      @Produces("application/json")
      public Actor getActor(@PathParam("id") int id) {
           return db.findActorById(id);
      }
}                      http://blogs.sun.com/arungupta/entry/totd_124_using_cdi_jpa
                                                                            76
JAX-RS 1.1
          Integration with Java EE 6 – Servlets 3.0

         No or Portable “web.xml”
<web-app>                                                     @ApplicationPath(“resources”
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
                                                              )
                                                              public class MyApplication
    <servlet-class>                                              extends
      com.sun.jersey.spi.container.servlet.ServletContainer      javax.ws.rs.core.Application {
    </servlet-class>
    <init-param>                                              }
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.foo.MyApplication</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/resources/*</url-pattern>
  </servlet-mapping>
</web-app>




                                                                                          77
Screencast - JAX-RS


                      78
GlassFish Distributions
Distribution              License      Features

GlassFish Open Source     CDDL &       • Java EE 6 Compatibility
Edition 3.0.1             GPLv2        • No Clustering
                                       • Clustering planned in 3.1
                                       • mod_jk for load balancing
GlassFish Open Source     CDDL &       • Java EE 5 Compatibility
Edition 2.1.1             GPLv2        • In memory replication
                                       • mod_loadbalancer
Oracle GlassFish Server   Commercial   • GlassFish Open Source Edition 3.0.1
                                                                             Clustering
3.0.1                                  • Oracle GlassFish Server Control      Coming
                                       • Clustering planned in 3.1             Soon!
Oracle GlassFish Server   Commercial   • GlassFish Open Source Edition 2.1.1
2.1.1                                  • Enterprise Manager
                                       • HADB




                                                                                 79
GlassFish 3 & OSGi
   No OSGi APIs are used in GlassFish
         HK2 provides abstraction layer
   All GlassFish modules are OSGi bundles
   Felix is default, also runs on Knopflerfish & Equinox
         Can run in an existing shell
         200+ modules in v3




    http://blogs.sun.com/arungupta/entry/totd_103_glassfish_v3_with

                                                                      80
Light Weight & On-demand
     Monitoring
   Event-driven light-weight and non-intrusive
    monitoring
   Modules provide domain specific probes
    (monitoring events)
    • EJB, Web, Connector, JPA, Jersey, Orb, Ruby
   End-to-end monitoring on Solaris using
    DTrace
   3rd party scripting clients
    • JavaScript to begin with                      81
Boost your productivity
    Retain session across deployment
asadmin redeploy –properties keepSessions=true helloworld.war




                                                                82
Boost your productivity
Deploy-on-Save




                          83
GlassFish Roadmap Detail




                                            84
  84
©2010 Oracle Corporation
GlassFish 3.1 = 3.0 + 2.1.1
   Main Features
       Clustering and Centralized Administration
       High Availability
   Other ...
       Application Versioning
       Application-scoped Resources
       SSH-based remote management and monitoring
       Embedded (extensive)
       Admin Console based on RESTful API

     http://wikis.sun.com/display/glassfish/GlassFishv3.1
                                                            85
References & Queries
   glassfish.org
   blogs.sun.com/theaquarium
   oracle.com/goto/glassfish
   glassfish.org/roadmap
   youtube.com/user/GlassFishVideos
   Follow @glassfish
   users@glassfish.java.net
   dev@glassfish.java.net
                                       86
Jagadish.Ramu@Sun.COM
                        Sun Microsystems
Java EE 6 - Deep Dive




                                   87

Mais conteúdo relacionado

Mais procurados

JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0Arun Gupta
 
Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008JavaEE Trainers
 
Java EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexusJava EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexusArun Gupta
 
Java EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The FutureJava EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The FutureIndicThreads
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5Arun Gupta
 
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010Arun Gupta
 
Ejb 3.0 Runtime Environment
Ejb 3.0 Runtime EnvironmentEjb 3.0 Runtime Environment
Ejb 3.0 Runtime Environmentrradhak
 
Introduction to java servlet 3.0 api javaone 2009
Introduction to java servlet 3.0 api javaone 2009Introduction to java servlet 3.0 api javaone 2009
Introduction to java servlet 3.0 api javaone 2009JavaEE Trainers
 
Java EE 6 = Less Code + More Power
Java EE 6 = Less Code + More PowerJava EE 6 = Less Code + More Power
Java EE 6 = Less Code + More PowerArun Gupta
 
Maven 3… so what?
Maven 3… so what?Maven 3… so what?
Maven 3… so what?Abel Muíño
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3 Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3 Skills Matter
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012Arun Gupta
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudArun Gupta
 
ICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax FrameworkICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax FrameworkICEsoftTech
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 

Mais procurados (19)

JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
 
Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008
 
Java EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexusJava EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexus
 
Java EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The FutureJava EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The Future
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
 
Ejb 3.0 Runtime Environment
Ejb 3.0 Runtime EnvironmentEjb 3.0 Runtime Environment
Ejb 3.0 Runtime Environment
 
Introduction to java servlet 3.0 api javaone 2009
Introduction to java servlet 3.0 api javaone 2009Introduction to java servlet 3.0 api javaone 2009
Introduction to java servlet 3.0 api javaone 2009
 
Java EE 6 = Less Code + More Power
Java EE 6 = Less Code + More PowerJava EE 6 = Less Code + More Power
Java EE 6 = Less Code + More Power
 
Maven 3… so what?
Maven 3… so what?Maven 3… so what?
Maven 3… so what?
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3 Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
 
Build system
Build systemBuild system
Build system
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the Cloud
 
ICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax FrameworkICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax Framework
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 

Semelhante a Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference On Java, 2010, Pune, India]

Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Arun Gupta
 
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnitionJava EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnitionArun Gupta
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...Arun Gupta
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Arun Gupta
 
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010Arun Gupta
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
Java Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewJava Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewEugene Bogaart
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopArun Gupta
 
Spring into rails
Spring into railsSpring into rails
Spring into railsHiro Asari
 
Java EE7 Demystified
Java EE7 DemystifiedJava EE7 Demystified
Java EE7 DemystifiedAnkara JUG
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Java EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the futureJava EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the futureArun Gupta
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3Ben Abdallah Helmi
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2Techglyphs
 
Sun Java EE 6 Overview
Sun Java EE 6 OverviewSun Java EE 6 Overview
Sun Java EE 6 Overviewsbobde
 

Semelhante a Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference On Java, 2010, Pune, India] (20)

Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6
 
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnitionJava EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
 
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
 
Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
 
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
Java EE 6 & GlassFish v3: Paving the path for the future - Spark IT 2010
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
J boss
J bossJ boss
J boss
 
Java Enterprise Edition 6 Overview
Java Enterprise Edition 6 OverviewJava Enterprise Edition 6 Overview
Java Enterprise Edition 6 Overview
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 Workshop
 
Spring into rails
Spring into railsSpring into rails
Spring into rails
 
Jsf Framework
Jsf FrameworkJsf Framework
Jsf Framework
 
Java EE7 Demystified
Java EE7 DemystifiedJava EE7 Demystified
Java EE7 Demystified
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Java EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the futureJava EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the future
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Sun Java EE 6 Overview
Sun Java EE 6 OverviewSun Java EE 6 Overview
Sun Java EE 6 Overview
 

Mais de IndicThreads

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs itIndicThreads
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsIndicThreads
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayIndicThreads
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices IndicThreads
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreadsIndicThreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreadsIndicThreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreadsIndicThreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprisesIndicThreads
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIndicThreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameIndicThreads
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceIndicThreads
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java CarputerIndicThreads
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache SparkIndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & DockerIndicThreads
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackIndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack CloudsIndicThreads
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!IndicThreads
 

Mais de IndicThreads (20)

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference On Java, 2010, Pune, India]

  • 1. Jagadish Ramu Sun Microsystems Java EE 6 - Deep Dive 1
  • 2. The following/preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 2
  • 3. Compatible Java EE 6 Impls Today: Announced: 3
  • 4. Goals for the Java EE 6 Platform  Flexible & Light-weight  Web Profile 1.0  Pruning: JAX-RPC, EJB 2.x Entity Beans, JAXR, JSR 88  Extensible • Embrace Open Source Frameworks  Easier to use, develop on • Continue on path set by Java EE 5 4
  • 5. Java EE 6 Web Profile 1.0  Fully functional mid-sized profile • Actively discussed in the Java EE 6 Expert Group and outside it • Technologies • Servlets 3.0, JSP 2.2, EL 2.2, Debugging Support for Other Languages 1.0, JSTL 1.2, JSF 2.0, Common Annotations 1.1, EJB 3.1 Lite, JTA 1.1, JPA 2.0, Bean Validation 1.0, Managed Beans 1.0, Interceptors 1.1, Context & Dependency Injection 1.0, Dependency Injection for Java 1.0 5
  • 6. Java EE 6 - Done 09  Specifications approved by the JCP  Reference Implementation is GlassFish v3 20  TCK ec D 6
  • 7. Java EE 6 Specifications  The Platform  Java EE 6 Web Profile 1.0  Managed Beans 1.0 7
  • 8. Java EE 6 Specifications New  Contexts and Dependency Injection for Java EE (JSR 299)  Bean Validation 1.0 (JSR 303)  Java API for RESTful Web Services (JSR 311)  Dependency Injection for Java (JSR 330) 8
  • 9. Java EE 6 Specifications Extreme Makeover  Java Server Faces 2.0 (JSR 314)  Java Servlets 3.0 (JSR 315)  Java Persistence 2.0 (JSR 317)  Enterprise Java Beans 3.1 & Interceptors 1.1 (JSR 318)  Java EE Connector Architecture 1.6 (JSR 322) 9
  • 10. Java EE 6 Specifications Updates  Java API for XML-based Web Services 2.2 (JSR 224)  Java API for XML Binding 2.2 (JSR 222)  Web Services Metadata MR3 (JSR 181)  JSP 2.2/EL 2.2 (JSR 245)  Web Services for Java EE 1.3 (JSR 109)  Common Annotations 1.1 (JSR 250)  Java Authorization Contract for Containers 1.3 (JSR 115)  Java Authentication Service Provider Interface for Containers 1.0 (JSR 196) 10
  • 11. Servlets in Java EE 5 At least 2 files <!--Deployment descriptor /* Code in Java Class */ web.xml --> package com.sun; <web-app> public class MyServlet extends <servlet> HttpServlet { <servlet-name>MyServlet public void doGet(HttpServletRequest </servlet-name> req,HttpServletResponse res) <servlet-class> com.sun.MyServlet { </servlet-class> ... </servlet> <servlet-mapping> } <servlet-name>MyServlet </servlet-name> ... <url-pattern>/myApp/* </url-pattern> } </servlet-mapping> ... </web-app> 11
  • 12. Servlets 3.0 (JSR 315) Annotations-based @WebServlet package com.sun; @WebServlet(name=”MyServlet”, urlPatterns={”/myApp/*”}) public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) <!--Deployment descriptor web.xml --> { ... <web-app> <servlet> } <servlet-name>MyServlet</servlet-name> <servlet-class> com.sun.MyServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/myApp/*</url-pattern> </servlet-mapping> ... </web-app> http://blogs.sun.com/arungupta/entry/totd_81_getting_started_with 12
  • 13. Servlets 3.0 Annotations-based @WebServlet @WebServlet(name="mytest", urlPatterns={"/myurl"}, initParams={ @WebInitParam(name="n1", value="v1"), @WebInitParam(name="n2", value="v2") } ) public class TestServlet extends javax.servlet.http.HttpServlet { .... 13 }
  • 14. Servlets 3.0 Annotations-based @WebListeners <listener> <listener-class> server.LoginServletListener </listener-class> </listener> package server; . . . @WebListener() public class LoginServletListener implements ServletContextListener { 14
  • 15. Servlets 3.0 Annotations-based @WebFilter <filter> <filter-name>PaymentFilter</filter-name> <filter-class>server.PaymentFilter</filter-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> package server; </init-param> . . . </filter> @WebFilter( <filter-mapping> <filter-name>PaymentFilter</filter-name> filterName="PaymentFilter", <url-pattern>/*</url-pattern> InitParams={ </filter-mapping> @WebInitParam( <filter-mapping> <filter-name>PaymentFilter</filter-name> name="param1", <servlet-name>PaymentServlet</servlet-name> value="value1") <dispatcher>REQUEST</dispatcher> } </filter-mapping> urlPatterns={"/*"}, servletNames={"PaymentServlet"}, dispatcherTypes={DispatcherType.REQUEST} ) public class PaymentFilter implements Filter { . . . 15
  • 16. Servlets 3.0 Asynchronous Servlets  Useful for Comet, long waits  Must declare @WebServlet(asyncSupported=true) AsyncContext context = request.startAsync(); context.addListener(new AsyncListener() { … }); context.dispatch(“/request.jsp”); //context.start(Runnable action); ... context.complete(); //marks completion 16 http://blogs.sun.com/arungupta/entry/totd_139_asynchronous_request_processing
  • 17. Servlets 3.0 Extensibility  Plugin libraries using web fragments  Modular web.xml  Bundled in framework JAR file in META-INF directory  Zero-configuration, drag-and-drop for web frameworks • Servlets, servlet filters, context listeners for a framework get discovered and registered by the container  Only JAR files in WEB-INF/lib are used 17
  • 18. Servlets 3.0 Extensibility <web-fragment> <filter> <filter-name>wicket.helloworld</filter-name> <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class> <init-param> <param-name>applicationClassName</param-name> <param-value>...</param-value> </init-param> </filter> <filter-mapping> <filter-name>wicket.helloworld</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-fragment> http://blogs.sun.com/arungupta/entry/totd_91_applying_java_ee 18
  • 19. Servlets 3.0 Resource Sharing  Static and JSP no longer confined to document root of the web application  May be placed in WEB-INF/lib/ [*.jar]/META-INF/resources  Resources in document root take precedence over those in bundled JAR myapp.war WEB-INF/lib/catalog.jar /META-INF/resources/catalog/books.html http://localhost:8080/myapp/catalog/books.html 19
  • 20. EJB 3.1 (JSR 318) Package & Deploy in a WAR Java EE 5 Java EE 6 foo.war foo.ear WEB-INF/classes foo_web.war com.sun.FooServlet com.sun.TickTock WEB-INF/web.xml com.sun.FooBean WEB-INF/classes com.sun.FooHelper com.sun.FooServlet com.sun.TickTock foo_ejb.jar com.sun.FooBean web.xml ? com.sun.FooHelper http://blogs.sun.com/arungupta/entry/totd_95_ejb_3_1 20
  • 21. EJB 3.1 @Stateless public class App { public String sayHello(String name) { return "Hello " + name; } } 21
  • 22. EJB 3.1  No interface view – one source file per bean  Only for Local and within WAR  Required for Remote  No location transparency  Component initialization in @PostConstruct  No assumptions on no-arg ctor 22
  • 23. Java EE 6 Namespaces  Global  java:global/..(for all applications)  Application scoped  java:app/.. (visibile only for the app.)  App-1 binds an Object by name “java:app/myObject”, App-2 cannot see it.  All modules of the app has visibility.  mod-1, mod-2 of app-1 can see “java:app/myObject” 23
  • 24. Java EE 6 Namespaces  Module Scoped  java:module/.. (visible only for the module)  App-1 has module-1 and module-2  Module-1's namespace not accessible by module-2  All components of the module has visibility  Component 24
  • 25. EJB 3.1 Portable Global JNDI Name Syntax  Portable  Global  Application/Module-scoped  Derived from metadata such as name, component name etc. 25
  • 26. EJB 3.1 Portable Global JNDI Name Syntax Base name of ejb-jar/WAR Only within EAR (or ejb-jar.xml/web.xml) Base name of EAR (or application.xml) java:global[/<app-name>]/<module-name>/<bean-name> [!<fully-qualified-interface-name>] Unqualified name of the bean class Annotation/name attribute • Until now, only java:comp Or ejb-jar.xml • Local & Remote business • No-interface • Also in java:app, java:module 26
  • 27. EJB 3.1 Portable Global JNDI Name Syntax package com.acme; @Stateless public class FooBean implements Foo { ... }  FooBean is packaged in fooejb.jar java:global/fooejb/FooBean java:global/fooejb/FooBean!com.acme.Foo java:app/fooejb/FooBean java:app/fooejb/FooBean!com.acme.Foo java:module/FooBean java:module/FooBean!com.acme.Foo 27
  • 28. EJB 3.1 Embeddable API – Deploy the Bean public void testEJB() throws NamingException { EJBContainer ejbC = EJBContainer.createEJBContainer(); Context ctx = ejbC.getContext(); App app = (App) ctx.lookup("java:global/classes/App"); assertNotNull(app); String NAME = "Duke"; String greeting = app.sayHello(NAME); assertNotNull(greeting); assertTrue(greeting.equals("Hello " + NAME)); ejbC.close(); } http://blogs.sun.com/arungupta/entry/totd_128_ejbcontainer_createejbcontainer_embedded 28
  • 30. EJB 3.1 Singleton Beans  One instance per app/VM, not pooled  Useful for caching state  CMT/BMT  Access to container services for injection, resource manager, timers, startup/shutdown callbacks, etc.  Enable eager initialization using @Startup  Always supports concurrent access  Define initialization ordering using @DependsOn @Singleton public class MyEJB { . . . 30 }
  • 31. EJB 3.1 Asynchronous Session Beans  Control returns to the client before the container dispatches invocation to a bean instance  @Asynchronous – method or class  Return type – void or Future<V>  Transaction context does not propagate  REQUIRED → REQUIRED_NEW  Security principal propagates 31
  • 32. EJB 3.1 Asynchronous Session Beans – Code Sample @Stateless @Asynchronous public class SimpleAsyncEJB { public Future<Integer> addNumbers(int n1, int n2) { Integer result; result = n1 + n2; try { // simulate JPA queries + reading file system Thread.currentThread().sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); } return new AsyncResult(result); } } http://blogs.sun.com/arungupta/entry/totd_137_asynchronous_ejb_a 32
  • 33. EJB 3.1 Timers  Automatically created EJB Timers  Calendar-based Timers – cron like semantics  Every Mon & Wed midnight @Schedule(dayOfWeek=”Mon,Wed”)  2pm on Last Thur of Nov of every year (hour=”14”, dayOfMonth=”Last Thu”, month=”Nov”)  Every 5 minutes of every hour (minute=”*/5”, hour=”*”)  Every 10 seconds starting at 30 (second=”30/10”)  Every 14th minute within the hour, for the hours 1 & 2 am (minute=”*/14”, hour=”1,2”) 33
  • 34. EJB 3.1 Timers  Single persistent timer across JVMs  Automatically created EJB Timers  @Schedule(hour=”15”,dayOfWeek=”Fri”)  Can be chained  @Schedules({ @Schedule(hour=”6”,dayOfWeek=”Tue,Thu,Fri-Sun”), @Schedule(hour=”12”,dayOfWeek=”Mon,Wed”) })  May be associated with a TimeZone  Non-persistent timer, e.g. Cache  @Schedule(..., persistent=false) 34
  • 35. EJB 3.1 EJB 3.1 Lite – Feature Comparison 35
  • 36. Managed Beans 1.0 EJB CDI JSF JAX-WS JAX-RS JPA ... @Stateful @Managed @Web @Stateless @Named @Path @Entity ... Bean Service @Singleton @javax.annotation.ManagedBean 36
  • 37. Managed Beans 1.0  POJO as managed component for the Java EE container  JavaBeans component model for Java EE  Simple and Universally useful  Advanced concepts in companion specs  Basic Services  Resource Injection, Lifecycle Callbacks, Interceptors  Available as  @Resource / @Inject  java:app/<module-name>/<bean-name>  java:module/<bean-name> 37
  • 38. Managed Beans 1.0 - Sample @javax.annotation.ManagedBean @Resource public class MyManagedBean { MyManagedBean bean; @PostConstruct public void setupResources() { // setup your resources } @Inject MyManagedBean bean; @PreDestroy public void cleanupResources() { // collect them back here } public String sayHello(String name) { return "Hello " + name; } } http://blogs.sun.com/arungupta/entry/totd_129_managed_beans_1 38
  • 39. Java Persistence API 2 (JSR 317) Sophisticated mapping/modeling options  Collection of basic types @Entity public class Person { @Id protected String ssn; protected String name; protected Date birthDate; . . . @ElementCollection @CollectionTable(name=”ALIAS”) protected Set<String> nickNames; } 39
  • 40. Java Persistence API 2 Sophisticated mapping/modeling options  Collection of embeddables @Embeddable public class Address { String street; String city; String state; . . . } @Entity public class RichPerson extends Person { . . . @ElementCollection protected Set<Address> vacationHomes; . . . } 40
  • 41. Java Persistence API 2 Sophisticated mapping/modeling options  Multiple levels of embedding @Embeddable public class ContactInfo { @Embedded Address address; . . . } @Entity public class Employee { @Id int empId; String name; ContactInfo contactInfo; . . . } 41
  • 42. Java Persistence API 2 Sophisticated mapping/modeling options  Improved Map support @Entity public class VideoStore { @Id Integer storeId; Address location; . . . @ElementCollection Map<Movie, Integer> inventory; } @Entity public class Movie { @Id String title; @String director; . . . } 42
  • 43. Java Persistence API 2 Metamodel  Abstract “schema-level” model over managed classes of a Persistence Context  Entities, Mapped classes, Embeddables, ...  Accessed dynamically  EntityManager or EntityManagerFactory.getMetamodel()  And/or statically materialized as metamodel classes  Use annotation processor with javac 43
  • 44. Java Persistence API 2 Metamodel Example @Entity public class Customer { @Id Integer custId; String name; ... Address address; @ManyToOne SalesRep rep; @OneToMany Set<Order> orders; } import javax.persistence.metamodel.*; @StaticMetamodel(Customer.class) public class Customer_ { public static SingularAttribute<Customer, Integer> custId; public static SingularAttribute<Customer, String> name; public static SingularAttribute<Customer, Address> address; public static SingularAttribute<Customer, SalesRep> rep; public static SetAttribute<Customer, Order> orders; } 44
  • 45. Java Persistence API 2 Caching  1st-level Cache by PersistenceContext  Only one object instance for any database row  2nd-level by “shared-cache-mode”  ALL, NONE  UNSPECIFIED – Provider specific defaults  ENABE_SELECTIVE - Only entities with Cacheable(true)  DISABLE_SELECTIVE - All but with Cacheable(false)  Optional feature for PersistenceProvider 45
  • 46. Java Persistence API 2 Much more ...  New locking modes  PESSIMISTIC_READ – grab shared lock  PESSIMISTIC_WRITE – grab exclusive lock  PESSIMISTIC_FORCE_INCREMENT – update version  em.find(<entity>.class, id, LockModeType.XXX)  em.lock(<entity>, LockModeType.XXX)  Standard configuration options  javax.persistence.jdbc.[driver | url | user | password] 46
  • 48. @DataSourceDefinition @DataSourceDefinition( name="java:global/MyApp/MyDataSource", className="org.apache.derby.jdbc.ClientDataSource" databaseName=”testdb”, serverName=”localhost”, portNumber=”1527”, user="dbuser", password="dbpassword" ) • Equivalents in DDs as <datasource-definition> element • Can be defined in Servlet, EJB, Managed Beans, Application Client and their DDs. • Can be defined in 'global', 'app', 'module', 'comp' scopes 48
  • 49. Interceptors 1.1  Interpose on invocations and lifecycle events on a target class  Defined  Using annotations or DD  Default Interceptors (only in DD)  Class & Method Interceptors  In the same transaction & security context  Cross-cutting concerns: logging, auditing, profiling 49
  • 50. Interceptors 1.1 - Code @InterceptorBinding @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface MyInterceptorBinding { } @Interceptor @MyInterceptorBinding public class MyInterceptor { @AroundInvoke public Object intercept(InvocationContext context) { System.out.println(context.getMethod.getName()); System.out.println(context.getParameters()); Object result = context.proceed(); return result; } 50 . . .
  • 51. Interceptors 1.1 – Sample Code @Interceptors(MyInterceptor.class) public class MyManagedBean { . . . } @Inject MyManagedBean bean; http://blogs.sun.com/arungupta/entry/totd_134_interceptors_1_1 51
  • 52. Interceptors 1.1 – Sample Code @MyInterceptorBinding public class MyManagedBean { . . . } Single instance of Interceptor per target class instance public class MyManagedBean { @Interceptors(MyInterceptor.class) public String sayHello(String name) { . . . } } 52
  • 53. Interceptors 1.1 – Sample Code @Named @Interceptors(MyInterceptor.class) public class MyManagedBean { . . . @Interceptors(AnotherInterceptor.class) @ExcludeDefaultInterceptors @ExcludeClassInterceptors public void someMethod() { . . . } } 53
  • 54. Java Server Faces 2.0  Facelets as “templating language” for the page • Custom components much easier to develop <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Enter Name &amp; Password</title> </h:head> <h:body> <h1>Enter Name &amp; Password</h1> <h:form> <h:panelGrid columns="2"> <h:outputText value="Name:"/> <h:inputText value="#{simplebean.name}" title="name" id="name" required="true"/> <h:outputText value="Password:"/> <h:inputText value="#{simplebean.password}" title="password" id="password" required="true"/> </h:panelGrid> <h:commandButton action="show" value="submit"/> </h:form> </h:body> 54 </html>
  • 55. JSF 2 Composite Components 55
  • 56. JSF 2 Composite Components <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:ez="http://java.sun.com/jsf/composite/ezcomp"> <h:head> <title>Enter Name &amp; Password</title> </h:head> <h:body> <h1>Enter Name &amp; Password</h1> <h:form> <ez:username-password/> <h:commandButton action="show" value="submit"/> </h:form> . . . </h:body> WEB-INF </html> index.xhtml resources/ ezcomp/ username-password.xhtml http://blogs.sun.com/arungupta/entry/totd_135_jsf2_custom_components 56
  • 58. Contexts & Dependency Injection – CDI (JSR 299)  Type-safe Dependency Injection  No String-based identifiers  Selected at development/deployment time  Strong typing, Loose coupling  Context & Scope management - extensible  Works with Java EE modular and component architecture  Integration with Unified Expression Language (UEL) 58
  • 59. CDI Injection Points  Field, Method, Constructor  0 or more qualifiers  Type Which one ? (Qualifier) @Inject @LoggedIn User user Request What ? Injection (Type) 59
  • 60. CDI – Sample Client Code Field and Method Injection public class CheckoutHandler { @Inject @LoggedIn User user; @Inject PaymentProcessor processor; @Inject void setShoppingCart(@Default Cart cart) { … } } 60
  • 61. CDI – Sample Client Code Constructor Injection public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, PaymentProcessor processor, @Default Cart cart) { ... } } • Only one constructor can have @Inject 61
  • 62. CDI - Sample Client Code Multiple Qualifiers and Qualifiers with Arguments public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, @Reliable @PayBy(CREDIT_CARD) PaymentProcessor processor, @Default Cart cart) { ... } } 62
  • 63. CDI - Scopes  Beans can be declared in a scope  Everywhere: @ApplicationScoped, @RequestScoped  Web app: @SessionScoped  JSF app: @ConversationScoped : begin(), end()  Transient and long-running  Pseudo-scope (default): @Dependent  Custom scopes via @Scope  CDI runtime makes sure the right bean is created at the right time  Client do NOT have to be scope-aware 63
  • 64. CDI - Named Beans Built-in support for the Unified EL  Beans give themselves a name with @Named(“cart”)  Then refer to it from a JSF or JSP page using the EL: <h:commandButton value=”Checkout” action=“#{cart.checkout}”/> 64
  • 65. CDI - Events Even more decoupling  Annotation-based event model  A bean observes an event void logPrintJobs(@Observes PrintEvent event){…}  Another bean fires an event @Inject @Any Event<PrintEvent> myEvent; void doPrint() { . . . myEvent.fire(new PrintEvent()); }  Events can have qualifiers too void logPrintJobs(@Observes @LargeFile PrintEvent event){…} 65
  • 66. CDI Much more ...  Producer methods and fields  Alternatives  Interceptors  Decorators  Stereotypes  ... 66
  • 68. Bean Validation (JSR 303)  Tier-independent mechanism to define constraints for data validation • Represented by annotations • javax.validation.* package  Integrated with JSF and JPA • JSF: f:validateRequired, f:validateRegexp • JPA: pre-persist, pre-update, and pre-remove  @NotNull(message=”...”), @Max, @Min, @Size  Fully Extensible @Email String recipient; 68
  • 69. Bean Validation Integration with JPA  Managed classes may be configured  Entities, Mapped superclasses, Embeddable classes  Applied during pre-persist, pre-update, pre-remove lifecycle events  How to enable ?  “validation-mode” in persistence.xml  “javax.persistence.validation.mode” key in Persistence.createEntityManagerFactory  Specific set of classes can be targeted  javax.persistence.validation.group.pre-[persist| 69 update|remove]
  • 70. Bean Validation Integration with JSF  Individual validators not required  Integration with EL  f:validateBean, f:validateRequired <h:form> <f:validateBean> <h:inputText value=”#{model.property}” /> <h:selectOneRadio value=”#{model.radioProperty}” > … </h:selectOneRadio> <!-- other input components here --> </f:validateBean> </h:form> 70
  • 71. JAX-RS 1.1  Java API for building RESTful Web Services  POJO based  Annotation-driven  Server-side API  HTTP-centric 71
  • 72. JAX-RS 1.1 Code Sample - Simple @Path("helloworld") public class HelloWorldResource { @Context UriInfo ui; @GET @Produces("text/plain") public String sayHello() { return "Hello World"; } @GET @Path("morning") public String morning() { return “Good Morning!”; } } 72
  • 73. JAX-RS 1.1 Code Sample – Specifying Output MIME type @Path("/helloworld") @Produces("text/plain") public class HelloWorldResource { @GET public String doGetAsPlainText() { . . . } @GET @Produces("text/html") public String doGetAsHtml() { . . . } @GET } @Produces({ "application/xml", "application/json"}) public String doGetAsXmlOrJson() { . . . } 73
  • 74. JAX-RS 1.1 Code Sample – Specifying Input MIME type @POST @Consumes("text/plain") public String saveMessage() { . . . } 74
  • 75. JAX-RS 1.1 Code Sample import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @RequestScoped public class ActorResource { @Inject DatbaseBean db; public Actor getActor(int id) { return db.findActorById(id); } } 75
  • 76. JAX-RS 1.1 Code Sample import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @Path("/actor/{id}") @RequestScoped public class ActorResource { @Inject DatbaseBean db; @GET @Produces("application/json") public Actor getActor(@PathParam("id") int id) { return db.findActorById(id); } } http://blogs.sun.com/arungupta/entry/totd_124_using_cdi_jpa 76
  • 77. JAX-RS 1.1 Integration with Java EE 6 – Servlets 3.0  No or Portable “web.xml” <web-app> @ApplicationPath(“resources” <servlet> <servlet-name>Jersey Web Application</servlet-name> ) public class MyApplication <servlet-class> extends com.sun.jersey.spi.container.servlet.ServletContainer javax.ws.rs.core.Application { </servlet-class> <init-param> } <param-name>javax.ws.rs.Application</param-name> <param-value>com.foo.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> </web-app> 77
  • 79. GlassFish Distributions Distribution License Features GlassFish Open Source CDDL & • Java EE 6 Compatibility Edition 3.0.1 GPLv2 • No Clustering • Clustering planned in 3.1 • mod_jk for load balancing GlassFish Open Source CDDL & • Java EE 5 Compatibility Edition 2.1.1 GPLv2 • In memory replication • mod_loadbalancer Oracle GlassFish Server Commercial • GlassFish Open Source Edition 3.0.1 Clustering 3.0.1 • Oracle GlassFish Server Control Coming • Clustering planned in 3.1 Soon! Oracle GlassFish Server Commercial • GlassFish Open Source Edition 2.1.1 2.1.1 • Enterprise Manager • HADB 79
  • 80. GlassFish 3 & OSGi  No OSGi APIs are used in GlassFish  HK2 provides abstraction layer  All GlassFish modules are OSGi bundles  Felix is default, also runs on Knopflerfish & Equinox  Can run in an existing shell  200+ modules in v3 http://blogs.sun.com/arungupta/entry/totd_103_glassfish_v3_with 80
  • 81. Light Weight & On-demand Monitoring  Event-driven light-weight and non-intrusive monitoring  Modules provide domain specific probes (monitoring events) • EJB, Web, Connector, JPA, Jersey, Orb, Ruby  End-to-end monitoring on Solaris using DTrace  3rd party scripting clients • JavaScript to begin with 81
  • 82. Boost your productivity Retain session across deployment asadmin redeploy –properties keepSessions=true helloworld.war 82
  • 84. GlassFish Roadmap Detail 84 84 ©2010 Oracle Corporation
  • 85. GlassFish 3.1 = 3.0 + 2.1.1  Main Features  Clustering and Centralized Administration  High Availability  Other ...  Application Versioning  Application-scoped Resources  SSH-based remote management and monitoring  Embedded (extensive)  Admin Console based on RESTful API http://wikis.sun.com/display/glassfish/GlassFishv3.1 85
  • 86. References & Queries  glassfish.org  blogs.sun.com/theaquarium  oracle.com/goto/glassfish  glassfish.org/roadmap  youtube.com/user/GlassFishVideos  Follow @glassfish  users@glassfish.java.net  dev@glassfish.java.net 86
  • 87. Jagadish.Ramu@Sun.COM Sun Microsystems Java EE 6 - Deep Dive 87

Notas do Editor

  1. P2A: Can you talk about the ecosystem of compatible implementations? What has been the feedback of various vendors as they have gone through the EE 6 spec lifecycle? J2EE 1.4 Implementations (17) Apache BEA CAS Once Hitachi IBM JBoss Kingdee NEC ObjectWeb Oracle Pramati SAP Sun Sybase TmaxSoft TongTech Trifork
  2. Talk about the introduction of profiles. Eg: Web Profile Eg: Telco Profile with SIP Servlet Specification + few specifications from Java EE Share common features : naming, resource injection, packaging rules, security requirements. Pruning : Process of making a specification/tech. Optional. Mark as Proposed for Optional in Nth release, Later decide to mark it as Optional in N+1 th release or further. Extensible : Ability to plugin other frameworks eg: web-fragments.xml Ease of use : annotations, packaging becoming easier (ejbs in war)
  3. Recently (during Java EE 6 timeframe), JCP requires the specification, reference-implementation and TCK need to be submitted together.
  4. *Interceptors has been elevated such that its not just for EJB interception, but for any ManagedBean Interception ?
  5. Standard Java EE 5 way of defining a Servlet with its DD. Refer servlet-name, servlet-mapping
  6. Equivalent of web.xml is available in Dds. @WebServlet, url pattern, explain how the mapping is done automatically. Classes in WEB-INF/classes or WEB-INF/lib are scanned for all “web” related annotations The class must extend HttpServlet Different instances, per “servlet-name” in DD (if any) “ servlet-name” if unspecified becomes fully classified class-name
  7. *WebInitParam : equivalent of init-param in DD so as to have default values for parameters.
  8. * Web Listener to listen to session, servletContext, request related events Which may be lifecycle related changes or attribute related changes. AsyncListener, Session Migration, Object Binding AsyncListeners can be registered only programmatically
  9. WebFilters to transform (adapt) HTTPRequest, Response to, from a Web Resource. (eg: Servlet). Equivalent annotations are introduced. Sample filtering : auditing, logging, encyrption, decryption, compression etc., RequestDispatcher : to forward processing a request to another servlet / include output from one servlet etc.,
  10. Web Fragments web-fragments.xml in META-INF directory Starts with &lt;web-fragment&gt; Order of elements differ from that of web.xml schema Web-fragments bundled with the framework library (automatically detected). This way frameworks are made available in a self contained manner and no special plumbing in web.xml per framework is required. Jars in WEB-INF/lib will be detected Possible to have a web-fragment.xml to define the order (&lt;ordering&gt; element) in which web-fragments will be initialized. [It is also possible to have the ordering defined in web.xml using &lt;absolute-ordering&gt; element]
  11. In Java EE 5, In order for a web module to use EJB, there need to be ejb-jar Ear : war + ejb-jar Java EE 6 : Ejbs can be part of .war No web.xml (as explained before). EJBs part of WEB-INF/classes
  12. * Simple POJO annotated with @Stateless makes it an EJB * This is of type no interface view EJB * Components can directly inject the bean, but only a reference is provided and not actual object
  13. One source per bean makes it easier for development. No interface defined This mode is supported only for Local Beans and within the WAR No support of location transparency (EJBs can be anywhere, outside the WAR etc.,) @PostConstruct : Component initialization logic must be in @PostConstruct as the constructor might be called multiple times by the container (eg: for each injection).
  14. Global jndi name of the ejb defined in vendor specific way (eg: sun-ejb-jar.xml) and then Referred by clients like application clients. Instead, exposed globally with a portable naming convention and hence will work in all vendor implementations.
  15. App-name is valid only if its an ear
  16. @Asynchronous Future&lt;T&gt; new AsyncResult(T), a wrapper which will provide the appropriate type of Future AsyncResult is defined in javax.ejb package
  17. Timer : Helps running cron jobs like generating reports, sending emails etc.,
  18. Attribute for timezone
  19. Java EE 6 introduces guidelines for various kinds of Beans in the system. ManagedBeans defines those basic characteristics which can be inherited by other specifications and build more features on top of it. Eg: EJB and CDI beans will be based on ManagedBeans. ManagedBeans will have : life-cycle callbacks, interceptor, Resource Injection capability.
  20. * Beans are exported in JNDI namespace. App-scoped and module scoped variants are available.
  21. Default Interceptors : Invoked first. Invoked in the order in which they are specified Interceptors on class first followed by Interceptors on method Superclass interceptors first.
  22. Default Interceptors : Invoked first. Invoked in the order in which they are specified Interceptors on class first followed by Interceptors on method Superclass interceptors first.
  23. In order to decouple interceptor from the bean, bean can be annotated with @MyInterceptorBinding (ie., the binding annotation itself). All @Interceptors having @MyInterceptorBinding will be called It is possible to have Method level interceptors. There will only one instance of interceptor per target class instance.
  24. Exclude default interceptors defined in the descriptor Exclude class level interceptors (eg: MyInterceptor in this case) So, the resulting interceptor will be only AnotherInterceptor for this “method” someMethod
  25. Strong typing, loose coupling - A bean specifies only the type and semantics of other beans it depends upon, and that too using typing information available in the the Java object model, and no String-based identifiers. It need not be aware of the actual lifecycle, concrete implementation, threading model or other clients of any bean it interacts with. Even better, the concrete implementation, lifecycle and threading model of a bean may vary according to the deployment scenario, without affecting any client. This loose-coupling makes your code easier to maintain. Events, interceptors and decorators enhance the loose-coupling inherent in this model: • event notifications decouple event producers from event consumers, • interceptors decouple technical concerns from business logic, and • decorators allow business concerns to be compartmentalized.
  26. Inject to Field, Method, Constructor Qualifier : Determines which bean to be injected whenever multiple beans match the request. Inject the currently logged in user. Qualifier : @LoggedIn Type : User @Inject : requests injection
  27. * Only One qualifier, @Default as good as not specifying it.
  28. To be able to invoke non-default constructor. Use @Inject on the constructor. Can also request injection of its parameters. Only one constructor can have @Inject
  29. Constructor CheckoutHandler requests a loggedin User and a Secure (reliable) credit-card based payment processor Among multiple PaymentProcessors, get Credit card based payment processor. Among multiple credit card based payment processor, get secure ones. What if multiple secure credit card based payment processors are available in the application ? Deployment will fail. Or Use “Alternative” in beans.xml
  30. Scope is declared on a bean. AppScoped, SessionScoped, ConversationScoped, Dependent AppScoped : throughout the application, bean will be active, shared. SessionScoped : throughout the session, bean will be active, shared ConversationScoped : Bean will inject a Conversation and do conversation.begin() and conversation.end() Dependent : Scope is based on the caller&apos;s scope. Eg: Method parameter : method Instance : till the life of the instance. More scopes via @Scope
  31. @Any : all events of type PrintEvent
  32. * Producer private Random random = new Random(System.currentTimeMillis()); @Produces @Named @Random int getRandomNumber() { return random.nextInt(100); } @Inject @Random int randomNumber; * Alternatives : To choose a particular bean when multiple beans will match the requested (even “qualified”) injection. Interceptors : cross cutting concerns : orthogonal to business concerns Decorators : Helps separate business related concerns : do extra things. Eg: monitor highValueTransactions alone in all accounts. Stereotypes : helps to compartmentalize beans. Helps to apply Scope and Interceptor Bindings.
  33. After pre-persist, pre-update, pre-remove are called, validation of JPA entity will be done. Can be defined on Fields, Methods Can define multiple constraints on Injection Points Can extend it to validate combination of multiple attributes Extensible : eg: @Email to make sure that “@” is present etc.,
  34. &lt;property name=&amp;quot;javax.persistence.validation.group.pre-persist&amp;quot; value&amp;quot;javax.validation.groups.Default, com.acme.model.Structural&amp;quot;/&gt; &lt;property name=&amp;quot;javax.persistence.validation.group.pre-update&amp;quot; value&amp;quot;javax.validation.groups.Default, com.acme.model.Structural&amp;quot;/&gt; &lt;property name=&amp;quot;javax.persistence.validation.group.pre-delete&amp;quot; value&amp;quot;com.acme.model.SafeDestruct&amp;quot;/&gt;
  35. * validateBean has “validateGroups” indicating the validation groups that need to be included while validating the bean that it is enclosing. * When the tag is unspecified, default validations will take place For more advanced use cases, like disabling constraint validation for one or several fields or using a specific group or set of groups instead of the default one, you can use the &lt;f:validateBean/&gt; tag
  36. OSGi : Module system and service platform for Java Helps to define modules, add, remove, update modules to the runtime dynamically, ability to execute multiple versions of same module simultaneously. Modules expose services which can be consumed by other modules dynamically. Security : to allow access to specific packages/ classes alone.