View Javadoc

1   /**
2    * 2009, Digitalis Informatica. All rights reserved. Distribuicao e Gestao de Informatica, Lda. Estrada de Paco de Arcos
3    * num.9 - Piso -1 2780-666 Paco de Arcos Telefone: (351) 21 4408990 Fax: (351) 21 4408999 http://www.digitalis.pt
4    */
5   
6   package pt.digitalis.dif.utils.templates;
7   
8   import java.io.BufferedReader;
9   import java.io.IOException;
10  import java.io.InputStream;
11  import java.io.InputStreamReader;
12  import java.net.URL;
13  import java.net.URLConnection;
14  import java.util.Map;
15  import java.util.Map.Entry;
16  
17  import pt.digitalis.dif.startup.DIFGeneralConfigurationParameters;
18  import pt.digitalis.dif.utils.logging.DIFLogger;
19  
20  /**
21   * Utilities for template loading and parsing
22   * 
23   * @author Pedro Viegas <a href="mailto:pviegas@digitalis.pt">pviegas@digitalis.pt</a><br/>
24   * @created Mar 3, 2009
25   */
26  public class TemplateUtils {
27  
28      /**
29       * Get a Remote template
30       * 
31       * @param url
32       *            the template location the language tranlation
33       * @return content to String
34       * @throws Exception
35       *             if an Exception occurrs
36       */
37      static public String getRemoteTemplate(String url) throws Exception
38      {
39          URL website;
40  
41          website = new URL(url);
42  
43          URLConnection connection = website.openConnection();
44          BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
45  
46          StringBuilder response = new StringBuilder();
47          String inputLine;
48  
49          while ((inputLine = in.readLine()) != null)
50              response.append(inputLine);
51  
52          in.close();
53  
54          return response.toString();
55      }
56  
57      /**
58       * Get the remote template for language
59       * 
60       * @param url
61       *            the url
62       * @param language
63       *            the language
64       * @return the content
65       */
66      static public String getRemoteTemplate(String url, String language)
67      {
68          String result = null;
69  
70          if (language == null)
71          {
72              try
73              {
74                  return getRemoteTemplate(url);
75              }
76              catch (Exception e)
77              {
78                  DIFLogger.getLogger().debug(e);
79                  return null;
80              }
81          }
82  
83          // Try to get content for specific language
84          try
85          {
86              result = getRemoteTemplate(url + "." + language);
87          }
88          catch (Exception e)
89          {
90              DIFLogger.getLogger().debug(e);
91          }
92  
93          if (result != null)
94          {
95              return result;
96          }
97          else
98          {
99              // Try to get content for default language
100             try
101             {
102                 result = getRemoteTemplate(url + "."
103                         + DIFGeneralConfigurationParameters.getInstance().getDefaultLanguage());
104             }
105             catch (Exception e)
106             {
107                 DIFLogger.getLogger().debug(e);
108             }
109         }
110 
111         if (result != null)
112         {
113             return result;
114         }
115         else
116         {
117             // Try to get content without language
118             try
119             {
120                 result = getRemoteTemplate(url);
121             }
122             catch (Exception e)
123             {
124                 DIFLogger.getLogger().debug(e);
125             }
126         }
127 
128         return result;
129     }
130 
131     /**
132      * Reads a given template and it's content
133      * 
134      * @param inputStream
135      *            the input stream for the resource
136      * @param params
137      *            the parameters to parse the template and replace their values
138      * @return the resource content
139      * @throws IOException
140      *             if any error happened when reading the resource
141      */
142     static private StringBuffer getTemplateContent(InputStream inputStream, Map<String, String> params)
143             throws IOException
144     {
145         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
146 
147         StringBuffer buffer = new StringBuffer();
148         String line = parseTemplateLine(bufferedReader.readLine(), params);
149         while (line != null)
150         {
151             buffer.append(line);
152             line = parseTemplateLine(bufferedReader.readLine(), params);
153         }
154 
155         return buffer;
156     }
157 
158     /**
159      * Reads a given template and it's content
160      * 
161      * @param resource
162      *            the resource name
163      * @param params
164      *            the parameters to parse the template and replace their values
165      * @return the content of the given resource
166      * @throws IOException
167      *             if any error happened when reading the resource
168      */
169     static public StringBuffer getTemplateContent(String resource, Map<String, String> params) throws IOException
170     {
171         return getTemplateContent(getTemplateStream(resource), null);
172     }
173 
174     /**
175      * Reads a given template and it's content
176      * 
177      * @param resource
178      *            the resource name
179      * @param language
180      *            the default language to get the template in
181      * @param params
182      *            the parameters to parse the template and replace their values
183      * @return the content of the given resource
184      * @throws IOException
185      *             if any error happened when reading the resource
186      */
187     static public StringBuffer getTemplateContent(String resource, String language, Map<String, String> params)
188             throws IOException
189     {
190 
191         if (language != null)
192         {
193             InputStream fileInput = Thread.currentThread().getContextClassLoader()
194                     .getResourceAsStream(resource + "." + language);
195 
196             if (fileInput == null)
197                 fileInput = Thread
198                         .currentThread()
199                         .getContextClassLoader()
200                         .getResourceAsStream(
201                                 resource + "." + DIFGeneralConfigurationParameters.getInstance().getDefaultLanguage());
202 
203             if (fileInput == null)
204                 fileInput = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
205 
206             return getTemplateContent(fileInput, params);
207         }
208         else
209             return getTemplateContent(resource, params);
210     }
211 
212     /**
213      * Returns a given template input stream
214      * 
215      * @param resource
216      *            the resource name
217      * @return the stream
218      * @throws IOException
219      *             if any error happened when reading the resource
220      */
221     static public InputStream getTemplateStream(String resource) throws IOException
222     {
223         // TODO: Must define the correct codepage to load. Is not picking up the ISO-8859-1!!!
224         return Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
225     }
226 
227     /**
228      * Parses a given line for parameters, and replaces them with their respective values
229      * 
230      * @param line
231      *            the line to parse and replace parameter values
232      * @param params
233      *            the parameters to parse the template and replace their values
234      * @return the resource content
235      */
236     static public String parseTemplateLine(String line, Map<String, String> params)
237     {
238         if (line != null && !"".equals(line) && params != null)
239         {
240             for (Entry<String, String> param: params.entrySet())
241                 line = line.replaceAll("\\$\\{" + param.getKey() + "\\}", param.getValue());
242         }
243 
244         return line;
245     }
246 }