Monday, March 23, 2015

Solving Circular Dependencies in CDI

If you are using CDI in your project and if you are using it in such a way that there are circular dependencies:

@Singleton @AC class A { @Inject @DC D d; }
@Singleton @DC class D { @Inject @AC A a; }
You are likely to end up with issues like:
 org.jboss.weld.exceptions.DeploymentException: WELD-001443: Pseudo scoped bean has circular dependencies. Dependency path:  

You can go ahead and use the javax.inject.Provider to resolve these issues in such a way.
 
@Singleton @AC class A { @Inject @DC D d; }
@Singleton @DC class D { @Provider Provider<A> a; }
 
Then you may get the instance of Class A within any method of D as follows: 
 A aInstance = a.get();  

This way you can solve circular dependency issues of such nature.

Testing JEE6 CDI outside of Container using Weld-SE

0. Add the dependencies in Maven Model
    <dependency>  
       <groupId>org.jboss.weld.se</groupId>  
       <artifactId>weld-se-core</artifactId>  
       <version>2.2.9.Final</version>  
       <scope>test</scope>  
    </dependency>  

1. Develop the Class(es) which are annotated with CDI
 @ApplicationScoped  
 public class ContextsDependencyInjectionManager {  
private static final Logger LOGGER = Logger.getLogger(
ContextsDependencyInjectionManager.class);
@Resource private ManagedThreadFactory managedThreadFactory;
@Inject @Persistent private EngagementManager persistentManger;
@Inject @Radia private
EngagementManager radiaManager;
@Inject @Accelerite private
EngagementManager acceleritManager;
@Inject @Services private
EngagementManager servicesManager; ... // add functionality, methods, other atrributes }

2. Write a Test Case to test the Class(es) using Weld-SE
 public class ContextsDependencyInjectionManagerTest { 
public static void main(String[] args) throws Exception {
ContextsDependencyInjectionManagerTest test = new ContextsDependencyInjectionManagerTest(); // cdi initialization outside of container Weld weld = new Weld(); WeldContainer weldContainer = weld.initialize(); ContextsDependencyInjectionManager cdiManager = weldContainer.instance() .select(ContextsDependencyInjectionManager .class).get(); ... // other tests, fire events, assert }

3.Using/Firing Events in Weld-SE - Test @Observes
If you have used the observer pattern or added listeners using @Observes, you may choose to test them out as follows.
           weldContainer  
                     .event()  
                     .select(EngagementAttributeChangedEvent.class)  
                     .fire(new EngagementAttributeChangedEvent(  
                               EngagementManagerConstants.ENGAGEMENT_MANAGER_ENTITY_DASHBOARD,  
                               "contact", "sumith_puri", "pl"));  

This is helpful for the initial developer testing and before a version is available to deploy in the container, to understand if all dependencies are getting injected and whether many of the CDI annotations are working as intended.

Wednesday, March 18, 2015

Contexts and Dependency Injection (CDI) - Eager Extension

CDI does not provide eager extensions out of the box. Even though there is @ApplicationScoped that is intended to work in a similar way to eager instantiation - It does not behave in the specified fashion. 

I am going to describe how to use CDI extensions to get eagerly instantiated beans following the CDI lifecycle, inside the container. I have used this in Wildfly 8.0. 


Step 1: First, write the @Eager Annotation
 package me.sumithpuri.test.cdi.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier;
@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}) public @interface Eager { }

Step 2: Next, develop the Eager Extension to parse the Annotations.
 package me.sumithpuri.test.cdi.extension;  
import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AfterDeploymentValidation; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessBean; import me.sumithpuri.test.cdi.annotation.Eager;
public class EagerExtension implements Extension {
private List<Bean<?>> eagerBeansList = new ArrayList<Bean<?>>(); public <T> void collect(@Observes ProcessBean<T> event) {
if (event.getAnnotated().isAnnotationPresent(Eager.class) && event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) { System.out.println("debug: found an eager annotation"); eagerBeansList.add(event.getBean()); } }
public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
for (Bean<?> bean : eagerBeansList) { System.out.println("debug: eager instantiation will be performed - " + bean.getBeanClass()); // note: toString() is important to instantiate the bean beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); } } }

Step 3: Next, configure the extension, using this single line of code, placed inside META-INF/services/javax.enterprise.inject.spi.Extension
 me.sumithpuri.test.cdi.extension.EagerExtension  

Step 4: Develop other parts of the application 
You can refer to the attached code to develop other parts of the application to test CDI (@Eager)

You may download the code from here. Also, note that even though all lifecycle methods are performed such @PostConstruct, @PreDestroy, etc. - no @Inject is being performed. My assumption is that we have to write another extension to perform this. My request to the CDI creators to provide an @Eager out of the box, so that it can help to develop (and sometime help in test) applications where Dependency Injection can be performed outside of Servlets, Web Services, etc.

[credits to: http://ovaraksin.blogspot.in/2013/02/eager-cdi-beans.html]

Thursday, March 12, 2015

REST Using Apache Wink (XML/JSON)

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-hochiminh
 
Representational State Transfer (REST)
Hypermedia as the Engine of Application State (HATEOAS)
 
 
As mentioned earlier, this is  the second in series on REST Using Apache Wink. You can understand how to use complex return types, such as XML using JAXB and Json using Jackson as the stream reader or stream writer.

Firstly, setup the REST project as described in REST Using Apache Wink

1. Returning XML using JAXB
The class whose object that has to be returned to the client has to be first annotated using the following annotations:

1. XMLRootElement
The root element of the xml that has to be returned, at the class level

2. XMLAttribute
An attribute of the root element that has to be returned

3. XMLElement
An element contained within the root element

This can be used in a nested way to allow multiple levels of nested objects to be returned to the invoker.
 package me.sumithpuri.rest.vo;  
 import javax.xml.bind.annotation.XmlAttribute;  
 /**  
  * @author sumith_puri  
  *  
  */  
 @XmlRootElement(name="product")  
 public class Product {  
      long id;  
      String name;  
      @XmlAttribute  
      public long getId() {  
           return id;  
      }  
      public void setId(long id) {  
           this.id = id;  
      }  
      @XmlElement(name="name")  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String toString() {  
           String productStr="ID:" + this.id + ", NAME: " + this.name;  
           return productStr;  
      }  
 }  

The respective method(s) now need to annotated to return XML using @Produces.
      @GET  
      @Path("/{id}")  
      @Produces(MediaType.APPLICATION_XML)  
      public Product getProductById(@PathParam(value="id") long id) {  
           Product product = persistenceManager.getProduct(id);  
           return product;  
      }  

We can access this method now using a REST Client
      public void invokeJAXBGET(long id) {  
           System.out.println("Testing JAXB GET command....");       
           RestClient restClient = new RestClient(clientConfig);  
           Resource resource = restClient.resource(REST_WEB_SERVICE+"/"+id);  
           ClientResponse response=resource.accept(MediaType.APPLICATION_XML).get();  
           System.out.println("...JAXB GET command is successful");  
      }  

On the browser, type the url : http://localhost:8080/products/rest/product/3
<product id="3">
<name>Sumith Puri</name>
</product> 

2. Returning JSON using Jackson
Jackson is an extension over JAXB to return JSON from REST web service. It can be used as the mapper to convert from JAXB. First, include the relevant Jackson JARs:

We also have to write an application class, to register the mapper.
 package me.sumithpuri.rest.app;  

 import java.util.HashSet;  
 import java.util.Set;  
 import javax.ws.rs.core.Application;  
 import me.sumithpuri.rest.webservice.ProductWebService;  
 import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;  
 import org.codehaus.jackson.map.AnnotationIntrospector;  
 import org.codehaus.jackson.map.ObjectMapper;  
 import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;  


 public class ProductApplication extends Application {  
      @Override  
      public Set<Class<?>> getClasses() {  
           Set<Class<?>> classes = new HashSet<Class<?>>();  
           classes.add(ProductWebService.class);  
           return classes;  
      }  
      @Override  
      public Set<Object> getSingletons() {  
           Set<Object> s = new HashSet<>();  
           ObjectMapper objMapper = new ObjectMapper();  
           AnnotationIntrospector primary = new JaxbAnnotationIntrospector();  
           AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();  
           AnnotationIntrospector pair = AnnotationIntrospector.pair(primary, secondary);  
           objMapper.getDeserializationConfig().withAnnotationIntrospector(pair);  
           objMapper.getSerializationConfig().withAnnotationIntrospector(pair);  
           JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider();  
           jaxbProvider.setMapper(objMapper);  
           s.add(jaxbProvider);  
           return s;  
      }  
 }  

Next, change the Apache Wink configuration in your web.xml as follows:
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>products</display-name>  
  <servlet>  
   <servlet-name>restService</servlet-name>  
   <servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>  
   <init-param>  
    <!-- <param-name>applicationConfigLocation</param-name> -->  
    <!-- <param-value>/WEB-INF/application</param-value> -->  
    <param-name>javax.ws.rs.Application</param-name>  
    <param-value>me.sumithpuri.rest.app.ProductApplication</param-value>  
   </init-param>  
  </servlet>  
  <servlet-mapping>  
   <servlet-name>restService</servlet-name>  
   <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>  
 </web-app>  

The next is to add the relevant method to the service, and mark that it returns JSON. 
      @GET  
      @Path("/json/{id}")  
      @Produces(MediaType.APPLICATION_JSON)  
      public Product getProductJsonById(@PathParam(value="id") long id) {  
           Product product = persistenceManager.getProduct(id);  
           return product;  
      }  

Now, add the method to the client to test out the method.
      public void invokeJSONGET(long id) {  
           System.out.println("Testing JSON GET command....");       
           RestClient restClient = new RestClient(clientConfig);  
           Resource resource = restClient.resource(REST_WEB_SERVICE+"/json/"+id);  
           ClientResponse response=resource.accept(MediaType.APPLICATION_JSON).get();  
           System.out.println("...JSON GET command is successful");  
      }  

On the browser, type the url : http://localhost:8080/products/rest/product/json/3 
{"id":3,"name":"Sumith Puri"}

You may download the war, including source, for reference from here.


[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-hochiminh