From: Sanjay Dalal Date: Wed, 21 Apr 2010 20:45:48 +0000 (+0000) Subject: NOJIRA - refactored JpaStorageClient, extracted out utilities into JpaStorageUtils... X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=2105928820146426f1a9c909bc037a481866f79d;p=tmp%2Fjakarta-migration.git NOJIRA - refactored JpaStorageClient, extracted out utilities into JpaStorageUtils so that some of those (getEntity) could be used for validation 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 --- diff --git a/services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java b/services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java index 82b9ae841..c72d69122 100644 --- a/services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java +++ b/services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java @@ -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; } diff --git a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java index 3e87d65ce..8d70d594f 100644 --- a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java +++ b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountJpaFilter.java @@ -52,7 +52,7 @@ public class AccountJpaFilter extends JpaDocumentFilter { String screenName = null; List 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 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 emailvals = getQueryParam(AccountStorageConstants.Q_EMAIL); - if (emailvals != null) { + if (null != emailvals && emailvals.size() > 0) { email = emailvals.get(0); } if (null != email && !email.isEmpty()) { diff --git a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java index 81e0909e0..eb7374d4e 100644 --- a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java +++ b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java @@ -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 wrapDoc = new DocumentWrapperImpl(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(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); } } } diff --git a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java index 95e77c292..c5bb8ef45 100644 --- a/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java +++ b/services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountValidatorHandler.java @@ -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 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; diff --git a/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java b/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java index 807d5f4c1..e982bb76a 100644 --- a/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java +++ b/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionJpaFilter.java @@ -58,7 +58,7 @@ public class PermissionJpaFilter extends JpaDocumentFilter { String resName = null; List rn = getQueryParam(PermissionStorageConstants.Q_RESOURCE_NAME); - if (null != rn) { + if (null != rn && rn.size() > 0) { resName = rn.get(0); } if (null != resName && !resName.isEmpty()) { diff --git a/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java b/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java index cc30c603c..687b529d7 100644 --- a/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java +++ b/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/RoleJpaFilter.java @@ -51,7 +51,7 @@ public class RoleJpaFilter extends JpaDocumentFilter { String roleName = null; List rn = getQueryParam(RoleStorageConstants.Q_ROLE_NAME); - if (null != rn) { + if (null != rn && rn.size() > 0) { roleName = rn.get(0); } if (null != roleName && !roleName.isEmpty()) { diff --git a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java index 87f17e593..e1092fcfd 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java +++ b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java @@ -43,8 +43,11 @@ public class DocumentFilter { protected int startPage; // Pagination offset for list results protected int pageSize; // Pagination limit for list results private boolean pageSizeDirty = false; // True if default page size explicitly set/overridden - private MultivaluedMap queryParams = null; + //queryParams is not initialized as it would require a multi-valued map implementation + //unless it is used from opensource lib...this variable holds ref to + //implementation available in JBoss RESTeasy + private MultivaluedMap queryParams = null; /** * ParamBinding encapsulates parameter binding for query @@ -87,17 +90,17 @@ public class DocumentFilter { this.value = value; } } - + /** * Instantiates a new document filter. * * @param ctx the ctx */ public DocumentFilter(ServiceContext ctx) { - this.setPageSize(ctx.getServiceBindingPropertyValue( - DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY)); + this.setPageSize(ctx.getServiceBindingPropertyValue( + DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY)); } - + public DocumentFilter() { this("", 0, defaultPageSize); // Use empty string for easy concatenation } @@ -113,16 +116,18 @@ public class DocumentFilter { * * @param queryParams the query params */ - public void setPagination(MultivaluedMap queryParams) { - // - // Bail if there are no params - // - if (queryParams == null) return; - + public void setPagination(MultivaluedMap queryParams) { // - // Set the page size - // - String pageSizeStr = null; + // Bail if there are no params + // + if (queryParams == null) { + return; + } + + // + // Set the page size + // + String pageSizeStr = null; List list = queryParams.remove(PAGE_SIZE_PARAM); if (list != null) { pageSizeStr = list.get(0); @@ -214,9 +219,9 @@ public class DocumentFilter { public int getPageSize() { return pageSize; } - + public boolean getPageSizeDirty() { - return this.getPageSizeDirty(); + return this.getPageSizeDirty(); } /** @@ -231,17 +236,17 @@ public class DocumentFilter { * @param pageSize the max number of items to return for list requests */ public void setPageSize(String pageSizeStr) { - int pageSize = this.defaultPageSize; + int pageSize = this.defaultPageSize; if (pageSizeStr != null) { try { - pageSize = Integer.valueOf(pageSizeStr); + pageSize = Integer.valueOf(pageSizeStr); } catch (NumberFormatException e) { - //FIXME This should cause a warning in the log file and should result in the - //FIXME page size being set to the default. We don't need to throw an exception here. + //FIXME This should cause a warning in the log file and should result in the + //FIXME page size being set to the default. We don't need to throw an exception here. throw new NumberFormatException("Bad value for: " + PAGE_SIZE_PARAM); } } - + setPageSize(pageSize); } @@ -253,7 +258,7 @@ public class DocumentFilter { protected void setStartPage(String startPageStr) { if (startPageStr != null) { try { - startPage = Integer.valueOf(startPageStr); + startPage = Integer.valueOf(startPageStr); } catch (NumberFormatException e) { throw new NumberFormatException("Bad value for: " + START_PAGE_PARAM); } @@ -268,11 +273,17 @@ public class DocumentFilter { } public void addQueryParam(String key, String value) { - queryParams.add(key, value); + if (queryParams != null) { + queryParams.add(key, value); + } } public List getQueryParam(String key) { - return queryParams.get(key); + if (queryParams != null) { + return queryParams.get(key); + } else { + return new ArrayList(); + } } public MultivaluedMap getQueryParams() { diff --git a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java index 91ae14073..1e12bdfe4 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java +++ b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java @@ -91,7 +91,7 @@ public class JpaRelationshipStorageClient extends JpaStorageClientImpl { DocumentWrapper> wrapDoc = new DocumentWrapperImpl>(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 extends JpaStorageClientImpl { throw new DocumentException(e); } finally { if (em != null) { - releaseEntityManagerFactory(emf); + JpaStorageUtils.releaseEntityManagerFactory(emf); } } } @@ -161,7 +161,7 @@ public class JpaRelationshipStorageClient 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 extends JpaStorageClientImpl { throw new DocumentException(e); } finally { if (emf != null) { - releaseEntityManagerFactory(emf); + JpaStorageUtils.releaseEntityManagerFactory(emf); } } } @@ -237,7 +237,7 @@ public class JpaRelationshipStorageClient 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 extends JpaStorageClientImpl { throw new DocumentException(e); } finally { if (emf != null) { - releaseEntityManagerFactory(emf); + JpaStorageUtils.releaseEntityManagerFactory(emf); } } } diff --git a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java index 552b17e44..03286a81f 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java @@ -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 wrapDoc = new DocumentWrapperImpl(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 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 wrapDoc = new DocumentWrapperImpl(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 index 000000000..e67699314 --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java @@ -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 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(); + } + + } +} +