1    package com.instantbank.common.utilcomponents;
2    
3    import java.util.ArrayList;
4    
5    // for looking the datasource:
6    import javax.naming.InitialContext;
7    import javax.naming.NamingException;
8    import javax.ejb.SessionContext;
9    import javax.ejb.EJBException;
10   
11   // for accessing DB:
12   import java.sql.Connection;
13   import java.sql.Statement;
14   import java.sql.PreparedStatement;
15   import java.sql.CallableStatement;
16   import java.sql.ResultSet;
17   import java.sql.SQLException;
18   import javax.sql.DataSource;
19   
20   // streams
21   import java.io.InputStream;
22   
23   // common util:
24   import com.instantbank.common.utilcomponents.CodeDescription;
25   import com.instantbank.common.utilcomponents.DAOException;
26   import com.instantbank.common.utilcomponents.CommonExceptionMessage;
27   import com.instantbank.common.utilcomponents.Debug;
28   
29   /**
30    *  This utility class for EJB tier components.
31    *
32    * @author Instant-bank (Consuelo Franky)
33    * @created October 2002
34    */
35   public final class DAOUtil extends Object {
36   
37     // METHODS FOR CONSULTING USER AND ROLE:
38   
39     /**
40      *  get the current user from the context
41      *
42      * @param context is the context
43      * @return The userId value
44      * @exception Exception
45      */
46     public static String getUserId(SessionContext context)
47        throws Exception {
48       String userId = context.getCallerPrincipal().getName();
49       return userId;
50     }
51   
52   
53     /**
54      *  determine if the current user belongs to a role
55      *
56      * @param context is the context
57      * @param rol role of sistem
58      * @return The userInRole value
59      * @exception Exception
60      */
61     public static boolean isUserInRole(SessionContext context, String rol)
62        throws Exception {
63       return (context.isCallerInRole(rol));
64     }
65   
66   
67     // METHODS FOR MANAGING DB CONNECTION:
68   
69     /**
70      *  Get the DataSource associated to a JNDIName
71      *
72      * @param dsName Description of the Parameter
73      * @return The dataSource value
74      * @exception DAOException
75      */
76     public static DataSource getDataSource(String dsName)
77        throws DAOException {
78       Debug debug = null;
79       debug = new Debug();
80       debug.setDebugginOn(true);
81       debug.setPreMessage("** JSPUtil:getDataSource ");
82   
83       DataSource datasource = null;
84       InitialContext ic = null;
85   
86       try {
87         ic = new InitialContext();
88         datasource = (DataSource)ic.lookup(dsName);
89       }
90       catch(NamingException ne) {
91         debug.println("Failed to lookup JDBC Datasource. Please double check that"
92           + "\nthe JNDI name defined in the resource-description of the "
93           + "\nEJB's weblogic-ejb-jar.xml file is the same as the JNDI name "
94           + "\nfor the Datasource defined in your config.xml.");
95         throw new DAOException
96           (CommonExceptionMessage.DB_NOT_FOUND
97           + dsName + ": <BR>" + ne.getMessage());
98       }
99       finally {
100        try {
101          if(ic != null) {
102            ic.close();
103          }
104        }
105        catch(NamingException ne) {
106          debug.println("Error closing context: " + ne.toString());
107          throw new DAOException(ne.getMessage());
108        }
109      }
110      return datasource;
111    }
112  
113  
114    /**
115     *  Get a database connection
116     *
117     * @param datasource Description of the Parameter
118     * @return The dBConnection value
119     * @exception DAOException
120     */
121    public static Connection getDBConnection(DataSource datasource)
122       throws DAOException {
123      Debug debug = null;
124      debug = new Debug();
125      debug.setDebugginOn(true);
126      debug.setPreMessage("** JSPUtil:getDBConnection ");
127  
128      Connection dbConnection = null;
129      try {
130        dbConnection = datasource.getConnection();
131      }
132      catch(SQLException se) {
133        debug.println("DBConnection not obtained because " + se);
134        throw new DAOException
135          (CommonExceptionMessage.DB_NOT_CONNECTION + se.getMessage());
136      }
137      return dbConnection;
138    }
139  
140  
141    /**
142     *  Close database connection associated to dbConnection attribute
143     *
144     * @param dbConnection Description of the Parameter
145     * @exception DAOException
146     */
147    public static void closeConnection(Connection dbConnection) throws DAOException {
148      try {
149        if(dbConnection != null && !dbConnection.isClosed()) {
150          dbConnection.close();
151        }
152      }
153      catch(SQLException se) {
154        throw new DAOException
155          (CommonExceptionMessage.DB_NOT_CLOSING + se.getMessage());
156      }
157    }
158  
159  
160    /**
161     *  Close a resultSet
162     *
163     * @param result is the ResultSet to close
164     * @exception DAOException
165     */
166    public static void closeResultSet(ResultSet result) throws DAOException {
167      try {
168        if(result != null) {
169          result.close();
170        }
171      }
172      catch(SQLException se) {
173        throw new DAOException
174          (CommonExceptionMessage.RS_NOT_CLOSING + se.getMessage());
175      }
176    }
177  
178  
179    /**
180     *  Close a statement
181     *
182     * @param stmt is the Statement to close
183     * @exception DAOException
184     */
185    public static void closeStatement(Statement stmt) throws DAOException {
186      try {
187        if(stmt != null) {
188          stmt.close();
189        }
190      }
191      catch(SQLException se) {
192        throw new DAOException
193          (CommonExceptionMessage.ST_NOT_CLOSING + se.getMessage());
194      }
195    }
196  
197  
198    /**
199     *  Close a PreparedStatement statement
200     *
201     * @param stmt is the PreparedStatement to close
202     * @exception DAOException
203     */
204    public static void closePreparedStatement(PreparedStatement stmt)
205       throws DAOException {
206      try {
207        if(stmt != null) {
208          stmt.close();
209        }
210      }
211      catch(SQLException se) {
212        throw new DAOException
213          (CommonExceptionMessage.PS_NOT_CLOSING + se.getMessage());
214      }
215    }
216  
217  
218    /**
219     *  Close a CallableStatement
220     *
221     * @param cstmt is the PreparedStatement to close
222     * @exception DAOException
223     */
224    public static void closeCallableStatement(CallableStatement cstmt)
225       throws DAOException {
226      try {
227        if(cstmt != null) {
228          cstmt.close();
229        }
230      }
231      catch(SQLException se) {
232        throw new DAOException
233          (CommonExceptionMessage.CS_NOT_CLOSING + se.getMessage());
234      }
235    }
236  
237  
238    // AUXILIARY METHODS FOR LOADING CODES FROM DB
239  
240    /**
241     *  Auxiliary for load a CodeDescription[] from DB
242     *
243     * @param ps auxiliary PreparedStatement
244     * @param rs auxiliary ResultSet
245     * @return CodeDescription[]
246     * @exception Exception
247     */
248    public static CodeDescription[] loadCodeDescription
249      (PreparedStatement ps, ResultSet rs) throws Exception {
250      CodeDescription[] answer = null;
251      ArrayList data = new ArrayList();
252  
253      ps.executeQuery();
254      rs = ps.getResultSet();
255      int i;
256      for(i = 0; rs.next(); i++) {
257        long code = rs.getInt(1);
258        String description = rs.getString(2);
259        data.add(new CodeDescription(code, description));
260      }
261  
262      int numTuples = i;
263      answer = new CodeDescription[numTuples];
264      for(int k = 0; k < answer.length; k++) {
265        answer[k] = (CodeDescription)data.get(k);
266      }
267      return answer;
268    }
269  
270  
271    // AUXILIARY METHODS FOR BLOB DATA
272  
273    /**
274     *  Obtain reference to BLOB field in the DB
275     *
276     * @param ps auxiliary PreparedStatement
277     * @param rs auxiliary ResultSet
278     * @return Blob reference to a Blob field
279     * @exception Exception
280     */
281    public static java.sql.Blob getBlobReference
282      (PreparedStatement ps, ResultSet rs) throws Exception {
283      ps.executeQuery();
284      rs = ps.getResultSet();
285      rs.next();
286      java.sql.Blob blobRef = rs.getBlob(1);
287      return blobRef;
288    }
289  
290  
291    /**
292     *  Write BLOB data on the DB
293     *
294     * @param blobRef reference to a Blob field
295     * @param is data (InputStream) to write in the Blob field
296     * @exception Exception
297     */
298    public static void writeBlobData(java.sql.Blob blobRef, InputStream is)
299       throws Exception {
300      java.io.OutputStream os =
301        ((weblogic.jdbc.common.OracleBlob)blobRef).getBinaryOutputStream();
302      byte[] buffer = new byte[65534];
303      int numBytes;
304      while((numBytes = is.read(buffer)) > 0) {
305        os.write(buffer, 0, numBytes);
306      }
307      os.flush();
308      os.close();
309    }
310  
311  
312    /**
313     *  Get BLOB text from DB
314     *
315     * @param blobRef reference to a Blob text field
316     * @param textArray is an auxiliary byte[] to receive the text
317     *                       from the Blob field
318     * @return String is the gotten text
319     * @exception Exception
320     */
321    public static String getBlobText(java.sql.Blob blobRef, byte[] textArray)
322       throws Exception {
323      byte[] inBytes = new byte[65534];
324      java.io.InputStream is = blobRef.getBinaryStream();
325      int contBytes = inputStreamTobyte(is, textArray, inBytes);
326      return (new String(textArray, 0, contBytes));
327    }
328  
329  
330    /**
331     *  Get BLOB image from DB
332     *
333     * @param blobRef reference to a Blob text field
334     * @param imageArray is an auxiliary byte[] to receive the image from
335     *                       the Blob field
336     * @return byte[] bytes of image
337     * @exception Exception
338     */
339    public static byte[] getBlobImage(java.sql.Blob blobRef, byte[] imageArray)
340       throws Exception {
341      byte[] inBytes = new byte[65534];
342      java.io.InputStream is = blobRef.getBinaryStream();
343      int contBytes = inputStreamTobyte(is, imageArray, inBytes);
344      byte[] finalImage = new byte[contBytes];
345      for(int i = 0; i < contBytes; i++) {
346        finalImage[i] = imageArray[i];
347      }
348      return finalImage;
349    }
350  
351  
352    /**
353     *  Get byte[] from InputStream
354     *
355     * @param is InputStream
356     * @param array byte[] for storing all the bytes of is
357     * @param buf auxiliary byte[] for reading from is
358     * @return number of bytes of is (int)
359     */
360    public static int inputStreamTobyte(InputStream is, byte[] array, byte[] buf) {
361  
362      Debug debug = null;
363      debug = new Debug();
364      debug.setDebugginOn(true);
365      debug.setPreMessage("** JSPUtil:inputStreamTobyte ");
366  
367      int contBytes = 0;
368      int k = 0;
369      int numBytes;
370      try {
371        while((numBytes = is.read(buf)) > 0) {
372          contBytes += numBytes;
373          for(int i = 0; i < numBytes; i++, k++) {
374            array[k] = buf[i];
375          }
376        }
377        return contBytes;
378      }
379      catch(Exception e) {
380        debug.println("Exception:  " + e.toString());
381        throw new EJBException(e);
382      }
383    }
384  
385  
386    /**
387     *  Debug: Shows first and last bytes of a <tt>byte[]</tt>
388     *
389     * @param array array of bytes
390     */
391    public static void showByteArray(byte[] array) {
392      Debug debug = null;
393      debug = new Debug();
394      debug.setDebugginOn(true);
395      debug.setPreMessage("** JSPUtil:showByteArray ");
396  
397      for(int i = 0; i < 5; i++) {
398        debug.println("byte[" + i + "] = " + array[i]);
399      }
400      for(int i = array.length - 5; i < array.length; i++) {
401        debug.println("byte[" + i + "] = " + array[i]);
402      }
403    }
404  }
405  
406