1
votes

I have a server side event and receive an object in a @MessageDriven bean and I call a method in a @ApplicationScoped bean to prepare an E-Mail in a known locale. I need entries out of the recource bundle to prepare the dynamic message (many Translated Error Messages, the language is coded in the message object).

I try to build a message provider:

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

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

}

The Provider:

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.enterprise.inject.Produces;
import javax.inject.Named;

@Named
public class MessageProvider {

    private ResourceBundle bundle;

    public MessageProvider() {
        this.bundle = null;
    }



    @Produces @MessageBundle
    public ResourceBundle getBundle() {
        if (bundle == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            bundle = context.getApplication()
                     .getResourceBundle(context, "msgs");
        }
        return bundle;
    }
}

And I call it like this (simplified):

@Named
@ApplicationScoped
public class SmtpSenderBean {

    @EJB
    private SendMail sendmail;

    @Inject @MessageBundle
    private ResourceBundle bundle;

    public void send(Email mail, int errorCode){
        String subjectMsg = bundle.getString("event.smtp.subject");
        String bodyMsg = bundle.getString("event.smtp.body");
        mail.setSubject(MessageFormat.format(subjectMsg, errorCode));
        mail.setBody(MessageFormat.format(bodyMsg, errorCode))
        sendmail.send(mail);
    }
}

The FacesContext is always null, because the bean is not triggered by jsf. The object is received as server sided event via JMS. I found nothing about this problem. What is the preferred way in CDI to access a resource bundle in an @ApplicationScoped bean?

1
Check here: deltaspike.apache.org might be something very useful in thereKukeltje

1 Answers

0
votes

I solved it by accessing the resource bundle directly. I think this is best practice, because I found no example/documentation for that special case:

@Produces @MessageBundle
public ResourceBundle getBundle() {
    if (bundle == null) {
        bundle = ResourceBundle.getBundle("com.example.msgs");
    }
    return bundle;
}