1    package com.instantbank.common.utilcomponents;
2    
3    import java.io.StringWriter;
4    import java.io.PrintWriter;
5    import java.io.File;
6    import java.io.IOException;
7    import java.io.ByteArrayInputStream;
8    
9    import java.text.BreakIterator;
10   
11   import java.util.Vector;
12   import java.util.Hashtable;
13   import java.util.Locale;
14   import java.util.Date;
15   import java.util.Calendar;
16   import java.util.GregorianCalendar;
17   
18   import javax.servlet.ServletContext;
19   import javax.servlet.http.HttpServletRequest;
20   import javax.servlet.http.HttpServletResponse;
21   import javax.servlet.http.HttpSession;
22   import javax.servlet.ServletException;
23   
24   import javax.naming.InitialContext;
25   import javax.naming.NamingException;
26   
27   import org.xml.sax.SAXException;
28   
29   import oracle.xml.parser.v2.XMLDocument;
30   import oracle.xml.parser.v2.DOMParser;
31   import oracle.xml.parser.v2.XSLException;
32   import oracle.xml.parser.v2.XMLParseException;
33   
34   
35   /**
36    * Various general algorithms implemented as static methods.
37    *
38    * @author InstantBank (Consuelo Franky, Rodrigo Lopez)
39    */
40   public class CommonUtil {
41   
42     /**
43      * A verification is OK.
44      */
45     public static final int OK = 1;
46   
47     // for debugging:
48     private static Debug debug = null;
49   
50     static {
51       debug = new Debug();
52       debug.setDebugginOn(true);
53       debug.setPreMessage("** CommonUtil: ");
54     }
55   
56   
57   
58     /**
59      *  method for instantiating and returning a context variable that is a
60      *  Hashtable with an entry for each company
61      *
62      * @param context web context
63      * @param variableName name of context variable (according to WebKeys
64      *      enumeration)
65      * @return Hashtable of the context variable
66      */
67     public static Hashtable getWebContextVariable(ServletContext context,
68                                                   String variableName) {
69       Hashtable table = null;
70       Object variable = context.getAttribute(variableName);
71       if(variable == null) {
72         table = new Hashtable();
73         context.setAttribute(variableName, table);
74       }
75       else {
76         table = (Hashtable)variable;
77       }
78       return table;
79     }
80   
81   
82     /**
83      *  method for putting the value of a company variable in a Hashtable context
84      *  variable (with an entry for each company)
85      *
86      * @param context web context
87      * @param companyId current company id
88      * @param tableName name of Hashtable context variable (according to
89      *      WebKeys enumeration)
90      * @param variableValue value of the company variable
91      */
92     public static void putVariableInContext
93       (ServletContext context, String companyId,
94        String tableName, Object variableValue) {
95       Hashtable tableVariable
96          = CommonUtil.getWebContextVariable(context, tableName);
97       tableVariable.put(companyId, variableValue);
98       context.setAttribute(tableName, tableVariable);
99     }
100  
101  
102    /**
103     *  method for putting in the current request, a company variable obtained
104     *  from a Hashtable context variable (with an entry for each company)
105     *
106     * @param request current request
107     * @param context web context
108     * @param companyId current company number
109     * @param tableName name of Hahtable context variable (according to
110     *      WebKeys enumeration)
111     * @param variableName name of the company variable (according to WebKeys
112     *      enumeration)
113     */
114    public static void putVariableInRequest
115      (HttpServletRequest request, ServletContext context,
116       String companyId, String tableName, String variableName) {
117      Hashtable tableVariable
118         = CommonUtil.getWebContextVariable(context, tableName);
119      Object variable = tableVariable.get(companyId);
120      request.setAttribute(variableName, variable);
121    }
122  
123  
124    /**
125     *  Produces --as a String-- the "stacktrace" corresponding to a Throwable
126     *  object (exceptions, errors).
127     *
128     * @param thw The throwed object.
129     * @return string corrsponding to stacktrace
130     */
131    public static String stackTraceToString(Throwable thw) {
132      StringWriter sw = new StringWriter();
133      PrintWriter pw = new PrintWriter(sw);
134      thw.printStackTrace(pw);
135      return sw.toString();
136    }
137  
138  
139    /**
140     *  Delete files from a temporal directory and its subdirectories,
141     *  excepting those with extensions ".log" or ".war".
142     *
143     * @param pathName Full path of the directory.
144     */
145    public static void cleanTemporaldirectory(String pathName) {
146      if(pathName != null) {
147        cleanTemporaldirectory(new File(pathName));
148      }
149    }
150  
151  
152    /**
153     *  Delete files from a temporal directory and all its subdirectories,
154     *  excepting those with extensions ".log" or ".war".
155     *
156     * @param dirPath Directory "abstract" path.
157     */
158    public static void cleanTemporaldirectory(File dirPath) {
159      if(dirPath == null) {
160        return;
161      }
162  
163      try {
164        String[] fileNames = dirPath.list();
165  
166        if(fileNames == null) {
167          return;
168        }
169  
170        for(int i = 0; i < fileNames.length; i++) {
171          File tf = new File(dirPath, fileNames[i]);
172          if(!fileNames[i].endsWith(".log") && !fileNames[i].endsWith(".war")
173            && !tf.isDirectory()) {
174            if(tf.delete()) {
175              //debug.println("file deleted: " + tf.getPath());
176            }
177            else {
178              tf.deleteOnExit();
179              debug.println("Couldn't be erased: " + tf.getPath());
180            }
181          }
182  
183          if(tf.isDirectory()) {
184            cleanTemporaldirectory(tf);
185          }
186  
187        }
188      }
189      catch(Exception e) {
190  
191      }
192    }
193  
194  
195    /**
196     *  find the current user from the HttpServletRequest:
197     *
198     * @param req request
199     * @return The userId value
200     * @exception Exception
201     */
202    public static String getUserId(HttpServletRequest req) throws Exception {
203      return (req.getUserPrincipal().getName());
204    }
205  
206  
207  
208    /**
209     *  determine if the current user belongs to a role
210     *
211     * @param req HTTP request
212     * @param rol J2EE role
213     * @return The userInRole value
214     * @exception Exception
215     */
216    public static boolean isUserInRole(HttpServletRequest req, String rol)
217       throws Exception {
218      return (req.isUserInRole(rol));
219      //TODO: to confirm
220    }
221  
222  
223    /**
224     *  Auxiliary method for building a XMLDocument from a XML string method for
225     *  building a XMLDocument from a XML string
226     *
227     * @param xmlData xml string
228     * @return XMLDocument corresponding to xmlData
229     * @exception XMLParseException
230     * @exception XSLException
231     * @exception SAXException
232     * @exception IOException
233     */
234    public static XMLDocument parseInfo(String xmlData)
235       throws XMLParseException, XSLException, SAXException, IOException {
236      DOMParser docParser = new DOMParser();
237      ByteArrayInputStream stream;
238      XMLDocument xmlDoc = null;
239  
240      stream = new ByteArrayInputStream(xmlData.getBytes());
241      docParser.setValidationMode(false);
242      docParser.parse(stream);
243      xmlDoc = docParser.getDocument();
244      return xmlDoc;
245    }
246  
247  
248    /**
249     *  parsing of a string composed of words
250     *
251     * @param keywordString string with words
252     * @param locale language
253     * @return Vector with words
254     */
255    public static Vector parseKeywords
256      (String keywordString, Locale locale) {
257  
258      if(keywordString != null) {
259        Vector keywords = new Vector();
260        BreakIterator breakIt = BreakIterator.getWordInstance(locale);
261        int index = 0;
262        int previousIndex = 0;
263        breakIt.setText(keywordString);
264        try {
265          while(index < keywordString.length()) {
266            previousIndex = index;
267            index = breakIt.next();
268            String word
269               = keywordString.substring(previousIndex, index);
270            if(!word.trim().equals("")) {
271              keywords.addElement(word);
272            }
273          }
274          return keywords;
275        }
276        catch(Throwable e) {
277          debug.println("Error while parsing search string:" + e.toString());
278        }
279  
280      }
281      return null;
282    }
283  
284  
285    /**
286     *  Method for transforming a String with special characters in a Java String.
287     *
288     * @param in is the string with special characters.
289     * @return another String with the special characters transformed.
290     */
291    public static String toSafeJavaString(String in) {
292      StringBuffer out = new StringBuffer();
293      boolean newLines = false;
294  
295      for(int i = 0; in != null && i < in.length(); i++) {
296        char c = in.charAt(i);
297        if(c == '"') {
298          out.append("\\\"");
299        }
300        else if(c == '\'') {
301          out.append("\\\'");
302        }
303        else if(c == '\\') {
304          out.append("\\\\");
305        }
306        else if(c == '\n') {
307          if(newLines) {
308            out.append('\n');
309          }
310        }
311        else if(c == '\r') {
312          if(newLines) {
313            out.append('\r');
314          }
315        }
316        else {
317          out.append(c);
318        }
319      }
320      return out.toString();
321    }
322  
323  
324    /**
325     *  Method for transforming in a String the ' character  in '' characters
326     * in order to be understood by Oracle
327     *
328     * @param in is the string with special characters.
329     * @return another String with the special characters transformed.
330     */
331    public static String toSafeOracleString(String in) {
332      StringBuffer out = new StringBuffer();
333  
334      for(int i = 0; in != null && i < in.length(); i++) {
335        char c = in.charAt(i);
336        if(c == '\'') {
337          out.append("''");
338        }
339        else {
340          out.append(c);
341        }
342      }
343      return out.toString();
344    }
345  
346  
347    /**
348     *  control time out in a servlet when it is invoked several times
349     *  without MVC participation, and in a separate window
350     *
351     * @param request HTTP request
352     * @param response HTTP response
353     * @param context Description of the Parameter
354     * @return true if timeout; false otherwise
355     * @exception IOException
356     * @exception ServletException
357     */
358    public static boolean controlTimeout
359      (HttpServletRequest request, HttpServletResponse response,
360       ServletContext context)
361       throws IOException, ServletException {
362      boolean existsTimeout = false;
363      HttpSession session = request.getSession();
364  
365      if(session.isNew()) {
366        context.getRequestDispatcher("/control_web/TimeOutPageOff.jsp")
367          .forward(request, response);
368        existsTimeout = true;
369      }
370      return existsTimeout;
371    }
372  
373  
374    /**
375     *  gets the value of an application property (of String type)
376     *
377     * @param nameJNDI JNDI name of the property
378     * @return corresponding String
379     */
380    public static String getApplicationProperty(String nameJNDI) {
381  
382      String value = null;
383      try {
384        InitialContext ic = new InitialContext();
385        value = (String)ic.lookup(nameJNDI);
386      }
387      catch(NamingException ne) {
388        debug.println(nameJNDI + " not specified in deployment descriptor: "
389          + " 'false' value will be used.");
390        value = "false";
391      }
392      return value;
393    }
394  
395  
396    /**
397     *  Determine if a selected Date is a workable day or not in a company calendar
398     *
399     * @param selectedDate selected Date to determine if it is workable day or not
400     * @param companyCalendar company calendar corresponding to year of
401     *           selectedDate; each day of year is a character :
402     *          'P' is it is workable(processing) day, 'N' otherwise
403     * @return true is selectedDate is workable day, false otherwise
404     */
405    public static boolean isWorkableDay(Date selectedDate,
406                                        String companyCalendar) {
407  
408      GregorianCalendar cal = new GregorianCalendar();
409      cal.clear();
410      cal.setTime(selectedDate);
411  
412      int dayOfyear = cal.get(Calendar.DAY_OF_YEAR);
413      char typeOfDay = companyCalendar.charAt(dayOfyear - 1);
414      if(typeOfDay == 'P') {
415        return true;
416      }
417      else {  // 'N'
418        return false;
419      }
420    }
421  
422  
423    /**
424     *  Add a workable offset (positive or negative) to  a selected date,  accordingly
425     *  to the calendars of a company.
426     *
427     * @param selectedDate selected Date
428     * @param companyCalendars hash table of company calendars:
429     *           key:   year (Integer),
430     *           value: String representing the year calendar
431     *                 (each day of year is a character :
432     *                  'P' is it is workable(processing) day, 'N' otherwise)
433     * @param offset Description of the Parameter
434     * @return Date corresponding to selectedDate + offset in workable days
435     *           (null if it can not be calculated because
436     *            companyCalendars are incomplete)
437     * @offset number (positive or negative) of workable days to add to selectedDate
438     */
439    public static Date workableOffset(Date selectedDate, int offset,
440                                      Hashtable companyCalendars) {
441  
442      Date resultingDate = null;
443  
444      int offsetSign = (offset > 0) ? 1 : -1;
445      int offsetWithoutSign = Math.abs(offset);
446  
447      GregorianCalendar cal = new GregorianCalendar();
448      cal.clear();
449      cal.setTime(selectedDate);
450  
451      int cont = 0;
452      while(cont < offsetWithoutSign) {
453        cal.add(Calendar.DAY_OF_YEAR, offsetSign * 1);
454        resultingDate = cal.getTime();
455        int resultingYear = cal.get(Calendar.YEAR);
456        String companyCalendar
457           = (String)companyCalendars.get(new Integer(resultingYear));
458        if(companyCalendar == null) {
459          return null;
460        }
461        if(isWorkableDay(resultingDate, companyCalendar)) {
462          cont++;
463        }
464      }
465      return resultingDate;
466    }
467  }
468  
469