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