]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
NOJIRA - refactored JpaStorageClient, extracted out utilities into JpaStorageUtils...
authorSanjay Dalal <sanjay.dalal@berkeley.edu>
Wed, 21 Apr 2010 20:45:48 +0000 (20:45 +0000)
committerSanjay Dalal <sanjay.dalal@berkeley.edu>
Wed, 21 Apr 2010 20:45:48 +0000 (20:45 +0000)
DocumentFilter#getQueryParams returns empty list of query para values but not null
test: all tests, account and authorization-mgt

M    account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java
M    account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java
M    account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java
M    account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java
M    authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java
M    authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java
M    common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java
M    common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java
A    common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java
M    common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java

services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java
services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java
services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java
services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java
services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java
services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java
services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java
services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java
services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java
services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java [new file with mode: 0644]

index 82b9ae8411b9114b5b9e2a613cf2d50e96b8527f..c72d69122c9b566a3c3af2edaa986bdd01d410f5 100644 (file)
@@ -106,7 +106,7 @@ public class AccountRoleSubResource
         ctx.setProperty("entity-name", AccountRoleRel.class.getName());
         //subject name is necessary to indicate if role or account is a subject
         ctx.setProperty("subject", subject);
-        //set context that for the relationship query
+        //set context for the relationship query
         ctx.setProperty("objectId", "account_id");
         return ctx;
     }
index 3e87d65ce4bf20bad53c3012e851092b9f11241a..8d70d594f91703227ffd1151aed2f6d574a0e814 100644 (file)
@@ -52,7 +52,7 @@ public class AccountJpaFilter extends JpaDocumentFilter {
 
         String screenName = null;
         List<String> snvals = getQueryParam(AccountStorageConstants.Q_SCREEN_NAME);
-        if (snvals != null) {
+        if (null != snvals && snvals.size() > 0) {
             screenName = snvals.get(0);
         }
         if (null != screenName && !screenName.isEmpty()) {
@@ -67,7 +67,7 @@ public class AccountJpaFilter extends JpaDocumentFilter {
 
         String uid = null;
         List<String> uidvals = getQueryParam(AccountStorageConstants.Q_USER_ID);
-        if (uidvals != null) {
+        if (null != uidvals && uidvals.size() > 0) {
             uid = uidvals.get(0);
         }
         if (null != uid && !uid.isEmpty()) {
@@ -86,7 +86,7 @@ public class AccountJpaFilter extends JpaDocumentFilter {
 
         String email = null;
         List<String> emailvals = getQueryParam(AccountStorageConstants.Q_EMAIL);
-        if (emailvals != null) {
+        if (null != emailvals && emailvals.size() > 0) {
             email = emailvals.get(0);
         }
         if (null != email && !email.isEmpty()) {
index 81e0909e092a49b05a4081f7aeb572f76d96cbe7..eb7374d4e7aef751cc281805f29c3751eb9e188c 100644 (file)
@@ -27,7 +27,6 @@ import java.util.Date;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.Query;
-import org.apache.commons.codec.binary.Base64;
 import org.collectionspace.services.account.AccountsCommon;
 import org.collectionspace.services.authentication.User;
 import org.collectionspace.services.common.context.ServiceContext;
@@ -40,6 +39,7 @@ import org.collectionspace.services.common.document.DocumentWrapper;
 import org.collectionspace.services.common.document.DocumentWrapperImpl;
 import org.collectionspace.services.common.security.SecurityUtils;
 import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl;
+import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -77,7 +77,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
             DocumentWrapper<AccountsCommon> wrapDoc =
                     new DocumentWrapperImpl<AccountsCommon>(account);
             handler.handle(Action.CREATE, wrapDoc);
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             em.getTransaction().begin();
             //if userid and password are given, add to default id provider
@@ -109,7 +109,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (em != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -135,7 +135,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
                     new DocumentWrapperImpl<AccountsCommon>(account);
             setCsid(account, id); //set id just in case it was not populated by consumer
             handler.handle(Action.UPDATE, wrapDoc);
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             em.getTransaction().begin();
             AccountsCommon accountFound = getAccount(em, id);
@@ -169,7 +169,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -189,7 +189,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
         EntityManagerFactory emf = null;
         EntityManager em = null;
         try {
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             //TODO investigate if deep delete is possible
             //query an delete is inefficient
@@ -242,7 +242,7 @@ public class AccountStorageClient extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
index 95e77c2924d254c96e7d26768c1a9991cda39dd7..c5bb8ef45ca50ead36a5174faf0a8a405d1c2dd3 100644 (file)
@@ -52,8 +52,6 @@ package org.collectionspace.services.account.storage;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
 import org.collectionspace.services.account.AccountTenant;
 import org.collectionspace.services.account.AccountsCommon;
 import org.collectionspace.services.account.Tenant;
@@ -61,7 +59,7 @@ import org.collectionspace.services.common.context.ServiceContext;
 import org.collectionspace.services.common.document.DocumentHandler.Action;
 import org.collectionspace.services.common.document.InvalidDocumentException;
 import org.collectionspace.services.common.document.ValidatorHandler;
-import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl;
+import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -152,28 +150,19 @@ public class AccountValidatorHandler implements ValidatorHandler {
 
     private boolean isInvalidTenant(List<AccountTenant> atList, StringBuilder msgBldr) {
         boolean invalid = false;
-        JpaStorageClientImpl store = new JpaStorageClientImpl();
-        EntityManagerFactory emf = store.getEntityManagerFactory();
-        EntityManager em = emf.createEntityManager();
-        try {
-            for (AccountTenant at : atList) {
-                String tid = at.getTenantId();
-                if (tid == null || tid.isEmpty()) {
-                    invalid = true;
-                    msgBldr.append("\n tenant : tenantId is missing");
-                    break;
-                }
-                Tenant tenantFound = em.find(Tenant.class, tid);
-                if (tenantFound == null) {
-                    invalid = true;
-                    msgBldr.append("\n tenant : tenantId=" + tid
-                            + " not found");
-                    break;
-                }
+        for (AccountTenant at : atList) {
+            String tid = at.getTenantId();
+            if (tid == null || tid.isEmpty()) {
+                invalid = true;
+                msgBldr.append("\n tenant : tenantId is missing");
+                break;
             }
-        } finally {
-            if (em != null) {
-                store.releaseEntityManagerFactory(emf);
+            Tenant tenantFound = (Tenant) JpaStorageUtils.getEntity(tid, Tenant.class);
+            if (tenantFound == null) {
+                invalid = true;
+                msgBldr.append("\n tenant : tenantId=" + tid
+                        + " not found");
+                break;
             }
         }
         return invalid;
index 807d5f4c156cada0742238818d648f82d3f0b72e..e982bb76ab25c44e7e8cab230912a76c0e4f2bae 100644 (file)
@@ -58,7 +58,7 @@ public class PermissionJpaFilter extends JpaDocumentFilter {
 
         String resName = null;
         List<String> rn = getQueryParam(PermissionStorageConstants.Q_RESOURCE_NAME);
-        if (null != rn) {
+        if (null != rn && rn.size() > 0) {
             resName = rn.get(0);
         }
         if (null != resName && !resName.isEmpty()) {
index cc30c603ce3f5f23f10e886c564ba39c8d7569b9..687b529d71a7be25aac4c117f0908b2d75481fd3 100644 (file)
@@ -51,7 +51,7 @@ public class RoleJpaFilter extends JpaDocumentFilter {
 
         String roleName = null;
         List<String> rn = getQueryParam(RoleStorageConstants.Q_ROLE_NAME);
-        if (null != rn) {
+        if (null != rn && rn.size() > 0) {
             roleName = rn.get(0);
         }
         if (null != roleName && !roleName.isEmpty()) {
index 87f17e593f2e5603a2a8b77add7a7e40aa473fde..e1092fcfde94c2eb37e52029dc0814f163649b30 100644 (file)
@@ -43,8 +43,11 @@ public class DocumentFilter {
     protected int startPage;           // Pagination offset for list results\r
     protected int pageSize;                    // Pagination limit for list results\r
     private boolean pageSizeDirty = false; // True if default page size explicitly set/overridden\r
-    private MultivaluedMap<String, String> queryParams = null;\r
 \r
+    //queryParams is not initialized as it would require a multi-valued map implementation\r
+    //unless it is used from opensource lib...this variable holds ref to\r
+    //implementation available in JBoss RESTeasy\r
+    private MultivaluedMap<String, String> queryParams = null;\r
 \r
     /**\r
      * ParamBinding encapsulates parameter binding for query\r
@@ -87,17 +90,17 @@ public class DocumentFilter {
             this.value = value;\r
         }\r
     }\r
-    \r
+\r
     /**\r
      * Instantiates a new document filter.\r
      * \r
      * @param ctx the ctx\r
      */\r
     public DocumentFilter(ServiceContext ctx) {\r
-       this.setPageSize(ctx.getServiceBindingPropertyValue(\r
-                       DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY));\r
+        this.setPageSize(ctx.getServiceBindingPropertyValue(\r
+                DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY));\r
     }\r
-    \r
+\r
     public DocumentFilter() {\r
         this("", 0, defaultPageSize);                  // Use empty string for easy concatenation\r
     }\r
@@ -113,16 +116,18 @@ public class DocumentFilter {
      * \r
      * @param queryParams the query params\r
      */\r
-    public void setPagination(MultivaluedMap<String, String> queryParams) {            \r
-       //\r
-       // Bail if there are no params\r
-       //\r
-       if (queryParams == null) return;\r
-       \r
+    public void setPagination(MultivaluedMap<String, String> queryParams) {\r
         //\r
-       // Set the page size\r
-       //\r
-       String pageSizeStr = null;\r
+        // Bail if there are no params\r
+        //\r
+        if (queryParams == null) {\r
+            return;\r
+        }\r
+\r
+        //\r
+        // Set the page size\r
+        //\r
+        String pageSizeStr = null;\r
         List<String> list = queryParams.remove(PAGE_SIZE_PARAM);\r
         if (list != null) {\r
             pageSizeStr = list.get(0);\r
@@ -214,9 +219,9 @@ public class DocumentFilter {
     public int getPageSize() {\r
         return pageSize;\r
     }\r
-    \r
+\r
     public boolean getPageSizeDirty() {\r
-       return this.getPageSizeDirty();\r
+        return this.getPageSizeDirty();\r
     }\r
 \r
     /**\r
@@ -231,17 +236,17 @@ public class DocumentFilter {
      * @param pageSize the max number of items to return for list requests\r
      */\r
     public void setPageSize(String pageSizeStr) {\r
-       int pageSize = this.defaultPageSize;\r
+        int pageSize = this.defaultPageSize;\r
         if (pageSizeStr != null) {\r
             try {\r
-               pageSize = Integer.valueOf(pageSizeStr);\r
+                pageSize = Integer.valueOf(pageSizeStr);\r
             } catch (NumberFormatException e) {\r
-               //FIXME This should cause a warning in the log file and should result in the\r
-               //FIXME page size being set to the default.  We don't need to throw an exception here.\r
+                //FIXME This should cause a warning in the log file and should result in the\r
+                //FIXME page size being set to the default.  We don't need to throw an exception here.\r
                 throw new NumberFormatException("Bad value for: " + PAGE_SIZE_PARAM);\r
             }\r
         }\r
-        \r
+\r
         setPageSize(pageSize);\r
     }\r
 \r
@@ -253,7 +258,7 @@ public class DocumentFilter {
     protected void setStartPage(String startPageStr) {\r
         if (startPageStr != null) {\r
             try {\r
-               startPage = Integer.valueOf(startPageStr);\r
+                startPage = Integer.valueOf(startPageStr);\r
             } catch (NumberFormatException e) {\r
                 throw new NumberFormatException("Bad value for: " + START_PAGE_PARAM);\r
             }\r
@@ -268,11 +273,17 @@ public class DocumentFilter {
     }\r
 \r
     public void addQueryParam(String key, String value) {\r
-        queryParams.add(key, value);\r
+        if (queryParams != null) {\r
+            queryParams.add(key, value);\r
+        }\r
     }\r
 \r
     public List<String> getQueryParam(String key) {\r
-        return queryParams.get(key);\r
+        if (queryParams != null) {\r
+            return queryParams.get(key);\r
+        } else {\r
+            return new ArrayList<String>();\r
+        }\r
     }\r
 \r
     public MultivaluedMap<String, String> getQueryParams() {\r
index 91ae14073e9a8d110221b781e0210d6f558a95d2..1e12bdfe4e4b0fb63f0710ee0d04070f050ab7f2 100644 (file)
@@ -91,7 +91,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             DocumentWrapper<List<T>> wrapDoc =
                     new DocumentWrapperImpl<List<T>>(rl);
             handler.handle(Action.CREATE, wrapDoc);
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             em.getTransaction().begin();
             for (T r : rl) {
@@ -116,7 +116,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (em != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -161,7 +161,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             if ((null != where) && (where.length() > 0)) {
                 queryStrBldr.append(" AND " + where);
             }
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             String queryStr = queryStrBldr.toString(); //for debugging
             if (logger.isDebugEnabled()) {
@@ -202,7 +202,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -237,7 +237,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
                 logger.debug("delete: using objectId=" + objectId);
             }
             deleteStr.append(" WHERE " + objectId + " = :objectId");
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             if (logger.isDebugEnabled()) {
                 logger.debug("delete: jql=" + deleteStr.toString());
@@ -272,7 +272,7 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
index 552b17e442c4ca3b86b989b2c91ae560a8dbfd81..03286a81f377dbf07f86912582bab38bfbec3020 100644 (file)
@@ -81,8 +81,6 @@ public class JpaStorageClientImpl implements StorageClient {
 
     /** The logger. */
     private final Logger logger = LoggerFactory.getLogger(JpaStorageClientImpl.class);
-    /** The Constant CS_PERSISTENCE_UNIT. */
-    public final static String CS_PERSISTENCE_UNIT = "org.collectionspace.services";
     private Class entityClazz;
 
     /**
@@ -119,7 +117,7 @@ public class JpaStorageClientImpl implements StorageClient {
             DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(entity);
             handler.handle(Action.CREATE, wrapDoc);
             setValue(entity, "setCreatedAtItem", Date.class, new Date());
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             em.getTransaction().begin();
             em.persist(entity);
@@ -143,7 +141,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (em != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
 
@@ -180,33 +178,9 @@ public class JpaStorageClientImpl implements StorageClient {
         EntityManager em = null;
         try {
             handler.prepare(Action.GET);
-            StringBuilder queryStrBldr = new StringBuilder("SELECT a FROM ");
-            queryStrBldr.append(getEntityName(ctx));
-            queryStrBldr.append(" a");
-            queryStrBldr.append(" WHERE csid = :csid");
-            //TODO: add tenant id
-            String where = docFilter.getWhereClause();
-            if ((null != where) && (where.length() > 0)) {
-                queryStrBldr.append(" AND " + where);
-            }
-            emf = getEntityManagerFactory();
-            em = emf.createEntityManager();
-            String queryStr = queryStrBldr.toString(); //for debugging
-            Query q = em.createQuery(queryStr);
-            q.setParameter("csid", id);
-            //TODO: add tenant id
-
-            //TODO: get page
-            if ((docFilter.getOffset() > 0) || (docFilter.getPageSize() > 0)) {
-            } else {
-            }
             Object o = null;
-
             try {
-                //require transaction for get?
-                em.getTransaction().begin();
-                o = q.getSingleResult();
-                em.getTransaction().commit();
+                o = JpaStorageUtils.getEntity(getEntityName(ctx), id, docFilter);
             } catch (NoResultException nre) {
                 if (em != null && em.getTransaction().isActive()) {
                     em.getTransaction().rollback();
@@ -227,7 +201,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -255,6 +229,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new IllegalArgumentException(
                     "JpaStorageClient.getFiltered: handler is missing");
         }
+
         DocumentFilter docFilter = handler.getDocumentFilter();
         if (docFilter == null) {
             docFilter = handler.createDocumentFilter();
@@ -269,7 +244,7 @@ public class JpaStorageClientImpl implements StorageClient {
             queryStrBldr.append(" a");
             List<DocumentFilter.ParamBinding> params = docFilter.buildWhereForSearch(queryStrBldr);
             //TODO: add tenant id
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             String queryStr = queryStrBldr.toString(); //for debugging
             Query q = em.createQuery(queryStr);
@@ -300,7 +275,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -328,7 +303,7 @@ public class JpaStorageClientImpl implements StorageClient {
             setCsid(entity, id);
             DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(entity);
             handler.handle(Action.UPDATE, wrapDoc);
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             em.getTransaction().begin();
             Object entityFound = em.find(entity.getClass(), id);
@@ -361,7 +336,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -388,7 +363,7 @@ public class JpaStorageClientImpl implements StorageClient {
 
             //TODO: add tenant id
 
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
 
             em.getTransaction().begin();
@@ -416,7 +391,7 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
@@ -449,7 +424,7 @@ public class JpaStorageClientImpl implements StorageClient {
             deleteStr.append(" WHERE csid = :csid");
             //TODO: add tenant id
 
-            emf = getEntityManagerFactory();
+            emf = JpaStorageUtils.getEntityManagerFactory();
             em = emf.createEntityManager();
             Query q = em.createQuery(deleteStr.toString());
             q.setParameter("csid", id);
@@ -479,44 +454,12 @@ public class JpaStorageClientImpl implements StorageClient {
             throw new DocumentException(e);
         } finally {
             if (emf != null) {
-                releaseEntityManagerFactory(emf);
+                JpaStorageUtils.releaseEntityManagerFactory(emf);
             }
         }
     }
 
-    /**
-     * Gets the entity manager factory.
-     * 
-     * @return the entity manager factory
-     */
-    public EntityManagerFactory getEntityManagerFactory() {
-        return getEntityManagerFactory(CS_PERSISTENCE_UNIT);
-    }
-
-    /**
-     * Gets the entity manager factory.
-     * 
-     * @param persistenceUnit the persistence unit
-     * 
-     * @return the entity manager factory
-     */
-    public EntityManagerFactory getEntityManagerFactory(
-            String persistenceUnit) {
-        return Persistence.createEntityManagerFactory(persistenceUnit);
-
-    }
-
-    /**
-     * Release entity manager factory.
-     * 
-     * @param emf the emf
-     */
-    public void releaseEntityManagerFactory(EntityManagerFactory emf) {
-        if (emf != null) {
-            emf.close();
-        }
 
-    }
 
     /**
      * getValue gets invokes specified accessor method on given object. Assumption
diff --git a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java
new file mode 100644 (file)
index 0000000..e676993
--- /dev/null
@@ -0,0 +1,157 @@
+/**
+ *  This document is a part of the source code and related artifacts
+ *  for CollectionSpace, an open source collections management system
+ *  for museums and related institutions:
+
+ *  http://www.collectionspace.org
+ *  http://wiki.collectionspace.org
+
+ *  Copyright 2010 University of California at Berkeley
+
+ *  Licensed under the Educational Community License (ECL), Version 2.0.
+ *  You may not use this file except in compliance with this License.
+
+ *  You may obtain a copy of the ECL 2.0 License at
+
+ *  https://source.collectionspace.org/collection-space/LICENSE.txt
+
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+package org.collectionspace.services.common.storage.jpa;
+
+import java.util.List;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+import org.collectionspace.services.common.document.DocumentFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utilities for JpaStorage
+ * @author 
+ */
+public class JpaStorageUtils {
+
+    final private static Logger logger = LoggerFactory.getLogger(JpaStorageUtils.class);
+    /** The Constant CS_PERSISTENCE_UNIT. */
+    public final static String CS_PERSISTENCE_UNIT = "org.collectionspace.services";
+
+    /**
+     * getEntity for given id and class
+     * @param id
+     * @param entityClazz
+     * @return null if entity is not found
+     * @throws Exception
+     */
+    public static Object getEntity(String id, Class entityClazz) {
+        EntityManagerFactory emf = null;
+        EntityManager em = null;
+        Object entityFound = null;
+        try {
+            emf = getEntityManagerFactory();
+            em = emf.createEntityManager();
+            entityFound = em.find(entityClazz, id);
+            if (entityFound == null) {
+                if (em != null && em.getTransaction().isActive()) {
+                    em.getTransaction().rollback();
+                }
+            }
+        } finally {
+            if (em != null) {
+                releaseEntityManagerFactory(emf);
+            }
+        }
+        return entityFound;
+    }
+
+    /**
+     * getEntity using where clause from given docFilter
+     * @param entityName fully qualified entity name
+     * @param id
+     * @param docFilter
+     * @return
+     * @throws Exception
+     */
+    public static Object getEntity(String entityName, String id, DocumentFilter docFilter)
+            throws Exception {
+        EntityManagerFactory emf = null;
+        EntityManager em = null;
+        Object o = null;
+        try {
+            if (docFilter == null) {
+                docFilter = new DocumentFilter();
+            }
+            StringBuilder queryStrBldr = new StringBuilder("SELECT a FROM ");
+            queryStrBldr.append(entityName);
+            queryStrBldr.append(" a");
+            queryStrBldr.append(" WHERE csid = :csid");
+            //TODO: add tenant id
+            String where = docFilter.getWhereClause();
+            if ((null != where) && (where.length() > 0)) {
+                queryStrBldr.append(" AND " + where);
+            }
+
+            emf = getEntityManagerFactory();
+            em = emf.createEntityManager();
+            String queryStr = queryStrBldr.toString(); //for debugging
+            Query q = em.createQuery(queryStr);
+            q.setParameter("csid", id);
+            List<DocumentFilter.ParamBinding> params =
+                    docFilter.buildWhereForSearch(queryStrBldr);
+            for (DocumentFilter.ParamBinding p : params) {
+                q.setParameter(p.getName(), p.getValue());
+            }
+
+            //require transaction for get?
+            em.getTransaction().begin();
+            o = q.getSingleResult();
+            em.getTransaction().commit();
+        } finally {
+            if (em != null) {
+                releaseEntityManagerFactory(emf);
+            }
+        }
+        return o;
+    }
+
+    /**
+     * Gets the entity manager factory.
+     *
+     * @return the entity manager factory
+     */
+    public static EntityManagerFactory getEntityManagerFactory() {
+        return getEntityManagerFactory(CS_PERSISTENCE_UNIT);
+    }
+
+    /**
+     * Gets the entity manager factory.
+     *
+     * @param persistenceUnit the persistence unit
+     *
+     * @return the entity manager factory
+     */
+    public static EntityManagerFactory getEntityManagerFactory(
+            String persistenceUnit) {
+        return Persistence.createEntityManagerFactory(persistenceUnit);
+
+    }
+
+    /**
+     * Release entity manager factory.
+     *
+     * @param emf the emf
+     */
+    public static void releaseEntityManagerFactory(EntityManagerFactory emf) {
+        if (emf != null) {
+            emf.close();
+        }
+
+    }
+}
+