File Source: JPAPersistenceStrategy.java

         /* 
    P/P   *  Method: org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy$1__static_init
          */
     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   *  contributor license agreements.  The ASF licenses this file to You
     4   * under the Apache License, Version 2.0 (the "License"); you may not
     5   * use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.  For additional information regarding
    15   * copyright in this work, please see the NOTICE file in the top level
    16   * directory of this distribution.
    17   */
    18  
    19  package org.apache.roller.weblogger.business.jpa;
    20  
    21  import java.util.Collection;
    22  import java.util.Iterator;
    23  import java.util.Enumeration;
    24  import java.util.Properties;
    25  import java.io.InputStream;
    26  import java.io.IOException;
    27  import java.security.AccessController;
    28  import java.security.PrivilegedAction;
    29  import org.apache.commons.logging.Log;
    30  import org.apache.commons.logging.LogFactory;
    31  import org.apache.roller.weblogger.WebloggerException;
    32  import org.apache.roller.weblogger.config.WebloggerConfig;
    33  import javax.persistence.EntityManagerFactory;
    34  import javax.persistence.EntityManager;
    35  import javax.persistence.FlushModeType;
    36  import javax.persistence.Persistence;
    37  import javax.persistence.PersistenceException;
    38  import javax.persistence.Query;
    39  import javax.naming.InitialContext;
    40  import javax.naming.NamingException;
    41  
    42  import org.apache.roller.weblogger.business.DatabaseProvider;
    43  
    44  
    45  /**
    46   * Responsible for the lowest-level interaction with the JPA API.
    47   */
    48  @com.google.inject.Singleton
    49  public class JPAPersistenceStrategy {
    50      
             /* 
    P/P       *  Method: org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy__static_init
              * 
              *  Presumptions:
              *    org.apache.commons.logging.LogFactory:getFactory(...)@51 != null
              * 
              *  Postconditions:
              *    init'ed(logger)
              */
    51      private static Log logger = 
    52          LogFactory.getFactory().getInstance(JPAPersistenceStrategy.class);
    53      
    54      /**
    55       * The thread local EntityManager.
    56       */
    57      private final ThreadLocal threadLocalEntityManager = new ThreadLocal();
    58      
    59      /**
    60       * The EntityManagerFactory for this Roller instance.
    61       */
    62      private EntityManagerFactory emf = null;
    63      
    64              
    65      /**
    66       * Construct by finding JPA EntityManagerFactory.
    67       * @param dbProvider database configuration information for manual configuration.
    68       * @throws org.apache.roller.weblogger.WebloggerException on any error
    69       */
    70      @com.google.inject.Inject
             /* 
    P/P       *  Method: void org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy(DatabaseProvider)
              * 
              *  Preconditions:
              *    org/apache/roller/weblogger/config/WebloggerConfig.config != null
              *    org/apache/roller/weblogger/config/WebloggerConfig.log != null
              *    (soft) dbProvider != null
              *    (soft) init'ed(dbProvider.jdbcConnectionURL)
              *    (soft) init'ed(dbProvider.jdbcDriverClass)
              *    (soft) init'ed(dbProvider.jdbcPassword)
              *    (soft) init'ed(dbProvider.jdbcUsername)
              *    (soft) init'ed(dbProvider.jndiName)
              *    (soft) init'ed(dbProvider.type)
              *    (soft) logger != null
              * 
              *  Presumptions:
              *    java.security.AccessController:doPrivileged(...)@343 != null
              *    java.util.Enumeration:nextElement(...)@89 != null
              *    java.util.Properties:keys(...)@205 != null
              * 
              *  Postconditions:
              *    init'ed(this.emf)
              *    this.threadLocalEntityManager == &new ThreadLocal(JPAPersistenceStrategy#1)
              *    new ThreadLocal(JPAPersistenceStrategy#1) num objects == 1
              * 
              *  Test Vectors:
              *    java.lang.String:equals(...)@73: {0}, {1}
              *    java.lang.String:startsWith(...)@90: {1}, {0}
              *    java.lang.String:startsWith(...)@90: {0}, {1}
              *    java.util.Enumeration:hasMoreElements(...)@88: {0}, {1}
              */
    71      protected JPAPersistenceStrategy(DatabaseProvider dbProvider) throws WebloggerException {
    72          String jpaConfigurationType = WebloggerConfig.getProperty("jpa.configurationType");
    73          if ("jndi".equals(jpaConfigurationType)) {
    74              String emfJndiName = "java:comp/env/" + WebloggerConfig.getProperty("jpa.emf.jndi.name");
    75              try {
    76                  emf = (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
    77              } catch (NamingException e) {
    78                  throw new WebloggerException("Could not look up EntityManagerFactory in jndi at " + emfJndiName, e);
    79              }
    80          } else {
    81  
    82              // Pull in any properties defined in JMAEMF.properties config file
    83              Properties emfProps = loadPropertiesFromResourceName(
    84                      "JPAEMF.properties", getContextClassLoader());
    85  
    86              // Add all OpenJPA and Toplinks properties found in WebloggerConfig
    87              Enumeration keys = WebloggerConfig.keys();
    88              while (keys.hasMoreElements()) {
    89                  String key = (String) keys.nextElement();
    90                  if (key.startsWith("openjpa.") || key.startsWith("toplink.")) {
    91                      String value = WebloggerConfig.getProperty(key);
    92                      logger.info(key + ": " + value);
    93                      emfProps.setProperty(key, value);
    94                  }
    95              }
    96  
    97              if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {
    98                  // We're doing JNDI, so set OpenJPA JNDI name property
    99                  String jndiName = "java:comp/env/" + dbProvider.getJndiName();
   100                  emfProps.setProperty("openjpa.ConnectionFactoryName", jndiName);
   101  
   102              } else {
   103                  // So set JDBD properties for OpenJPA
   104                  emfProps.setProperty("openjpa.ConnectionDriverName", dbProvider.getJdbcDriverClass());
   105                  emfProps.setProperty("openjpa.ConnectionURL", dbProvider.getJdbcConnectionURL());
   106                  emfProps.setProperty("openjpa.ConnectionUserName", dbProvider.getJdbcUsername());
   107                  emfProps.setProperty("openjpa.ConnectionPassword", dbProvider.getJdbcPassword());
   108  
   109                  // And Toplink JPA
   110                  emfProps.setProperty("toplink.jdbc.driver", dbProvider.getJdbcDriverClass());
   111                  emfProps.setProperty("toplink.jdbc.url", dbProvider.getJdbcConnectionURL());
   112                  emfProps.setProperty("toplink.jdbc.user", dbProvider.getJdbcUsername());
   113                  emfProps.setProperty("toplink.jdbc.password", dbProvider.getJdbcPassword());
   114  
   115                  // And Hibernate JPA
   116                  emfProps.setProperty("hibernate.connection.driver_class", dbProvider.getJdbcDriverClass());
   117                  emfProps.setProperty("hibernate.connection.url", dbProvider.getJdbcConnectionURL());
   118                  emfProps.setProperty("hibernate.connection.username", dbProvider.getJdbcUsername());
   119                  emfProps.setProperty("hibernate.connection.password", dbProvider.getJdbcPassword());
   120              }
   121  
   122              try {
   123                  this.emf = Persistence.createEntityManagerFactory("RollerPU", emfProps);
   124              } catch (PersistenceException pe) {
   125                  logger.error("ERROR: creating entity manager", pe);
   126                  throw new WebloggerException(pe);
   127              }
   128          }
   129      }
   130                          
   131      /**
   132       * Flush changes to the datastore, commit transaction, release em.
   133       * @throws org.apache.roller.weblogger.WebloggerException on any error
   134       */
   135      public void flush() throws WebloggerException {
   136          try {
                     /* 
    P/P               *  Method: void flush()
                      * 
                      *  Preconditions:
                      *    this.threadLocalEntityManager != null
                      *    (soft) this.emf != null
                      * 
                      *  Presumptions:
                      *    javax.persistence.EntityManager:getTransaction(...)@138 != null
                      */
   137              EntityManager em = getEntityManager(true);
+  138              em.getTransaction().commit();
   139          } catch (PersistenceException pe) {
   140              throw new WebloggerException(pe);
   141          }
   142      }
   143      
   144      /**
   145       * Release database session, rolls back any uncommitted changes.
   146       */
   147      public void release() {
                 /* 
    P/P           *  Method: void release()
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Presumptions:
                  *    javax.persistence.EntityManager:getTransaction(...)@150 != null
                  */
   148          EntityManager em = getEntityManager(false);
   149          if (isTransactionActive(em)) {
+  150              em.getTransaction().rollback();
   151          }
+  152          em.close();
   153          setThreadLocalEntityManager(null);
   154      }
   155      
   156      /**
   157       * Store object using an existing transaction.
   158       * @param obj the object to persist
   159       * @return the object persisted
   160       * @throws org.apache.roller.weblogger.WebloggerException on any error
   161       */
   162      public Object store(Object obj) throws WebloggerException {
                 /* 
    P/P           *  Method: Object store(Object)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Postconditions:
                  *    return_value == obj
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    javax.persistence.EntityManager:contains(...)@164: {1}, {0}
                  */
   163          EntityManager em = getEntityManager(true);
+  164          if (!em.contains(obj)) {
   165              // If entity is not managed we can assume it is new
   166              em.persist(obj);
   167          }
   168          return obj;
   169      }
   170      
   171      /**
   172       * Remove object from persistence storage.
   173       * @param clazz the class of object to remove
   174       * @param id the id of the object to remove
   175       * @throws WebloggerException on any error deleting object
   176       */
   177      public void remove(Class clazz, String id) throws WebloggerException {
                 /* 
    P/P           *  Method: void remove(Class, String)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  */
   178          EntityManager em = getEntityManager(true);
+  179          Object po = em.find(clazz, id);
   180          em.remove(po);
   181      }
   182      
   183      /**
   184       * Remove object from persistence storage.
   185       * @param po the persistent object to remove
   186       * @throws org.apache.roller.weblogger.WebloggerException on any error
   187       */
   188      public void remove(Object po) throws WebloggerException {
                 /* 
    P/P           *  Method: void remove(Object)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  */
   189          EntityManager em = getEntityManager(true);
+  190          em.remove(po);
   191      }
   192      
   193      /**
   194       * Remove object from persistence storage.
   195       * @param pos the persistent objects to remove
   196       * @throws org.apache.roller.weblogger.WebloggerException on any error
   197       */
   198      public void removeAll(Collection pos) throws WebloggerException {
                 /* 
    P/P           *  Method: void removeAll(Collection)
                  * 
                  *  Preconditions:
                  *    pos != null
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Test Vectors:
                  *    java.util.Iterator:hasNext(...)@200: {0}, {1}
                  */
   199          EntityManager em = getEntityManager(true);
   200          for (Iterator iterator = pos.iterator(); iterator.hasNext();) {
   201              Object obj = iterator.next();
+  202              em.remove(obj);
   203          }
   204      }    
   205      
   206      /**
   207       * Retrieve object, no transaction needed.
   208       * @param clazz the class of object to retrieve
   209       * @param id the id of the object to retrieve
   210       * @return the object retrieved
   211       * @throws WebloggerException on any error retrieving object
   212       */
   213      public Object load(Class clazz, String id)
   214      throws WebloggerException {
                 /* 
    P/P           *  Method: Object load(Class, String)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   215          EntityManager em = getEntityManager(false);
+  216          return em.find(clazz, id);
   217      }
   218      
   219      /**
   220       * Return true if a transaction is active on the current EntityManager.
   221       * @param em the persistence manager
   222       * @return true if the persistence manager is not null and has an active
   223       *         transaction
   224       */
   225      private boolean isTransactionActive(EntityManager em) {
                 /* 
    P/P           *  Method: bool isTransactionActive(EntityManager)
                  * 
                  *  Presumptions:
                  *    javax.persistence.EntityManager:getTransaction(...)@229 != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    em: Inverse{null}, Addr_Set{null}
                  */
   226          if (em == null) {
   227              return false;
   228          }
   229          return em.getTransaction().isActive();
   230      }
   231      
   232      /**
   233       * Get the EntityManager associated with the current thread of control.
   234       * @param isTransactionRequired true if a transaction is begun if not
   235       * already active
   236       * @return the EntityManager
   237       */
   238      private EntityManager getEntityManager(boolean isTransactionRequired) {
                 /* 
    P/P           *  Method: EntityManager getEntityManager(bool)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Presumptions:
                  *    javax.persistence.EntityManager:getTransaction(...)@240 != null
                  *    javax.persistence.EntityManager:getTransaction(...)@241 != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    isTransactionRequired: {0}, {1}
                  *    javax.persistence.EntityTransaction:isActive(...)@240: {1}, {0}
                  */
   239          EntityManager em = getThreadLocalEntityManager();
+  240          if (isTransactionRequired && !em.getTransaction().isActive()) {
   241              em.getTransaction().begin();
   242          }
   243          return em;
   244      }
   245      
   246      /**
   247       * Get the current ThreadLocal EntityManager
   248       */
   249      private EntityManager getThreadLocalEntityManager() {
                 /* 
    P/P           *  Method: EntityManager getThreadLocalEntityManager()
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  * 
                  *  Test Vectors:
                  *    java.lang.ThreadLocal:get(...)@250: Inverse{null}, Addr_Set{null}
                  */
   250          EntityManager em = (EntityManager) threadLocalEntityManager.get();
   251          if (em == null) {
   252              em = emf.createEntityManager();
   253              threadLocalEntityManager.set(em);
   254          }
   255          return em;
   256      }
   257      
   258      /**
   259       * Set the current ThreadLocal EntityManager
   260       */
   261      private void setThreadLocalEntityManager(Object em) {
                 /* 
    P/P           *  Method: void setThreadLocalEntityManager(Object)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  */
   262          threadLocalEntityManager.set(em);
   263      }
   264      
   265      /**
   266       * Get named query with FlushModeType.COMMIT
   267       * @param queryName the name of the query
   268       * @throws org.apache.roller.weblogger.WebloggerException on any error
   269       */
   270      public Query getNamedQuery(String queryName)
   271      throws WebloggerException {
                 /* 
    P/P           *  Method: Query getNamedQuery(String)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Presumptions:
                  *    javax.persistence.EntityManager:createNamedQuery(...)@273 != null
                  *    init'ed(javax.persistence.FlushModeType.COMMIT)
                  * 
                  *  Postconditions:
                  *    (soft) return_value != null
                  */
   272          EntityManager em = getEntityManager(false);
+  273          Query q = em.createNamedQuery(queryName);
   274          // Never flush for queries. Roller code assumes this behavior
   275          q.setFlushMode(FlushModeType.COMMIT);
   276          return q;
   277      }
   278      
   279      /**
   280       * Create query from queryString with FlushModeType.COMMIT
   281       * @param queryString the quuery
   282       * @throws org.apache.roller.weblogger.WebloggerException on any error
   283       */
   284      public Query getDynamicQuery(String queryString)
   285      throws WebloggerException {
                 /* 
    P/P           *  Method: Query getDynamicQuery(String)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Presumptions:
                  *    javax.persistence.EntityManager:createQuery(...)@287 != null
                  *    init'ed(javax.persistence.FlushModeType.COMMIT)
                  * 
                  *  Postconditions:
                  *    (soft) return_value != null
                  */
   286          EntityManager em = getEntityManager(false);
+  287          Query q = em.createQuery(queryString);
   288          // Never flush for queries. Roller code assumes this behavior
   289          q.setFlushMode(FlushModeType.COMMIT);
   290          return q;
   291      }
   292      
   293      /**
   294       * Get named update query with default flush mode
   295       * @param queryName the name of the query
   296       * @throws org.apache.roller.weblogger.WebloggerException on any error
   297       */
   298      public Query getNamedUpdate(String queryName)
   299      throws WebloggerException {
                 /* 
    P/P           *  Method: Query getNamedUpdate(String)
                  * 
                  *  Preconditions:
                  *    this.threadLocalEntityManager != null
                  *    (soft) this.emf != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   300          EntityManager em = getEntityManager(true);
+  301          Query q = em.createNamedQuery(queryName);
   302          return q;
   303      }
   304      
   305      /**
   306       * Loads properties from given resourceName using given class loader
   307       * @param resourceName The name of the resource containing properties
   308       * @param cl Classloeder to be used to locate the resouce
   309       * @return A properties object
   310       * @throws WebloggerException
   311       */
   312      private static Properties loadPropertiesFromResourceName(
   313              String resourceName, ClassLoader cl) throws WebloggerException {
                 /* 
    P/P           *  Method: Properties loadPropertiesFromResourceName(String, ClassLoader)
                  * 
                  *  Preconditions:
                  *    cl != null
                  * 
                  *  Presumptions:
                  *    java.lang.ClassLoader:getResourceAsStream(...)@316 != null
                  * 
                  *  Postconditions:
                  *    return_value == &new Properties(loadPropertiesFromResourceName#1)
                  *    new Properties(loadPropertiesFromResourceName#1) num objects == 1
                  */
   314          Properties props = new Properties();
   315          InputStream in;
   316          in = cl.getResourceAsStream(resourceName);
   317          if (in == null) {
   318              //TODO: Check how i18n is done in roller
   319              throw new WebloggerException(
   320                      "Could not locate properties to load " + resourceName);
   321          }
   322          try {
   323              props.load(in);
   324          } catch (IOException ioe) {
   325              throw new WebloggerException(
   326                      "Could not load properties from " + resourceName);
   327          } finally {
   328              try {
   329                  in.close();
   330              } catch (IOException ioe) {
   331              }
   332          }
   333          
   334          return props;
   335      }
   336      
   337      /**
   338       * Get the context class loader associated with the current thread. This is
   339       * done in a doPrivileged block because it is a secure method.
   340       * @return the current thread's context class loader.
   341       */
   342      private static ClassLoader getContextClassLoader() {
                 /* 
    P/P           *  Method: ClassLoader getContextClassLoader()
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
   343          return (ClassLoader) AccessController.doPrivileged(
                         /* 
    P/P                   *  Method: void org.apache.roller.weblogger.business.jpa.JPAPersistenceStrategy$1()
                          */
   344                  new PrivilegedAction() {
   345              public Object run() {
                         /* 
    P/P                   *  Method: Object run()
                          * 
                          *  Presumptions:
                          *    java.lang.Thread:currentThread(...)@346 != null
                          * 
                          *  Postconditions:
                          *    init'ed(return_value)
                          */
   346                  return Thread.currentThread().getContextClassLoader();
   347              }
   348          });
   349      }  
   350  }








SofCheck Inspector Build Version : 2.18479
JPAPersistenceStrategy.java 2009-Jan-02 14:24:56
JPAPersistenceStrategy.class 2009-Sep-04 03:12:30
JPAPersistenceStrategy$1.class 2009-Sep-04 03:12:30