My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

.

.

.

.

.

.

.

.


[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

Se afișează postările cu eticheta CDI. Afișați toate postările
Se afișează postările cu eticheta CDI. Afișați toate postările

marți, 28 iunie 2016

CDI-JSF: Beans discovery modes

When we write applications that involves CDI we need to activate CDI by adding in our project a file named beans.xml. Usually, this file will look like below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
 bean-discovery-mode="all">       
</beans>

In this post, we are interested in the part highlighted in red. If you never notice that part before, then this quick post is for you. Let's see what is happening when we have bean-discovery-mode="all", and for this let's consider a simple interface with two implementations, as follows:

public interface IFoo {
 public void fooSlaveAction();
}

@RequestScoped
public class FooImplAnnotated implements IFoo {

 private static final Logger LOG = Logger.getLogger(FooImplAnnotated.class.getName());  
   
 @Override
 public void fooSlaveAction() {
  LOG.info("FooImplAnnotated#fooSlaveAction() invoked ...");
 }   
}

public class FooImplNoAnnotation implements IFoo {

 private static final Logger LOG = Logger.getLogger(FooImplNoAnnotation.class.getName());  
  
 @Override
 public void fooSlaveAction() {
  LOG.info("FooImplNoAnnotation#fooSlaveAction() was invoked ...");
 }   
}

As you can see, the main difference between these two implementations consist in the fact that FooImplAnnotated is annotated with a CDI annotation, @RequestScoped. Well, now let's inject these two implementation in a third CDI bean:

@Named
@RequestScoped
public class FooBean {
   
 // inject the annotated bean
 @Inject
 private FooImplAnnotated fooAnnotated;        
   
 // inject the no-annotation bean
 @Inject
 private FooImplNoAnnotation fooNoAnnotation;
   
 public void fooMasterAction(){
  // call fooSlaveAction() of the annotated bean
  fooAnnotated.fooSlaveAction();
    
  // call fooSlaveAction() of the no annotation bean
  fooNoAnnotation.fooSlaveAction();
 }   
}

If we test this application (for example by calling the fooMasterAction() method  via a simple EL as #{fooBean.fooMasterAction()}), we will get the following messages  in the server log:

FooImplAnnotated#fooSlaveAction() invoked ...
FooImplNoAnnotation#fooSlaveAction() was invoked ...

Ok, this is the effect of using bean-discovery-mode="all" who tells CDI to discover all beans. No, let's alter the beans.xml as switch the value of bean-discovery-mode from all to annotated:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
 bean-discovery-mode="annotated">       
</beans>

This time the test will fail with an error of type org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type FooImplNoAnnotation with qualifiers @Default. Well, the problem is that the FooImplNoAnnotation is not discoverable and it cannot be injected in FooBean. Since we are looking only for annotated implementation, we can re-write our FooBean like below:

@Named
@RequestScoped
public class FooBean {

 // inject the annotated bean
 @Inject
 private IFoo fooAnnotated;

 public void fooMasterAction() {
  // call fooSlaveAction() of the annotated bean
  fooAnnotated.fooSlaveAction();
 }
}

Now, the test will pass again, and the server log will reveal this message: FooImplAnnotated#fooSlaveAction() invoked ...Since the FooImplNoAnnotation is not discoverable, CDI has choose  the single available implementation, FooImplAnnotated. Of course, if we make the FooImplNoAnnotation discoverable by adding a CDI annotation to it, then CDI will cause  ambiguous dependencies errors.

Ok, finally, let's switch the value of bean-discovery-mode from annotated to none:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
 bean-discovery-mode="none">       
</beans>

This time the test will not cause any error and no messages will be available in the server log. We just told CDI to not try to discover any bean.

The complete example is available here.

marți, 21 iunie 2016

CDI-JSF: Using CDI alternatives priority (@Priority)


So, since you are familiar with the above post, now let's suppose that we have multiple mock implementations. In such cases, the problem is how to instruct the container to choose between the implementations? The answer relies on alternatives priority!

Basically, we annotate each mock implementation with @Priority and provide a number as the level of priority. The higher number has the higher priority. Here it is three mock implementations with priorities 1,2 and 3:

@Priority(1)
@Alternative
@Stateless
public class FooServiceMock implements IFooService {

 @Override
 public List getAllFoo() {
  return Arrays.asList("foo 1", "foo 2", "foo 3");
 }
}

@Priority(2)
@Alternative
@Stateless
public class BestFooServiceMock implements IFooService {

 @Override
 public List getAllFoo() {
  return Arrays.asList("best foo 1", "best foo 2", "best foo 3");
 }
}

@Priority(3)
@Alternative
@Stateless
public class GreatFooServiceMock implements IFooService {

 @Override
 public List getAllFoo() {
  return Arrays.asList("great foo 1", "great foo 2", "great foo 3");
 }
}

The mock implementation annotated with @Priority(3) has the higher priority. When we run the below code CDI will automatically choose the GreatFooServiceMock:

@Named
@RequestScoped
public class FooBean {

 private static final Logger LOG = Logger.getLogger(FooBean.class.getName());

 @Inject
 private IFooService fooService; // choose GreatFooServiceMock

 public void loadAllFoo() {
  List allfoo = fooService.getAllFoo();

  LOG.log(Level.INFO, "allfoo:{0}", allfoo);
 }
}

Now, we can also write a test using CDI-Unit as below (this will also choose the GreatFooServiceMock):

@RunWith(CdiRunner.class)
@ActivatedAlternatives({FooServiceMock.class, BestFooServiceMock.class, GreatFooServiceMock.class})
public class FooBeanTest {
   
 @Inject
 FooBean fooBean;

 @Test
 @InRequestScope
 public void testStart() {
  fooBean.loadAllFoo();
 }   
}

We can use the @Priority annotation to specify alternatives globally for an application that consists of multiple modules like this:

@Alternative
@Priority(Interceptor.Priority.APPLICATION+10)
public class ...

The complete example is available here.

sâmbătă, 18 iunie 2016

CDI-JSF: Use a CDI alternative as a mock implementation for a stateless session bean

A great feature of CDI (supported by Java EE starting with version 6) consist in alternatives. Basically, we want to specify an alternative for an injected object. Let's have a simple scenario commonly followed in JSF applications that uses stateless session beans to interact with a database. Supposing that we write the business logic part to query the database. We can start with an interface as:

public interface IFooService {
 List getAllFoo();
}

Further, we can write a stateless session bean that implements this interface and take usage of JPA capabilities to query the database. Well the things didn't go too far for this part because the database is not ready and all we can provide is a skeleton like below:

@Stateless
public class FooService implements IFooService {
   
 @PersistenceContext(unitName = "fooPU")
 private EntityManager em;

 @Override
 public List getAllFoo() {
  // perform the query
  ...
  return new ArrayList();
 }
}

Finally, we inject the stateless session bean in a CDI managed bean as below:

Named
@RequestScoped
public class FooBean {

 private static final Logger LOG = Logger.getLogger(FooBean.class.getName());

 @Inject
 private IFooService fooService;

 public void loadAllFoo() {
  List allfoo = fooService.getAllFoo();
  LOG.log(Level.INFO, "allfoo:{0}", allfoo);
 }
}

Now, let's suppose that we want to run/test this method, but we have an issue. The data that we expect from the database will not be available, so we think to mock this service and provide a set of dummy data as below:

@Stateless
public class FooServiceMock implements IFooService {

 @Override
 public List getAllFoo() {
  return Arrays.asList("foo 1", "foo 2", "foo 3");
 }
}

But, if we test the code now, we will obtain an error of type ambiguous dependencies. In order to fix this error, we simply annotated our mock with @Alternative annotation:

@Alternative
@Stateless
public class FooServiceMock implements IFooService {

 @Override
 public List getAllFoo() {
  return Arrays.asList("foo 1", "foo 2", "foo 3");
 }
}

If we run now, there will be no errors, but the application will not use the mock. This is happening because our alternative is not activated. We must accomplish this in the beans.xml, as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
   
 <alternatives>
  <class>beans.FooServiceMock</class>
 </alternatives>
</beans>

Done! Now the FooBean will use the FooServiceMock instead of FooService. When the database will be ready/queryable we will simply deactivate the alternative.

Via CDI-Unit we can write a quick test that also uses our mock:

@RunWith(CdiRunner.class)
@ActivatedAlternatives(FooServiceMock.class)
public class FooBeanTest {
   
 @Inject
 FooBean fooBean;

 @Test
 @InRequestScope
 public void testStart() {
  fooBean.loadAllFoo();
 }   
}

The complete example is available here.

vineri, 17 iunie 2016

CDI-JSF: Testing CDI code using CDI-Unit

There are a few approaches to test CDI code such as using @Alternative and/or mocking. Another approach, presented here is to use the JGlue project - more exactly the CDI-Unit which is a JUnit4 test runner that enables unit testing Java CDI applications.

For example, let's consider the application from post Inject a Java logger via a CDI producer method - in this application you saw exactly what the name of the post say, how to inject a Java logger via a producer method. Now, let's suppose that we want to write a JUnit test for  the method FooBean#logBuzzAction():

@Named
@RequestScoped
public class FooBean {

 @Inject
 Logger fooLog;

 public void logFooAction() {
  fooLog.info("Log message from FooBean !");
 }
}

In a pretty dummy approach we can try this:

public class LoggerTest {

 @Inject
 FooBean fooBean;

 @Test
 public void testStart() {
  fooBean.logFooAction();
 }
}

Well, obviously this will not work! The problem will be caused by the @Inject part, so is time to find a solution. Add quickly the CDI-Unit dependency in the POM:

<dependency>
 <groupId>org.jglue.cdi-unit</groupId>
 <artifactId>cdi-unit</artifactId>
 <version>3.1.2</version>
 <scope>test</scope>
</dependency>

And specify @RunWith(CdiRunner.class) on your JUnit4 test class to enable injection directly into the test class:

@RunWith(CdiRunner.class)
public class LoggerTest {

 @Inject
 FooBean fooBean;

 @Test
 public void testStart() {
  fooBean.logFooAction();
 }
}

Ok, the FooBean is injected now! But, now we have an unsatisfied dependencies for type Logger.  In order to fix this issue, simply specify MyLogger class as an additional class for this test. This will tell  CDI-Unit to explicitly add a class to the CDI environment:

@RunWith(CdiRunner.class)
@AdditionalClasses(MyLogger.class)
public class LoggerTest {

 @Inject
 FooBean fooBean;

 @Test 
 public void testStart() {
  fooBean.logFooAction();
 }
}

Ok, the last issue that we must solve consist in the fact that there is no active contexts for the request scope, but CDI-Unit has built in support for request, session and conversation scopes using @InRequestScope, @InSessionScope and @InConversationScope. So, let's bring the context in:

@RunWith(CdiRunner.class)
@AdditionalClasses(MyLogger.class)
public class LoggerTest {

 @Inject
 FooBean fooBean;

 @Test
 @InRequestScope
 public void testStart() {
  fooBean.logFooAction();
 }
}

Done! Now the test is ready and you can see it here.

CDI-JSF: Using the CDI @Observes

In this post we will discuss about using the CDI @Observes in a JSF application.

Basically, we will exploit the fact that Java EE provides an easier implementation of the observer design pattern via the @Observes annotation and javax.enterprise.event.Event<T> interface.

Note In the bellow examples, we will use CDI managed beans, but you can use EJB 3 beans also.

Basically, the observer pattern is based on a subject and some observers:

subject - an object that changes its state
observers - objects notified when the subject has changed its state

This time, the subject is a CDI managed bean named, MainFireStationBean:

@Named
@RequestScoped
public class MainFireStationBean {

 @Inject
 Event<String> evt;

 public void fireStarted(String address) {
  evt.fire(address);
 }
}

The container injects an Event object of type String into the evt instance variable of the MainFireStationBean class (practically, this String represents the fire address). To activate an event, call the javax.enterprise.event.Event.fire() method. This method fires an event and notifies any observer methods (observers). Now the observable part is completed, so it is time to create the observers that listens for our String events.

In Java EE the observers are marked with the @Observes annotation. The addition of the @Observes annotation to the method signature instructs the container that this method should act as an observer of events of the type it precedes.

We have three observers, ViningsFireStationBean , BrookhavenFireStationBean and DecaturFireStationBean:

@Named
@Dependent
public class ViningsFireStationBean {

 public void update(@Observes String arg) {
  System.out.println("Vinings fire department will go to " + arg);
 }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

 public void update(@Observes String arg) {
  System.out.println("Brookhaven fire department will go to " + arg);
 }
}

@Named
@Dependent
public class DecaturFireStationBean {

 public void update(@Observes String arg) {
  System.out.println("Decatur fire department will go to " + arg);
 }
}

So, the @Observes annotation precedes the type String and thus listens for events of that type. The @Observes annotation followed by an object type instruct the container will all the needed information.

In order to test it, we just need to report some fires. We can do this in several ways, but let's do it quickly via two JSF buttons:

<h:form>
 <h:commandButton value="Report Fire at Home Park Atlanta" 
                  action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA')}"/>
 <h:commandButton value="Report Fire at High Museum of Art" 
                  action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309')}"/>
</h:form>

If we suppose that the Report Fire at Home Park Atlanta button was pressed then the output will be:

Decatur fire department will go to Home Park Atlanta, GA
Vinings fire department will go to Home Park Atlanta, GA
Brookhaven fire department will go to Home Park Atlanta, GA

So, everything works as expected. The complete example is available here.

One step further and we will want to differentiate between the same object types of objects and set up different observers to listen for them. For example, we may need to distinguish between small fires and big fires. Depending on this aspect, a local fire station may send to the fire address one fire truck or multiple fire trucks. We can model this case via a qualifier:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface FireType {

 Type value();

 enum Type {
      SMALL, BIG
 }
}

The two enum types (SMALL and BIG)  will be used to act as annotation to mark the strings to be fired by the event instances. So, the MainFireStationBean will be:

@Named
@RequestScoped
public class MainFireStationBean {

 @Inject
 @FireType(Type.SMALL)
 Event<String> small;

 @Inject
 @FireType(Type.BIG)
 Event<String> big;

 public void fireStarted(String address, boolean t) {
  if (t) {
      small.fire(address);
  } else {
      big.fire(address);
  }
 }
}

Finally, add the annotations to the observer part:

@Named
@Dependent
public class ViningsFireStationBean {

 public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
  System.out.println("Vinings fire department will go to a small fire at " + arg);
 }

 public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
  System.out.println("Vinings fire department will go to a big fire at " + arg);
 }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

 public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
  System.out.println("Brookhaven fire department will go to a small fire at " + arg);
 }

 public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
  System.out.println("Brookhaven fire department will go to a big fire at " + arg);
 }
}

@Named
@Dependent
public class DecaturFireStationBean {

 public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
  System.out.println("Decatur fire department will go to a small fire at " + arg);
 }

 public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
  System.out.println("Decatur fire department will go to a big fire at " + arg);
 }
}

Now, let's report a big fire and a small fire:

<h:form>
 <h:commandButton value="Report a Small Fire at Home Park Atlanta" 
                  action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA', true)}"/>
 <h:commandButton value="Report a Big Fire at High Museum of Art" 
                  action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309', false)}"/>
</h:form>

In case of a small fire the output will be:

Brookhaven fire department will go to a small fire at Home Park Atlanta, GA
Vinings fire department will go to a small fire at Home Park Atlanta, GA
Decatur fire department will go to a small fire at Home Park Atlanta, GA

Note that in case of your own object types you don't need qualifiers. Since the object type is unique, you can fire/observe your own object types by using the object.

The complete example is available here.

JSF BOOKS COLLECTION

Postări populare

Visitors Starting 4 September 2015

Locations of Site Visitors