Friday, May 17, 2013

Java SE 8: Lambda

Introduction
Lambda expressions are a new and important feature included in Java Platform Standard Edition 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance in multicore environments.

JSR 335 - Project Lambda
Lambda Expressions are part of Java Specification Request (JSR 335) which is lead by Brian Goetz. JSR 335 is a coordinated co-evolution of the Java platform. It is going to change the language, libraries and VM.
  • Language - lambda expressions (closures), interface evolution, better type inference.
  • Libraries - Bulk parallel operations on collections.
  • VM - Support for default methods and lambda conversion.
This is a major step forward for the Java programming model:
  • More parallel-friendly.
  • Enable delivery of more powerful libraries.
  • Enable developers to write more concise, less error-prone code.
History - Closures for Java
When Java was first introduced in 1995 not many languages had closures, but they are present in pretty much every major language today, even C++.
In 1997 Java 1.1 added inner classes - a weak form of closures, which has many limitations as it is too bulky and the rule of name resolutions are too complex.
In 2006-2008, a vigorous community debate started about closures and multiple proposal arose including BGGA and CICE. Each had a different principle:
  • BGGA(Bracha Gafter Gosling Ahé) - Creating control abstraction in libraries and full closure support by Gilad Bracha, Neal Gafter, James Gosling and Peter von der Ahé.
  • CICE (Concise Instance Creation Expressions) - Simplified inner classes to reduce syntactic overhead by Bob Lee, Doug Lea and Josh Bloch.
Evaluation started from Java SE 5, 200, progress made by Project Coin (Small Language Changes) in Java SE 7. So for Java, it has been a long and winding road to get support for closures, until Project Lambda finally started in Dec 2009. In November 2010 the JSR 335 filled.
Currently the EDR (Early Draft Review) completed, prototype (source and binaries) available in OpenJDK and it is going to be a part of Java SE 8.

Why Lambda?
Java is the lone holdout among mainstream OO languages at this point to not have closures, and Lambda is no longer a radical idea, it was 10 years ago, times change and it is not anymore.
It provides libraries a path to multicore. Parallel-friendly APIs needs to have internal iteration and internal iteration needs a concise code-as-data mechanism.
It empower library developers by providing more powerful and flexible libraries and by providing higher degree of cooperation between libraries and client code which makes everybody's life better.

What is Lambda Expression?
A Lambda Expression is simply an anonymous method. Like a method it has an argument list, parameters, return type and has a set of thrown exception and a body. It has all the things that a method has except a name and it is not a member of a class, rather it is just an free floating expression.
Argument List Arrow Token Body
(int x, int y) -> x + y

Example:
(Object obj) -> obj.toString()
In this example it takes an Object as an argument, and in its body it calls Object.toString() and returns that. By this it removes a lots of syntactical overhead, there is no return statement, no braces etcetera.
It also can refer to values from the enclosing lexical scope:
(Shape shape) -> shape.getColor().equals(color)
Compiler can also infer parameter types from context, so in that case following statement is completely valid:
shape -> shape.getColor().equals(color)
There is also a feature added to the Lambda Expression is called Method References, which behave just like a Lambda Expression. If you already have a method and if you want to use that method behaviour as Lambda Expression, you can directly use that Method Reference as:
Object::toString
This is identical to the first example.


More to come...

Friday, May 10, 2013

Java EE 7: Specification, Services, Key features

Java EE Standard Services
The Java EE standard services include the following. Some of these standard services are actually provided by Java SE.
  1. HTTP
  2. HTTPS
  3. Java Transaction API (JTA)
  4. RMI-IIOP
  5. Java IDL
  6. JDBC API
  7. Java Persistence API (JPA)
  8. Java Message Service (JMS)
  9. Java Naming and Directory Interface (JNDI)
  10. JavaMail
  11. JavaBeans Activation Framework (JAF)
  12. XML Processing
  13. Java EE Connector Architecture
  14. Security Services
  15. Web Services
  16. Concurrency Utilities
  17. Batch
  18. Management
  19. Deployment
Interoperability 
Many of the APIs described above provide interoperability with components that are not a part of the Java EE platform, such as external web or CORBA services.
Following figure illustrates the interoperability facilities of the Java EE platform. (The directions of the arrows indicate the client/server relationships of the components.)
Java EE Interoperability
Key features:
Summary of the key features of different specifications in the Java EE 7 platform:
  1. Java EE 7 (JSR 342):
    • The main theme is to easily run applications on private or public clouds
    • The platform will define application metadata descriptor to describe PaaS execution environment such as multi-tenancy, resources sharing, quality-of-service, and dependencies between applications
    • Embrace latest standards like HTML5, WebSocket, JSON and have a standards-based API for each one of them
    • Remove inconsistencies between Managed Beans, EJB, Servlets, JSF, CDI, and JAX-RS
    • Possible inclusion of JAX-RS 2.0 in the Web Profile, revised JMS 2.0 API
    • Technology Refresh for several existing technologies (more on this below) and possible inclusion of Concurrency Utilities for Java EE (JSR 236) and JCache (JSR 107)
    • Status
  2. JPA 2.1 (JSR 338):
    • Support for multi-tenancy
    • Support for stored procedures and vendor function
    • Update and Delete Critieria queries
    • Support for schema generation
    • Persistence Context synchronization
    • CDI injection into listeners
    • Status
  3. JAX-RS 2.0 (JSR 339):
    • Client API - low level using builder pattern and possibly a higher level on top of that
    • Hypermedia - easily create and process links associated with resources
    • Form or Query parameter validation using Bean Validation
    • Closer integration with @Inject, etc
    • Server-side asynchronous request processing
    • Server-side content negotiation using "qs"
    • Status
  4. Servlets 3.1 (JSR 340):
    • Optimize the PaaS model for Web applications
    • Multi tenancy for security, session, resources, etc.
    • Asynchronous IO based on NIO2
    • Simplfiied asynchronous Servlets
    • Utilize Java EE concurrency utilities
    • Enable support for WebSockets
    • Status:
  5. Expression Language 3.0 (JSR 341):
    • Separate ELContext into parsing and evaluation contexts
    • Customizable EL coercion rules
    • Reference static methods and members directly in EL expressions
    • Adding operators like equality, string concatenation, and sizeof etc.
    • Integration with CDI such as generating events before/during/after the expressions are evaluated
    • Status
  6. Java Message Server 2.0 (JSR 343):
    • Ease of development - changes to the JMS programming model to make the application development simpler and easier
    • Remove/Clarify ambiguities in the existing specification
    • Integration with CDI
    • Clarification of the relationship between JMS and other Java EE specs
    • A new mandatory API to allow any JMS provider to be integrated with any Java EE container
    • Multi-tenancy and other cloud-related features from the platform
    • Status
  7. Java Server Faces 2.2 (JSR 344):
    • Ease of Development - making configuration options dynamic, make cc:interface in composite components optional, shorthand URLs for Facelet tag libraries, integration with CDI, OSGi support for JSF artifacts
    • Support implementation of Portlet Bridge 2.0 (JSR 329)
    • Support for HTML5 features like HTML5 Forms, Metadata, Heading and Section content model
    • Flow management, Listener for page navigation events, and new components like FileUpload and BackButton
    • Status
  8. EJB 3.2 (JSR 345):
    • Enhancements to the EJB architecture to enable PaaS, such as multi-tenancy
    • Factorization of container-managed transactions to use outside EJB
    • Further use of annotations
    • Alilgnment and integration with other specifications in the platform
    • Status
  9. CDI 1.1 (JSR 346, more details):
    • Global ordering of interceptors and decorators
    • API for managing built-in contexts
    • Embedded mode to allow startup outside Java EE container
    • Declarative control over which packages/beans are scanned in an archive
    • Injection for static members such as loggers
    • Send Servlet events as CDI event
    • Status
  10. Bean Validation 1.1 (JSR 349):
    • Integration with other Java EE specs
      • JAX-RS: Validate parameters and return values on HTTP calls
      • JAXB: Convert constraints into XML schema descriptor
    • Method level validation
    • Apply constraints on group collection
    • Extend the model to support AND and OR style composition
    • Status
  11. JCache (JSR 107)
    • API and semantics for temporary, in-memory caching of Java objects, including object creation, shared access, spooling, invalidation, and consistency across JVMs
    • Package: javax.cache
    • Status
      • Approved by the JCP
      • Spec lead: Yannis Cosmadopoulos, Cameron Purdy (Oracle) and Gregory Luck (Software AG)
      • Project page: jsr107spec
      • Mailing List Archive: jsr107@googlegroups.com
  12. State Management (JSR 350):
    • API that can be used by applications and Java EE containers to offload the responsibility of statement management into third party providers with different QoS characteristics
    • Java SE-based callers can access the state data by querying the state providers
    • Providers with different QoS can be added and API callers can query to meet their criteria
    • Package: javax.state and javax.state.provider
    • Status
  13. Batch Application for the Java Platform (JSR 352):
    • Programming model for batch applications and a runtime for scheduling and executing jobs
    • Defines Batch Job, Batch Job Step, Batch Application, Batch Executor, and Batch Job Manager for the standard programming model
    • Package: javax.batch
    • Status
  14. Concurrency Utilities for Java EE (JSR 236):
    • Provides a clean, simple, independent API by building on JSR 166, making it appropriate for use within any Java EE contianer.
    • Package: javax.util.concurrent
    • Status
      • Approved by the JCP
      • Spec lead: Anthony Lai, Naresh Revanuru (Oracle)
      • Project page:
      • Mailing List Archive:
  15. Java API for JSON Processing (JSR 353):
Reference:

Sunday, March 17, 2013

Upgrade JSF version in JBoss AS 7.1.1.Final

The JBoss AS 7.1.1 Final ships with Mojarra implementation of JSF versions 1.2 and 2.1.7. However sometimes developers need to change or upgrade the JSF version.
Prior to this JBoss version web applications could load their own JSF by placing the jar in WEB-INF/lib and adding the following context-param in web.xml.

   org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL
   true


But this doesn't work anymore for 7.1.1. Following is how you can do it.
At the time of this writing I have used version 2.1.19.
  • First you need to download the jsf-impl and jsf-api jars that you want. Here are the MVN Repository for jsf-impl and jsf-api.
  • Place the jsf-impl jar in the path modules/com/sun/jsf-impl/main.
  • Open the module.xml of that directory and change the value of path of resource-root as


  • Now place the jsf-api jar in the path modules/javax/faces/api/main.
  • Open the module.xml of that directory and change the value of path of resource-root as


  • Because jsf-api depends on jsf-impl you need to add the dependency in the module of jsf-api as


Now you are good to run you server. While running the server if you see the following line:
14:14:08,379 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (MSC service thread 1-4) Initializing Mojarra 2.1.19 ( 20130213-1512 https://svn.java.net/svn/mojarra~svn/tags/2.1.19@11614) for context '/your-app'
Then everything is fine.
Good luck.

Sunday, February 17, 2013

Implementation of Singleton pattern with Inheritance and Generics

Some day ago while playing around with Singleton, I had a thought that if it is possible to implement a Singleton class with Generics and Inheritance.
The Singleton classes do mostly same tasks, so I thought maybe I can put the common methods in the parent class using Inheritance.
Usually I create the Singleton object by Lazy Singleton pattern. Here is my parent class AbstractXMLParser:
public abstract class AbstractXMLParser<T> { 
 private static final Map<Class<? extends AbstractXMLParser>, AbstractXMLParser> INSTANCES = new HashMap<>();
 
 public AbstractXMLParser() {
  
 }

 private static class SingletonHolder<T> {    
  private static <T> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
   Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructors()[0];
   constructor.setAccessible(true);   
   return constructor.newInstance(null);
  }
 }
 
 protected static <T extends AbstractXMLParser<T>> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
  if(INSTANCES.containsKey(clazz)) {
   return (T) INSTANCES.get(clazz);
  } else {
   T instance = SingletonHolder.getInstance(clazz);
   INSTANCES.put(clazz, instance);
   return instance;
  }
 }
 
 protected static <T extends AbstractXMLParser<T>> void putInstance(Class<T> clazz, T instance) {
  if(!INSTANCES.containsKey(clazz)) {
   INSTANCES.put(clazz, instance);
  }
 }
}

Here the SingletonHolder inner class is used for Lazy. Note that the instantiation of the new child object has been done through Reflection. And the getInstance method is protected so that it can be accessible from the child classes only. As the Generic types are not visible in runtime so, I had to pass the class name explicitly from the child class's getInstance method to it.
Here is one of the child class ActivityTypeXMLParser:
public class ActivityTypeXMLParser extends AbstractXMLParser<ActivityTypeXMLParser> {

 private ActivityTypeXMLParser() {

 }

 public static ActivityTypeXMLParser getInstance() {
  ActivityTypeXMLParser activityTypeXMLParser = null;

  try {
   activityTypeXMLParser = getInstance(ActivityTypeXMLParser.class);
  } catch (Exception exception) {
  }

  if (activityTypeXMLParser == null) {
   activityTypeXMLParser = new ActivityTypeXMLParser();
   putInstance(ActivityTypeXMLParser.class, activityTypeXMLParser);
  }

  return activityTypeXMLParser;
 }
}
The Map of the parent class is used to store the class name as key the value object to get reference of the object in future call.
I hope you can get an idea how to use Inheritance with Singleton object in Java.

Sunday, May 6, 2012

Configuring Wicket to use HTTPS in JBoss AS7

I am currently developing a Web Application using Wicket-1.5.3. There I wanted to use HTTPS protocol. It is my pleasure to share the gathered information with you; perhaps this might come useful to you.

I am going to describe the procedure from the beginning. The whole procedure is split into three steps. At fist you need to create the Security Certificate and to create this certificate you need to use keytool command which comes with JDK.

Security Certificate Creation:
Open the command prompt and type the following command and follow the steps accordingly: 
 C:\Users\Tanmoy>keytool -genkey -alias tapasb -keypass joyguru -keystore jymCertificate.cer -storepass joyguru 

 What is your first and last name? 

  [Unknown]: Tapas Bose 

 What is the name of your organizational unit? 

  [Unknown]: JYM INC 

 What is the name of your organization? 

  [Unknown]: JYM INC 

 What is the name of your City or Locality? 

  [Unknown]: Kolkata 

 What is the name of your State or Province? 

  [Unknown]: West Bengal 

 What is the two-letter country code for this unit? 

  [Unknown]: IN 

 Is CN=Tapas Bose, OU=JYM INC, O=JYM INC, L=Kolkata, ST=West Bengal, C=IN correct? 

  [no]: yes 

 C:\Users\Tanmoy> 


After that the certificate file will be created in your home directory. Copy that file and go to the JBoss folder, in my case it is C:\Development\JBoss-AS-7.1.0.Final and create a folder with name certificate, in fact you can use any name you want, and paste the copied certificate file there and by doing this the first step completes. Now you are ready to go for second step.

Modify standalone.xml:
Stop your server. Go into the ${jboss.home.dir}/standalone directory, in my case it is C:\Development\JBoss-AS-7.1.0.Final\standalone\configuration, backup the standalone.xml, if something goes wrong, open that standalone.xml in an editor, I use Notepad++.

Find the xml element called <subsystem> with xmlns="urn:jboss:domain:web:1.1", this element configures the protocols. Add the following code:
  
     
  

Now it will be:
  
       
       
           
       
       
           
           
       
   

This ends the step two. Keep in mind you should stop your server before any modification.
Start your server and you should  see you server has been started successfully. Try to browse: https://localhost:8443/, if you don't see the following screen then  you probably mess something up and start again with the backup-ed xml file.

Now you are ready to go to write you wicket application which is going to use HTTPS protocol.

Make Wicket to use HTTPS:
It is very easy to make you application to use HTTPS in Wicket 1.5.x. In the init method of your application class which extends
org.apache.wicket.protocol.http.WebApplication  

in my case it is
org.apache.wicket.authroles.authentication.AuthenticatedWebApplication

since I am using Wicket Authentication policy, add the following code snippet:

setRootRequestMapper(new HttpsMapper(getRootRequestMapper(), new HttpsConfig(8080, 8443)));

After you configured your application to use HTTPS you need to specify the pages which will use this protocol and for that you need to use @RequireHttps annotation with the page class, as shown below:

public class MyPage extends WebPage {  
     private static final long serialVersionUID = -298979616675428637L;  
     // your code goes here  
}

If your page classes have a common super class, you can use this annotation on top of that base class.

Now deploy and run your application, you should see that it is using the Hyper Text Transfer Protocol Secure.

That's all folks.