buildframework/helium/sf/java/jpa/src/com/nokia/helium/jpa/ORMEntityManager.java
changeset 628 7c4a911dc066
parent 588 c7c26511138f
child 629 541af5ee3ed9
equal deleted inserted replaced
588:c7c26511138f 628:7c4a911dc066
     1 /*
       
     2  * Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
       
     3  * All rights reserved.
       
     4  * This component and the accompanying materials are made available
       
     5  * under the terms of the License "Eclipse Public License v1.0"
       
     6  * which accompanies this distribution, and is available
       
     7  * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8  *
       
     9  * Initial Contributors:
       
    10  * Nokia Corporation - initial contribution.
       
    11  *
       
    12  * Contributors:
       
    13  *
       
    14  * Description:
       
    15  *
       
    16  */
       
    17 
       
    18 package com.nokia.helium.jpa;
       
    19 
       
    20 import org.apache.log4j.Logger;
       
    21 import javax.persistence.EntityManager;
       
    22 import javax.persistence.EntityManagerFactory;
       
    23 import java.util.Hashtable;
       
    24 import javax.persistence.Persistence;
       
    25 import org.eclipse.persistence.config.PersistenceUnitProperties;
       
    26 import java.io.File;
       
    27 import org.apache.commons.io.FileUtils;
       
    28 import com.nokia.helium.jpa.entity.Version;
       
    29 import java.sql.Connection;
       
    30 import java.sql.DriverManager;
       
    31 import java.sql.Statement;
       
    32 import java.sql.ResultSet;
       
    33 import java.sql.SQLException;
       
    34 import org.apache.tools.ant.BuildException;
       
    35 import java.io.IOException;
       
    36 
       
    37 /**
       
    38  * This class handles the generic ORM entity management.
       
    39  */
       
    40 public class ORMEntityManager {
       
    41 
       
    42     private static Logger log = Logger.getLogger(ORMEntityManager.class);
       
    43 
       
    44     private EntityManager entityManager;
       
    45     private EntityManagerFactory factory;
       
    46 
       
    47     private ORMCommitCount commitCountObject = new ORMCommitCount();
       
    48 
       
    49     private String urlPath;
       
    50     /**  
       
    51      * Constructor.
       
    52      * @param urlPath path for which entity manager to be
       
    53      * created.
       
    54      */
       
    55     @SuppressWarnings("unchecked")
       
    56     public ORMEntityManager(String urlPath) throws IOException {
       
    57         this.urlPath = urlPath;
       
    58         String name = "metadata";
       
    59         Hashtable persistProperties = new Hashtable();
       
    60         persistProperties.put("javax.persistence.jdbc.driver",
       
    61                 "org.apache.derby.jdbc.EmbeddedDriver");
       
    62         System.setProperty("derby.stream.error.file", System.getProperty("java.io.tmpdir") + File.separator + "derby.log");
       
    63         persistProperties.put("javax.persistence.jdbc.url",
       
    64                "jdbc:derby:" + urlPath);
       
    65         persistProperties.put(
       
    66                 PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT,
       
    67                 "false");
       
    68         persistProperties.put(
       
    69                 PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE,
       
    70                 "WEAK");
       
    71         persistProperties.put(PersistenceUnitProperties.BATCH_WRITING,
       
    72                 "JDBC");
       
    73         persistProperties.put("eclipselink.read-only", "true");
       
    74         persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
       
    75         File dbFile = new File(urlPath);
       
    76         if (dbFile.exists()) {
       
    77             log.debug("checking db integrity for :" + urlPath);
       
    78             if (!checkDatabaseIntegrity(urlPath)) {
       
    79                 log.debug("db integrity failed cleaning up old db");
       
    80                 try {
       
    81                     log.debug("deleting the url path" + urlPath);
       
    82                     FileUtils.forceDelete(dbFile);
       
    83                     log.debug("successfully removed the urlpath" + urlPath);
       
    84                 } catch (java.io.IOException iex) {
       
    85                     log.debug("deleting the db directory failed", iex);
       
    86                     throw new BuildException("failed deleting corrupted db", iex);
       
    87                 }
       
    88             } else {
       
    89                 log.debug("db exists and trying to create entity manager");
       
    90                 factory =
       
    91                     Persistence.createEntityManagerFactory(
       
    92                         name,
       
    93                         persistProperties);
       
    94                 entityManager = factory.createEntityManager();
       
    95                 entityManager.getTransaction().begin();
       
    96                 return;
       
    97             }
       
    98         }
       
    99         log.debug("url path not exists" + urlPath + "creating it");
       
   100         persistProperties.put("javax.persistence.jdbc.url",
       
   101                "jdbc:derby:" + urlPath + ";create=true");
       
   102         persistProperties.put(PersistenceUnitProperties.DDL_GENERATION,
       
   103                 "create-tables");
       
   104         persistProperties.put(
       
   105                 PersistenceUnitProperties.DDL_GENERATION_MODE,
       
   106                 "database");
       
   107         persistProperties.put(
       
   108                 PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT,
       
   109                 "false");
       
   110         persistProperties.put(
       
   111                 PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE,
       
   112                 "WEAK");
       
   113         persistProperties.put(PersistenceUnitProperties.BATCH_WRITING,
       
   114                 "JDBC");
       
   115         persistProperties.put("eclipselink.read-only", "true");
       
   116         factory = Persistence.createEntityManagerFactory(
       
   117                 name,
       
   118                 persistProperties);
       
   119         entityManager = factory.createEntityManager();
       
   120         entityManager.getTransaction().begin();
       
   121         entityManager.persist(new Version());
       
   122         entityManager.getTransaction().commit();
       
   123         entityManager.clear();
       
   124         entityManager.getTransaction().begin();
       
   125     }
       
   126 
       
   127     /**
       
   128      * Helper function to get the entity manager.
       
   129      * @return entity manager
       
   130      */
       
   131     public EntityManager getEntityManager() {
       
   132         //log.debug("ORMEntityManager: getEntityManager: " + entityManager);
       
   133         return entityManager;
       
   134     }
       
   135 
       
   136     /**
       
   137      * Helper function to get commit count object
       
   138      * @return commit count object used for cached persisting.
       
   139      */
       
   140     public ORMCommitCount getCommitCountObject() {
       
   141         return commitCountObject;
       
   142     }
       
   143 
       
   144     /**
       
   145      * If Any data to be commited, then this function
       
   146      * commits the data to the database.
       
   147      */
       
   148     public void commitToDB() {
       
   149         log.debug("commitToDB");
       
   150         if (entityManager.getTransaction().isActive()) {
       
   151             if (commitCountObject.isDatatoCommit()) {
       
   152                 entityManager.getTransaction().commit();
       
   153                 commitCountObject.reset();
       
   154                 entityManager.clear();
       
   155                 entityManager.getTransaction().begin();
       
   156             }
       
   157         }
       
   158     }
       
   159 
       
   160     /**
       
   161      * Finalizes the entity manager.
       
   162      */
       
   163     public void finalizeEntityManager() {
       
   164         log.debug("finalizeEntitymanager:" + entityManager);
       
   165         try {
       
   166             log.debug("finalizeEntitymanager: in a transaction.");
       
   167             if (entityManager != null && entityManager.getTransaction().isActive()) {
       
   168                 log.debug("finalizeEntitymanager: committing pending transaction.");
       
   169                 entityManager.getTransaction().commit();
       
   170             }
       
   171         } finally {
       
   172             log.debug("cleaning up entity manager instance" + entityManager);
       
   173             commitCountObject.reset();
       
   174             if (entityManager != null) {
       
   175                 log.debug("Closing the entityManager");
       
   176                 entityManager.clear();
       
   177                 entityManager.close();
       
   178                 entityManager = null;
       
   179             }
       
   180             if (factory != null) {
       
   181                 log.debug("closing the factory");
       
   182                 factory.close();
       
   183                 factory = null;
       
   184             }                    
       
   185             // Shutting down the derby database access, so files get unlocked. 
       
   186             try {
       
   187                 log.debug("shutting down the db");
       
   188                 DriverManager.getConnection("jdbc:derby:" + urlPath + ";shutdown=true");
       
   189             } catch (SQLException e) {
       
   190                 log.debug(e.getMessage());
       
   191             }        
       
   192         }
       
   193     }
       
   194 
       
   195     /**
       
   196      * Checks the database integrity.
       
   197      * @param urlPath - database path to be connected to.
       
   198      * @return boolean - true if db is valid false otherwise.
       
   199      */
       
   200     private boolean checkDatabaseIntegrity(String urlPath) {
       
   201         boolean result = false;
       
   202         loadDriver();
       
   203         Connection connection = null;
       
   204         try {
       
   205             connection = DriverManager.getConnection("jdbc:derby:" + urlPath);
       
   206             if (connection != null) {
       
   207                 Statement stmt = connection.createStatement();
       
   208                 ResultSet rs = stmt.executeQuery("select version from version");
       
   209                 int version = -1;
       
   210                 log.debug("result set executed");
       
   211                 if ( rs.next()) {
       
   212                     version = rs.getInt(1);
       
   213                 }
       
   214                 log.debug("result set executed : " + version);
       
   215                 rs.close();
       
   216                 stmt.close();
       
   217                 if (version == Version.DB_VERSION) {
       
   218                     result = true;
       
   219                 } else {
       
   220                     DriverManager.getConnection("jdbc:derby:;shutdown= true");
       
   221                 }
       
   222             }
       
   223         } catch (SQLException ex) {
       
   224             log.debug("exception while checking database integrity: ", ex);
       
   225             log.debug("shutting down embedded db");
       
   226             try {
       
   227                 DriverManager.getConnection("jdbc:derby:;shutdown= true");
       
   228             } catch (java.sql.SQLException sex) {
       
   229                 log.debug("normal exception during db shutdown");
       
   230             }
       
   231         } finally {
       
   232             try {
       
   233                 log.debug("closing the connection");
       
   234                 if (connection != null) {
       
   235                     connection.close();
       
   236                 }
       
   237             } catch (java.sql.SQLException sex) {
       
   238                 log.debug("normal exception during db shutdown");
       
   239             }
       
   240             connection = null;
       
   241         }
       
   242         //shutdown unloads the driver, driver need to be loaded again.
       
   243         return result;
       
   244     }
       
   245     private void loadDriver() {
       
   246         try
       
   247         {
       
   248             Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
       
   249         }
       
   250         catch (java.lang.ClassNotFoundException e)
       
   251         {
       
   252             throw new BuildException("JDBC Driver could not be found");
       
   253         }
       
   254     }
       
   255 
       
   256 }