Search code examples
jboss7.xjava-ee-6cdi

JEE6 Producer for NewCookie


I would like to create a CDI producer for

javax.ws.rs.core.NewCookie(java.lang.String name,
             java.lang.String value,
             java.lang.String path,
             java.lang.String domain,
             java.lang.String comment,
             int maxAge,
             boolean secure)

in such a way that the value will be different each time. I did some JEE6 a while ago but my memory is poor!

for ex. my producer for a simple logger is

@Produces
public Logger produceLogger(final InjectionPoint injectionPoint) {  
    final String injectingClass = injectionPoint.getMember().getDeclaringClass().getName();
    logger.info("creating logger for : " + injectingClass);
    return Logger.getLogger(injectingClass);  
}  

Any help appreciated


Solution

  • If you are able to calculate a unique value within a producer method without any additional parameters, then all you have to do is annotate a method with the return value NewCookie:

    @Produces NewCookie createCookie() {
      // create cookie and its value  
    }
    

    If you need to create it subject to some external parameter, then this producer method can have parameters like any other method - but, all of these are injection points and must be obtainable by the container.

    @Produces NewCookie createCookie(String value) {
      // create cookie with parameter value  
    }
    

    Now, a primitive type (as well as a String) has the problem, that you for sure have other instances of the same type with a different meaning, so you either use a special class like MyValue wrapping your String and use this as an injection point or annotate it with a custom annotation.

    @Produces NewCookie createCookie(@CookieValue String value) {
      // create cookie with parameter value  
    }
    

    Then of course, you need again some place where this injected value is produced.

    @Produces @CookieValue String createCookieValue() {
        // create value
    }
    

    Check out the JavaEE 6 Tutorial or the CDI Spec for more information.