added:
[mir.git] / source / mir / storage / Database.java
index 4c8638a..f86f043 100755 (executable)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2001-2005 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
  *
  * This file is part of Mir.
  *
@@ -19,8 +19,6 @@
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
  * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
  * and distribute linked combinations including the two.  You must obey the
  * GNU General Public License in all respects for all of the code used other than
  * the above mentioned libraries.  If you modify this file, you may extend this
@@ -35,7 +33,6 @@ import mir.entity.Entity;
 import mir.entity.EntityList;
 import mir.entity.StorableObjectEntity;
 import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
 import mir.storage.store.*;
 import mir.util.JDBCStringRoutines;
 import mir.util.StreamCopier;
@@ -45,7 +42,9 @@ import org.postgresql.PGConnection;
 import org.postgresql.largeobject.LargeObject;
 import org.postgresql.largeobject.LargeObjectManager;
 
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.sql.*;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
@@ -54,23 +53,22 @@ import java.util.*;
 /**
  * Implements database access.
  *
- * @version $Id: Database.java,v 1.44.2.31 2005/04/16 18:27:31 zapata Exp $
+ * @version $Id: Database.java,v 1.44.2.37 2006/12/25 20:10:22 zapata Exp $
  * @author rk
  * @author Zapata
  *
  */
 public class Database {
-       private static int DEFAULT_LIMIT = 20;
-  private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
+       private static final int DEFAULT_LIMIT = 20;
+  private static final Class GENERIC_ENTITY_CLASS = StorableObjectEntity.class;
   protected static final ObjectStore o_store = ObjectStore.getInstance();
-  private static final int _millisPerHour = 60 * 60 * 1000;
 
   protected LoggerWrapper logger;
 
   protected String mainTable;
   protected String primaryKeyField = "id";
 
-  protected List fieldNames;
+  private List fieldNames;
   private int[] fieldTypes;
   private Map fieldNameToType;
 
@@ -79,29 +77,26 @@ public class Database {
   //
   private Set binaryFields;
 
-  TimeZone timezone;
-  SimpleDateFormat internalDateFormat;
-  SimpleDateFormat userInputDateFormat;
+  private TimeZone timezone;
+  private SimpleDateFormat userInputDateFormat;
 
   public Database() throws DatabaseFailure {
     MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
     logger = new LoggerWrapper("Database");
     timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
-    internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-    internalDateFormat.setTimeZone(timezone);
 
     userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
     userInputDateFormat.setTimeZone(timezone);
 
     binaryFields = new HashSet();
 
-    String theAdaptorName = configuration.getString("Database.Adaptor");
+    String adapterName = configuration.getString("Database.Adaptor");
 
     try {
       entityClass = GENERIC_ENTITY_CLASS;
     }
     catch (Throwable e) {
-      logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
+      logger.error("Error in Database() constructor with " + adapterName + " -- " + e.getMessage());
       throw new DatabaseFailure("Error in Database() constructor.", e);
     }
   }
@@ -180,8 +175,6 @@ public class Database {
             break;
 
           case java.sql.Types.NUMERIC:
-            /** todo Numeric can be float or double depending upon
-             *  metadata.getScale() / especially with oracle */
             long outl = aResultSet.getLong(aFieldIndex);
 
             if (!aResultSet.wasNull()) {
@@ -246,20 +239,7 @@ public class Database {
 
             if (!aResultSet.wasNull()) {
               java.util.Date date = new java.util.Date(timestamp.getTime());
-
-              Calendar calendar = new GregorianCalendar();
-              calendar.setTime(date);
-              calendar.setTimeZone(timezone);
-              outValue = internalDateFormat.format(date);
-
-              int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
-              String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
-
-              if (offset<0)
-                outValue = outValue + "-";
-              else
-                outValue = outValue + "+";
-              outValue = outValue + tzOffset;
+              outValue = DatabaseHelper.convertDateToInternalRepresenation(date);
             }
 
             break;
@@ -268,7 +248,8 @@ public class Database {
             outValue = "<unsupported value>";
             logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")");
         }
-      } catch (SQLException e) {
+      }
+      catch (SQLException e) {
         throw new DatabaseFailure("Could not get Value out of Resultset -- ",
           e);
       }
@@ -278,7 +259,8 @@ public class Database {
   }
 
   /**
-   * Return an entity specified by id
+   * Return an entity specified by id, or <code>null</code> if no such
+   * entity exists.
    */
   public Entity selectById(String anId) throws DatabaseExc {
     if ((anId == null) || anId.equals("")) {
@@ -393,8 +375,6 @@ public class Database {
       anExtraTables=null;
     }
 
-    RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
-
     // check o_store for entitylist
     // only if no relational select
     if (anExtraTables==null) {
@@ -411,6 +391,8 @@ public class Database {
       }
     }
 
+    RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
+
     EntityList result = null;
     Connection connection = null;
 
@@ -577,7 +559,6 @@ public class Database {
 
     String returnId = null;
     Connection con = null;
-    PreparedStatement pstmt = null;
 
     try {
       String fieldName;
@@ -607,16 +588,9 @@ public class Database {
       anEntity.setId(returnId);
     }
     finally {
-      try {
-        freeConnection(con, pstmt);
-      }
-      catch (Exception e) {
-      }
-
-      freeConnection(con, pstmt);
+      freeConnection(con);
     }
 
-    /** todo store entity in o_store */
     return returnId;
   }
 
@@ -626,21 +600,17 @@ public class Database {
    * @param theEntity
    */
   public void update(Entity theEntity) throws DatabaseFailure {
-    Connection connection = null;
-
     invalidateStore();
 
     RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
 
-    String field;
-
     // build sql statement
     for (int i = 0; i < getFieldNames().size(); i++) {
-      field = (String) getFieldNames().get(i);
+      String field = (String) getFieldNames().get(i);
 
       if (!(field.equals(primaryKeyField) ||
-            field.equals("webdb_create") ||
-            field.equals("webdb_lastchange") ||
+            "webdb_create".equals(field) ||
+            "webdb_lastchange".equals(field) ||
             binaryFields.contains(field))) {
 
         if (theEntity.hasFieldValue(field)) {
@@ -677,6 +647,7 @@ public class Database {
         }
       }
     }
+    Connection connection = null;
 
     try {
       connection = obtainConnection();
@@ -713,7 +684,6 @@ public class Database {
   public boolean delete(String id) throws DatabaseFailure {
        invalidateObject(id);
        
-    /** todo could be prepared Statement */
     int resultCode = 0;
     Connection connection = obtainConnection();
     PreparedStatement statement = null;
@@ -1046,7 +1016,7 @@ public class Database {
       aStatement.close();
     }
     catch (Throwable t) {
-      logger.warn("Can't close statemnet: " + t.toString());
+      logger.warn("Can't close statement", t);
     }
 
     freeConnection(aConnection);