Saturday, April 12, 2014

JEE 6 NEW FEATURES

Web profile :- Java EE 6 defines the first profile, called the Web Profile. This initial profile is a Java EE platform subset for web application development. 


  • JavaServer Faces (JSF) 2.0
  • JavaServer Pages 2.2 and Expression Language (EL) 1.2
  • A Standard Tag Library for JavaServer Pages 1.2
  • Debugging Support for Other Languages 1.0
  • Contexts and Dependency Injection for the Java EE Platform 1.0
  • Dependency Injection for Java
  • Enterprise JavaBeans 3.1(EJB Lite)
  • Java Persistence API 2.0
  • Common Annotations for the Java Platform 1.1
  • Java Transaction API (JTA) 1.1
  • Bean Validation 1.0



  • Java API for RESTful Web Services (JAX-RS)
  • Contexts and Dependency Injection for the Java EE Platform (CDI) -- CDI unifies and simplifies the EJB and JSF programming models. It allows enterprise beans to act as JSF managed beans in a JSF application, and brings transactional support to the web tier. CDI builds on managed beans, which are designed to unify all of the various types of beans in Java EE 6. In JSF2.2 backing beans are now managed beans & denoted by annotation @ManagedBean, CDI services allow Java EE components, including EJB components, to be bound to lifecycle events using @Model. @Inject, identifies a point at which a dependency on a Java class or interface can be injected. @Interceptors allows interceptors in managed bean
    • @Inject. Identifies injectable constructors, methods, and fields.
    • @Qualifier. Identifies qualifier annotations. Qualifiers are strongly-typed keys that help distinguish different uses of objects of the same type. For example, a @Red Car and a @Blue Car are understood to be different instances of the same type. In this example,@Red and @Blue are qualifiers.
    • @Scope. Identifies scope annotations.
    • @Singleton. Identifies a type that the injector only instantiates once
    • @Named. A String-based qualifier to access methos in Facelets using EL.
  • Bean Validation :- Bean Validation affords a standard framework for validation, in which the same set of validations can be shared by all the layers of an application. Bean Validation includes a number of built-in constraint definitions. You add your own constraints by declaring an annotation type that specifies a validator class.
    • e.g. @ZipCode, @Size, @ConstraintValidator, @NotNull

    • Servlet 3.0 :- Web fragments enable web frameworks to self-register, eliminating the need for you to register them through deployment descriptors. The  element identifies a web fragment. A web fragment must be in a file named web-fragment.xml and can be placed in any location in a web application's classpath. However, it's expected that a web framework will typically place its web fragments in the META-INF directory of the framework's JAR file. 
      • Instead of creating deployment descriptors, you can annotate classes to specify servlet-related deployment information.
      • @WebServlet
      • @WebFilter
      • @WebInitParam
      • @WebListener
      • @MultipartConfig
    • Asynchronous Processing in Servlet 3.0 :- A servlet no longer has to wait for a response from a resource such as a database before its thread can continue processing. To make a servlet asynchronous, you specify asyncSupported=true in a@WebServlet annotation
    • Simplified Page Authoring in JSF 2.0 :- 
      • Facelets :- In JSP, elements in a web page are processed and rendered in a progressive order. However, JSF provides its own processing and rendering order. This can cause unpredictable behavior when web applications are executed. Facelets resolves this mismatch. Facelets also enables code reuse through templating and can significantly reduce the time to develop and deploy UIs.
      • Templating
      • Composite Components
      • Support for Ajax in JSF 2.0 :-  tag can invoke functions in the JavaScript API.
      • Programatically servlet & filter can be added at runtime.
      • JSF2.0 :- All resources like css, js, images, properties file will go under resources folder.
    • EJB 3.1 :-
    • No-interface view. Allows you to specify an enterprise bean using only a bean class without having to write a separate business interface. Local interface is optional.
    • Singletons. Lets you easily share state between multiple instances of an enterprise bean component or between multiple enterprise bean components in an application.
    • Asynchronous session bean invocation. Enables you to invoke session bean methods asynchronously by specifying an annotation @Asynchronous@Startup annotation guarantees that @PostConstruct method will be called on application initialization.
    • Simplified Packaging. Removes the restriction that enterprise bean classes must be packaged in an ejb-jar file. You can now place EJB classes directly in a WAR file.
    • EJB Lite. Is a subset of EJB 3.1 for inclusion in a variety of Java EE profiles.
    • Timer :- Programmatic & calendar based scheduling. Cron like syntax.
    • JPA Enhancements:- 
      • In JPA 2.0, you can map collections of basic data types, such as Strings or Integers, as well as collections of embeddable objects.
      • In query, case statement, nullif, coalesce are supported.
      • Criteria API supports builder pattern to generate queries.
    • Misc Features :-
      • Portable JNDI Name
      1. Bean has a @LocalBean annotation -> bean has a no-interface view
      2. Bean has a @Local annotation -> bean has a local view
      3. Bean has a @Remote annotation -> bean has a remote view
The following table depicts what type of managed classes can inject what objects.
ResourcesStatelessStatefulMDBInterceptors
JDBC DataSourceYesYesYesYes
JMS Destinations, Connection FactoriesYesYesYesYes
Mail ResourcesYesYesYesYes
UserTransactionYesYesYesYes
Environment EntriesYesYesYesYes
EJBContextYesYesYesNo
Timer ServiceYesNoYesNo
Web Service referenceYesYesYesYes
EntityManager, EntityManagerFactoryYesYesYesYes
Java EE 5 introduced several metadata annotations as part of JSR 250. Although primarily geared toward EJB, these annotations also apply to Java EE components such as Servlets, JSF managed beans, and application clients.
The following annotations can be used in a field or a setter method for dependency injection. However, these annotations may also be applied at the class level for defining dependencies and then used with JNDI look up.
AnnotationsUsageComponents that can use
javax.annotation.ResourceDependency injection of resources such as DataSource, and JMS objectsEJB, Web, Application Client
javax.ejb.EJBDependency injection of Session beansEJB, Web, Application Client
javax.xml.ws.WebServiceRefDependency injection of Web servicesEJB, Web, Application Client
javax.persistence.PersistenceContextDependency injection of container-managed EntityManagerEJB, Web
javax.persistence.PersistenceUnitDependency injection of EntityManagerFactoryEJB, Web

JEE 7 New Features

  • CDI 1.1 (JSR 346) :- Can specify package as @Vetoed & classes are retrieved using auto discovery.
  • Bean Validation 1.1 (JSR 349) :- Pre/Post conditions on constructor, methods.
  • Interceptors 1.2 (JSR 318) :- Interceptor associated with constructor. @AroundConstruct
    • @Priority - priorirty can be set for different interceptors
  • Concurrency utilities 1.0 (JSR 236) :- Before JEE7, creating threads were discouraged in EE container. Thread pool of EJBs were managed by container.
    •  User threads in Java EE applications
    •  The ability to support simple and advance concurrency design patterns
    •  And to extend Concurrency Utilities API from Java SE (JSR 166y)
    • New classes ManagedExecutor, ManagedScheduledExecutor, ManagedThreadFactory, DynamicProxy
    • reates dynamic proxy objects, and adds contextual information available for applications running in Java EE environment
    • It supports Classloading, JNDI, Security, 
  • JPA 2.1 (JSR 338) :-
    • Schema generation
    • @Index - define index in JPA mapping. In schema generation index will be created.
    • Calling stored procedure in JPA
  • JTA 1.2 (JSR 907) :-
    • @Transactional - Transaction management on Managed Beans as CDI interceptor binding
  • EJB 3.2 (JSR 345) :- 
    • Disable passivation of stateful ejb
    • Async + non persistent timer
  • JMS 2.0 (JSR 343)
    • Simplified API to consume & produce messages.
    • Autoclosable implemented.
    • Annotation to create JMS factory connection definition, JMS destination definition.

  • Servlet 3.1 (JSR 340)
    • Servlet non blocking I/O - Only for asynchronous servlet. New interface ReadListener, Writelistener.
    • New methods like setReadListener, isReady, isfinished in ServletInputStream interface,
    • New methods like setWriteListener, canWrite in ServletOutputStream interface.
    • Improved security. Now can deny http type request by configuring in web.xml file.
  • Web Socket 1.0 (JSR 356)
    • Annotated server endpoint - enables full duplex bi-directional communication over single TCP connection.
    • LifeCycle callback methods - onOpen, ocClose, on Error
    • Annotated client endpoint
    • Websocket encoder & decoder
  • Expression Language 3.0 (JSR 341)
    • ELProcessor - Evaluate EL expression, GET/SET bean properties, 
  • JSF 2.2 (JSR 344)
    • FlowFaces, FileUpload component, 
  • JAX-RS 2.0 (JSR 339)
    • New API to consume services
    • Async client - Async invocation, Async server -  Async processing
    • Message Filter - Used to process Incoming/Outgoing request response headers
    • Entity interceptors- Marshalling/Un-Marshalling of HTTP message bodies.
  • JSON-P 1.0 (JSR 353)
    • JSON builder
    • JSON parser
  • Batch 1.0 (JSR 352)
    • Chunk style processing, BatchLet style processing, Step processing, batch partition
    • Creating batch workflows
  • JavaMail 1.5 (JSR 919)
  • JCA 1.7 (JSR 322)
  • Java Connector Architecture
  • Default Resources
    • Default JMSConnectionFactory
    • Default concurrency objects - DefaultMangedExecutorService, DefaultMangedScheduledExecutorService,  DefaultMangedThreadFactory, DefaultContextService



    Friday, April 11, 2014

    JDK 6 new features over jdk5

    Collections Framework Enhancements


    These new collection interfaces are provided:
    • Deque - a double ended queue, supporting element insertion and removal at both ends. Extends the Queue interface.
    • BlockingDeque - a Deque with operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element. Extends both the Deque andBlockingQueue interfaces. (This interface is part of java.util.concurrent.)
    • NavigableSet - a SortedSet extended with navigation methods reporting closest matches for given search targets. A NavigableSet may be accessed and traversed in either ascending or descending order. This interface is intended to supersede the SortedSet interface.
    • NavigableMap - a SortedMap extended with navigation methods returning the closest matches for given search targets. A NavigableMap may be accessed and traversed in either ascending or descending key order. This interface is intended to supersede the SortedMap interface.
    • ConcurrentNavigableMap - a ConcurrentMap that is also a NavigableMap. (This interface is part of java.util.concurrent.)
    The following concrete implementation classes have been added:
    These existing classes have been retrofitted to implement new interfaces:
    • LinkedList - retrofitted to implement the Deque interface.
    • TreeSet - retrofitted to implement the NavigableSet interface.
    • TreeMap - retrofitted to implement the NavigableMap interface.
    The Arrays utility class now has methods copyOf and copyOfRange that can efficiently resize, truncate, or copy subarrays for arrays of all types.
    Before:
    int[] newArray = new int[newLength];
    System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
    
    After:
    int[] newArray = Arrays.copyOf(a, newLength);
    
    
    The following new methods were added to File:
    Constructors were added to the following class:
    The behavior of the following method was modified:
    • The File.isFile() Windows implementation has been modified to always return false for reserved device names such as CON, NUL, AUX, LPT, etc. Previously it returned true, which customers considered a bug because it was inconsistent with behavior for devices on Unix.
    
    
    
    

    JDK 7 vs JDK 6

     Utilities :- 
    • Fork Join Pool :- ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks). When setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.
       
    • Phaser :- A reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.

    Java Programming Lang :-
    • Strings are allowed in switch statements.
    • try with resource :- no need to close resources for FileStream, Socket, Data connection etc all classes that are implementing AutoCloseable interface.    try (Statement stmt = con.createStatement()) {} catch {}
    • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
             catch (IOException|SQLException ex) {
                 logger.log(ex);
                 throw ex;
             }
    • Underscores in numeric literals :-
    132_465_789
    • Type inference for generic type :-
                    Map aMap = new HashMap<>();
    • JVM support for non java language :- Use bootstrap method & use invokedynamic method.
    • Garbage First collector :- The G1 collector is a server-style garbage collector, targeted for multi-processor machines with large memories. It meets garbage collection (GC) pause time goals with high probability, while achieving high throughput. Whole-heap operations, such as global marking, are performed concurrently with the application threads. This prevents interruptions proportional to heap or live-data size. G1 is planned as the long term replacement for the Concurrent Mark-Sweep Collector (CMS).

    JDK 8 vs JDK 7

    Lambda :- Java compiler compiles lambda expression into private method & using invokedynamic bind this method dynamically.
    Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces. An interface can have multiple default methods.
    Interface can have static methods.


    Functional Interface :- has only one abstract/normal method, but can have multiple default methods. With Java 8 the same concept of SingleAbstractMethod (SAM) interfaces is recreated and are called Functional interfaces. Some popular SAM interface are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable.

    Nashorn :-

    Stream class in util :-