marți, 23 iunie 2015

[OmniFaces utilities 2.1] Get the qualifier annotation of the given qualifier class from the given injection point


[OmniFaces utilities] The getQualifier() method returns the qualifier annotation of the given qualifier class from the given injection point.

Method:
Usage:

In order to see at work the Beans#getQualifier(), let's define an annotation for injecting the value of an application initialization parameter in a bean. First, let's write the CDI annotation named, ContextParam:

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface ContextParam {

    @Nonbinding
    String name() default "";

}

Further, let's write the CDI producer for injecting the value of an application initialization parameter (declared in web.xml via <context-param>) in a bean as defined by the above ContextParam annotation:

public class ContextParameterProducer {

 public static final String CONTEXT_PARAM_NOT_FOUND = "CONTEXT_PARAM_NOT_FOUND";

  // Workaround for OpenWebBeans not properly passing it as produce() method argument.
  @SuppressWarnings("unused")     

  @Inject
  private InjectionPoint injectionPoint;

  @Produces
  @ContextParam
  public String produce(InjectionPoint injectionPoint) {
   ContextParam contextParam = Beans.getQualifier(injectionPoint, ContextParam.class);
   return contextParam.name().isEmpty() ? CONTEXT_PARAM_NOT_FOUND : Faces.getInitParameter(contextParam.name());
  }
}

You can find the complete application on GitHub.

Further, let's see it in a bean named, MyBean:

@Named
@RequestScoped
public class MyBean {

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

 @Inject
 @ContextParam(name = "javax.faces.PROJECT_STAGE")
 private String projectStage;

 @Inject
 @ContextParam(name = "dummy")
 private String dummy;

 @Inject
 @ContextParam
 private String none;

 public void doSomething() {
  LOG.log(Level.INFO, "projectStage = {0}", projectStage); // e.g. Development
  LOG.log(Level.INFO, "dummy = {0}", dummy); // null
  LOG.log(Level.INFO, "none = {0}", none); // CONTEXT_PARAM_NOT_FOUND
 }
}

Moreover, you may want to check the OmniFaces @Cookie implementation.

Niciun comentariu:

Trimiteți un comentariu