View Javadoc

1   /*
2    * Copyright 2007-2013 smartics, Kronseder & Reiner GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package de.smartics.exceptions.i18n.message;
17  
18  import java.util.Arrays;
19  import java.util.Collections;
20  import java.util.Enumeration;
21  import java.util.Locale;
22  import java.util.MissingResourceException;
23  import java.util.ResourceBundle;
24  import java.util.logging.Logger;
25  
26  /**
27   * Helper to render the messages of an exception in a structured multi-line
28   * text.
29   */
30  class StructuredTextHandler extends AbstractTextHandler
31  {
32    // ********************************* Fields *********************************
33  
34    // --- constants ------------------------------------------------------------
35  
36    /**
37     * Reference to the logger for this class.
38     */
39    private final Logger log = Logger.getLogger(StructuredTextHandler.class
40        .getName());
41  
42    // --- members --------------------------------------------------------------
43  
44    // ****************************** Initializer *******************************
45  
46    // ****************************** Constructors ******************************
47  
48    /**
49     * Default constructor.
50     *
51     * @param bundleBaseName the fully qualified base name of the bundle to use.
52     * @param resourceKey the localization key to fetch messages from message
53     *          bundles.
54     */
55    public StructuredTextHandler(final String bundleBaseName,
56        final String resourceKey)
57    {
58      super(bundleBaseName, resourceKey);
59    }
60  
61    // ****************************** Inner Classes *****************************
62  
63    // ********************************* Methods ********************************
64  
65    // --- init -----------------------------------------------------------------
66  
67    // --- get&set --------------------------------------------------------------
68  
69    // --- business -------------------------------------------------------------
70  
71    /**
72     * Returns the structured and localized message for the given locale,
73     * returning each part of information that is provided.
74     *
75     * @param bean the throwable to construct the localized message.
76     * @param locale the locale for which the message is requested.
77     * @param loader the loader to read the message bundle.
78     * @return returns the localized message of this exception.
79     */
80    @Override
81    public String getMessage(final Object bean, final Locale locale,
82        final ClassLoader loader)
83    {
84      final StringBuilder buffer = new StringBuilder();
85      final ResourceBundle messageBundle = fetchMessageBundle(locale, loader);
86  
87      appendMessage(bean, locale, loader, buffer, MessageType.TITLE, null);
88  
89      appendWhatHasHappendMessage(bean, locale, loader, buffer, messageBundle);
90  
91      appendMessage(bean, locale, loader, buffer,
92          MessageType.IMPLICATIONS_ON_CURRENT_TASK,
93          messageBundle.getString("header.implications"));
94  
95      appendMessage(bean, locale, loader, buffer, MessageType.WHAT_TO_DO_NOW,
96          messageBundle.getString("header.whatToDoNow"));
97  
98      appendMessage(bean, locale, loader, buffer, MessageType.URL,
99          messageBundle.getString("header.url"));
100 
101     return buffer.toString();
102   }
103 
104   private ResourceBundle fetchMessageBundle(final Locale locale,
105       final ClassLoader loader)
106   {
107     try
108     {
109       return ResourceBundle.getBundle(
110           "de.smartics.exceptions.i18n.message.StructuredTextBundle", locale,
111           loader);
112     }
113     catch (final MissingResourceException e)
114     {
115       log.warning(String.format(
116           "Cannot find resources on classpath. Continue without. Cause: %s",
117           e.getMessage()));
118       final ResourceBundle bundle = new ResourceBundle()
119       {
120 
121         @Override
122         protected Object handleGetObject(final String key)
123         {
124           return key;
125         }
126 
127         @Override
128         public Enumeration<String> getKeys()
129         {
130           return Collections.enumeration(Arrays.asList(
131               "header.whatHasHappened", "header.whatHasHappened.summary",
132               "header.whatHasHappened.details", "header.implications",
133               "header.whatToDoNow", "header.url"));
134         }
135       };
136       return bundle;
137     }
138   }
139 
140   private void appendWhatHasHappendMessage(final Object bean,
141       final Locale locale, final ClassLoader loader,
142       final StringBuilder buffer, final ResourceBundle messageBundle)
143   {
144     final String summaryMessage =
145         internalGetLocalizedMessage(bean, resourceKey, locale,
146             MessageType.SUMMARY, loader);
147     final String detailsMessage =
148         internalGetLocalizedMessage(bean, resourceKey, locale,
149             MessageType.DETAILS, loader);
150     if (summaryMessage != null || detailsMessage != null)
151     {
152       buffer.append(' ')
153           .append(messageBundle.getString("header.whatHasHappened"))
154           .append('\n');
155       if (summaryMessage != null)
156       {
157         buffer.append("  ");
158         if (detailsMessage != null) // NOPMD
159         {
160           buffer.append(
161               messageBundle.getString("header.whatHasHappened.summary"))
162               .append(": ");
163         }
164 
165         buffer.append(summaryMessage).append('\n');
166       }
167       if (detailsMessage != null)
168       {
169         buffer.append("  ");
170         if (summaryMessage != null) // NOPMD
171         {
172           buffer.append(
173               messageBundle.getString("header.whatHasHappened.details"))
174               .append(": ");
175         }
176         buffer.append(detailsMessage).append('\n');
177       }
178     }
179   }
180 
181   // CHECKSTYLE:OFF
182   private void appendMessage(final Object bean, final Locale locale,
183       final ClassLoader loader, final StringBuilder buffer,
184       final MessageType type, final String headline)
185   {
186     final String message =
187         internalGetLocalizedMessage(bean, resourceKey, locale, type, loader);
188     if (message != null)
189     {
190       if (headline != null)
191       {
192         buffer.append(' ').append(headline).append("\n  ");
193       }
194 
195       buffer.append(message).append('\n');
196     }
197   }
198   // CHECKSTYLE:OFF
199 
200   // --- object basics --------------------------------------------------------
201 
202 }