View Javadoc
1   package eu.sydisnet.blog.samples.deltaspike.cdi12.boundary;
2   
3   import eu.sydisnet.blog.samples.deltaspike.cdi12.control.MessageFormatter;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import javax.annotation.PostConstruct;
8   import javax.annotation.PreDestroy;
9   import javax.inject.Inject;
10  import java.lang.invoke.MethodHandles;
11  
12  /**
13   * Component whose responsibility is to send to the client a welcome message.
14   *
15   * @since       CDI 1.2
16   * @author      sydisnet
17   * @version     1.0.0
18   */
19  @Unique
20  public class SingletonHelloServiceV2 {
21  
22      /**
23       * Static Logger.
24       */
25      private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
26  
27      /**
28       * Constant used by the service when userName is not defined by the client.
29       */
30      private static final String UNKNOWN_USERNAME = "M. John Doe";
31  
32      /**
33       * The default message template assigned when the bean is loaded.
34       */
35      private String defaultMessage;
36  
37      /**
38       * Delegate service.
39       */
40      @Inject
41      private MessageFormatter messageFormatter;
42  
43      /**
44       * Method called by the CDI container when the bean is retrieved from
45       * {@link javax.enterprise.inject.spi.BeanManager}. See the JSR 250 Callback {@link javax.annotation.PostConstruct}
46       * annotation.
47       */
48      @PostConstruct
49      void initBean() {
50          defaultMessage = "Welcome %s !";
51  
52          LOG.info(String.format("##### %s stopped !", MethodHandles.lookup().lookupClass().getSimpleName()));
53      }
54  
55      /**
56       * Method called by the CDI container before the destruction of the bean from the
57       * {@link javax.enterprise.inject.spi.BeanManager}. See the JSR 250 Callback {@link javax.annotation.PreDestroy}
58       * annotation.
59       */
60      @PreDestroy
61      void tearDown() {
62          LOG.info(String.format("##### %s stopped !", MethodHandles.lookup().lookupClass().getSimpleName()));
63      }
64  
65      /**
66       * Service called by <strong>client-tier</strong> in order to send a welcome message.
67       *
68       * @param userName the name of the user
69       * @return the welcome message
70       */
71      public String sayHello(final String userName) {
72          if (userName == null || userName.isEmpty()) {
73              return messageFormatter.format(defaultMessage, UNKNOWN_USERNAME);
74          }
75  
76          return messageFormatter.format(defaultMessage, userName);
77      }
78  }