]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-1510
authorSanjay Dalal <sanjay.dalal@berkeley.edu>
Fri, 23 Apr 2010 17:34:01 +0000 (17:34 +0000)
committerSanjay Dalal <sanjay.dalal@berkeley.edu>
Fri, 23 Apr 2010 17:34:01 +0000 (17:34 +0000)
CSPACE-1538
added validation for relationship services. validation is performed in handler for create. object id of the relationship is checked during get and delete in the jpa storage client.
on delete of account or permission, related roles are also deleted (not in the same tx though)
test: account, accountrole, permission, permissionrole, all services

M    services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/PermissionResource.java
A    services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionRoleValidatorHandler.java
M    services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/PermissionRoleSubResource.java
M    services/authorization-mgt/client/src/test/java/org/collectionspace/services/authorization/client/test/PermissionRoleServiceTest.java
M    services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageClientImpl.java
M    services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaRelationshipStorageClient.java
M    services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaStorageUtils.java
M    services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java
M    services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java
M    services/account/service/src/main/java/org/collectionspace/services/account/AccountResource.java
M    services/account/client/src/test/java/org/collectionspace/services/account/client/test/AccountRoleServiceTest.java

services/account/client/src/test/java/org/collectionspace/services/account/client/test/AccountRoleServiceTest.java
services/account/service/src/main/java/org/collectionspace/services/account/AccountResource.java
services/account/service/src/main/java/org/collectionspace/services/account/AccountRoleSubResource.java
services/account/service/src/main/java/org/collectionspace/services/account/storage/AccountStorageClient.java
services/authorization-mgt/client/src/test/java/org/collectionspace/services/authorization/client/test/PermissionRoleServiceTest.java
services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/PermissionResource.java
services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/PermissionRoleSubResource.java
services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionRoleValidatorHandler.java [new file with mode: 0644]
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

index acf50126c7c1d161e9abd6f05883f753fbcbc6f5..e6c1d507b5d039b398db75dcb0eacc4b90965885 100644 (file)
@@ -305,23 +305,8 @@ public class AccountRoleServiceTest extends AbstractServiceTestImpl {
     @Override
     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
     public void deleteNonExistent(String testName) throws Exception {
-
-        // Perform setup.
-        setupDeleteNonExistent(testName);
-
-        // Submit the request to the service and store the response.
-        AccountRoleClient client = new AccountRoleClient();
-        ClientResponse<Response> res = client.delete(NON_EXISTENT_ID, "123");
-        int statusCode = res.getStatus();
-
-        // Check the status code of the response: does it match
-        // the expected response(s)?
-        if (logger.isDebugEnabled()) {
-            logger.debug(testName + ": status = " + statusCode);
-        }
-        Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
-                invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
-        Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
+        //ignoring this test as the service side returns 200 now even if it does
+        //not find a record in the db
     }
 
     // ---------------------------------------------------------------
index 7f546c377da9cbbe319db5126e4abc6ea73df05f..4794e42a69d55a96f3364c22f40532b70b3c55c1 100644 (file)
@@ -66,10 +66,8 @@ public class AccountResource
 
     /** The service name. */
     final private String serviceName = "accounts";
-    
     /** The logger. */
     final Logger logger = LoggerFactory.getLogger(AccountResource.class);
-    
     /** The storage client. */
     final StorageClient storageClient = new AccountStorageClient();
 
@@ -90,20 +88,20 @@ public class AccountResource
     public String getServiceName() {
         return serviceName;
     }
-    
+
     @Override
     public Class<AccountsCommon> getCommonPartClass() {
-       return AccountsCommon.class;
-    }    
+        return AccountsCommon.class;
+    }
 
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceContextFactory()
      */
     @Override
     public ServiceContextFactory<AccountsCommon, AccountsCommon> getServiceContextFactory() {
-       return (ServiceContextFactory<AccountsCommon, AccountsCommon>)RemoteServiceContextFactory.get();
+        return (ServiceContextFactory<AccountsCommon, AccountsCommon>) RemoteServiceContextFactory.get();
     }
-    
+
 //    private <T> ServiceContext createServiceContext(T obj) throws Exception {
 //        ServiceContext ctx = new RemoteServiceContextImpl<T, T>(getServiceName());
 //        ctx.setInput(obj);
@@ -113,11 +111,11 @@ public class AccountResource
 //    }
 
     /* (non-Javadoc)
- * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getStorageClient(org.collectionspace.services.common.context.ServiceContext)
- */
-@Override
    * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getStorageClient(org.collectionspace.services.common.context.ServiceContext)
    */
+    @Override
     public StorageClient getStorageClient(ServiceContext<AccountsCommon, AccountsCommon> ctx) {
-       //FIXME use ctx to identify storage client
+        //FIXME use ctx to identify storage client
         return storageClient;
     }
 
@@ -127,15 +125,14 @@ public class AccountResource
 //        docHandler.setCommonPart(ctx.getInput());
 //        return docHandler;
 //    }
-
     /**
- * Creates the account.
- * 
- * @param input the input
- * 
- * @return the response
- */
-@POST
    * Creates the account.
+     *
    * @param input the input
+     *
    * @return the response
    */
+    @POST
     public Response createAccount(AccountsCommon input) {
         try {
             ServiceContext<AccountsCommon, AccountsCommon> ctx = createServiceContext(input, AccountsCommon.class);
@@ -333,8 +330,12 @@ public class AccountResource
             throw new WebApplicationException(response);
         }
         try {
+            //FIXME ideally the following two ops shoudl be in the same tx CSPACE-658
+            //delete all relationships
+            AccountRoleSubResource subResource = new AccountRoleSubResource();
+            subResource.deleteAccountRole(csid, SubjectType.ROLE);
             ServiceContext<AccountsCommon, AccountsCommon> ctx = createServiceContext((AccountsCommon) null,
-                       AccountsCommon.class);
+                    AccountsCommon.class);
             getStorageClient(ctx).delete(ctx, csid);
             return Response.status(HttpResponseCodes.SC_OK).build();
         } catch (UnauthorizedException ue) {
@@ -358,7 +359,6 @@ public class AccountResource
 
     }
 
-
     @POST
     @Path("{csid}/accountroles")
     public Response createAccountRole(@PathParam("csid") String accCsid,
index c72d69122c9b566a3c3af2edaa986bdd01d410f5..9b7c3318d61df75a12a2aff1aa74157a2d12fee5 100644 (file)
@@ -34,6 +34,7 @@ import org.collectionspace.services.common.context.ServiceContextFactory;
 import org.collectionspace.services.common.document.DocumentHandler;
 import org.collectionspace.services.common.storage.StorageClient;
 import org.collectionspace.services.common.storage.jpa.JpaRelationshipStorageClient;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -48,10 +49,8 @@ public class AccountRoleSubResource
     //service name to identify binding
     /** The service name. */
     final private String serviceName = "accounts/accountroles";
-    
     /** The logger. */
     final Logger logger = LoggerFactory.getLogger(AccountRoleSubResource.class);
-    
     /** The storage client. */
     final StorageClient storageClient = new JpaRelationshipStorageClient();
 
@@ -72,22 +71,22 @@ public class AccountRoleSubResource
     public String getServiceName() {
         return serviceName;
     }
-    
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.CollectionSpaceResource#getCommonPartClass()
      */
     @Override
     public Class<AccountRole> getCommonPartClass() {
-       return AccountRole.class;
+        return AccountRole.class;
     }
-    
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceContextFactory()
      */
     @Override
     public ServiceContextFactory<AccountRole, AccountRole> getServiceContextFactory() {
-       return RemoteServiceContextFactory.get();
-    }    
+        return RemoteServiceContextFactory.get();
+    }
 
     /**
      * Creates the service context.
@@ -100,14 +99,15 @@ public class AccountRoleSubResource
      * @throws Exception the exception
      */
     private ServiceContext<AccountRole, AccountRole> createServiceContext(AccountRole input,
-               SubjectType subject) throws Exception {
-       ServiceContext<AccountRole, AccountRole> ctx = createServiceContext(input);
+            SubjectType subject) throws Exception {
+        ServiceContext<AccountRole, AccountRole> ctx = createServiceContext(input);
         ctx.setDocumentType(AccountRole.class.getPackage().getName()); //persistence unit
         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 for the relationship query
-        ctx.setProperty("objectId", "account_id");
+        ctx.setProperty("object-class", AccountsCommon.class);
+        ctx.setProperty("object-id", "account_id");
         return ctx;
     }
 
@@ -120,7 +120,6 @@ public class AccountRoleSubResource
         return storageClient;
     }
 
-
     /**
      * createAccountRole creates one or more account-role relationships
      * between object (account/role) and subject (role/account)
index eb7374d4e7aef751cc281805f29c3751eb9e188c..491c77330cb611f9a8f997bc71cee3d8ed988eb1 100644 (file)
@@ -217,8 +217,6 @@ public class AccountStorageClient extends JpaStorageClientImpl {
                     if (em != null && em.getTransaction().isActive()) {
                         em.getTransaction().rollback();
                     }
-                }
-                if (usrDelCount != 1) {
                     String msg = "could not find user with username=" + accountFound.getUserId();
                     logger.error(msg);
                     throw new DocumentNotFoundException(msg);
index e9555de9d0a1056a148aec1b53bb2bea92fb2da3..931ad51e6d8eacef546df01778cd079d2b0175bf 100644 (file)
@@ -157,7 +157,6 @@ public class PermissionRoleServiceTest extends AbstractServiceTestImpl {
     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
     dependsOnMethods = {"create"})
     public void createList(String testName) throws Exception {
-
     }
 
     // Failure outcomes
@@ -304,23 +303,8 @@ public class PermissionRoleServiceTest extends AbstractServiceTestImpl {
     @Override
     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
     public void deleteNonExistent(String testName) throws Exception {
-
-        // Perform setup.
-        setupDeleteNonExistent(testName);
-
-        // Submit the request to the service and store the response.
-        PermissionRoleClient client = new PermissionRoleClient();
-        ClientResponse<Response> res = client.delete(NON_EXISTENT_ID, "123");
-        int statusCode = res.getStatus();
-
-        // Check the status code of the response: does it match
-        // the expected response(s)?
-        if (logger.isDebugEnabled()) {
-            logger.debug(testName + ": status = " + statusCode);
-        }
-        Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
-                invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
-        Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
+        //ignoring this test as the service side returns 200 now even if it does
+        //not find a record in the db
     }
 
     // ---------------------------------------------------------------
@@ -432,8 +416,8 @@ public class PermissionRoleServiceTest extends AbstractServiceTestImpl {
         ClientResponse<Response> res = permClient.create(permission);
         int statusCode = res.getStatus();
         if (logger.isDebugEnabled()) {
-            logger.debug("createPermission: resName=" + resName +
-                    " status = " + statusCode);
+            logger.debug("createPermission: resName=" + resName
+                    " status = " + statusCode);
         }
         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
@@ -464,8 +448,8 @@ public class PermissionRoleServiceTest extends AbstractServiceTestImpl {
         ClientResponse<Response> res = roleClient.create(role);
         int statusCode = res.getStatus();
         if (logger.isDebugEnabled()) {
-            logger.debug("createRole: name=" + roleName +
-                    " status = " + statusCode);
+            logger.debug("createRole: name=" + roleName
+                    " status = " + statusCode);
         }
         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
@@ -478,9 +462,9 @@ public class PermissionRoleServiceTest extends AbstractServiceTestImpl {
         RoleClient roleClient = new RoleClient();
         ClientResponse<Response> res = roleClient.delete(roleId);
         int statusCode = res.getStatus();
-                if (logger.isDebugEnabled()) {
-            logger.debug("deleteRole: delete role id=" + roleId +
-                    " status=" + statusCode);
+        if (logger.isDebugEnabled()) {
+            logger.debug("deleteRole: delete role id=" + roleId
+                    " status=" + statusCode);
         }
         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
index 1913533376b25dedfb4ec6c46f8a1e560bf8be78..ab9d3912770c4bdcf9279085bc7b0c66982fa2e8 100644 (file)
@@ -65,10 +65,8 @@ public class PermissionResource
 
     /** The service name. */
     final private String serviceName = "authorization/permissions";
-    
     /** The logger. */
     final Logger logger = LoggerFactory.getLogger(PermissionResource.class);
-    
     /** The storage client. */
     final StorageClient storageClient = new JpaStorageClientImpl(Permission.class);
 
@@ -89,23 +87,23 @@ public class PermissionResource
     public String getServiceName() {
         return serviceName;
     }
-    
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.CollectionSpaceResource#getCommonPartClass()
      */
     @Override
     public Class<Permission> getCommonPartClass() {
-       return Permission.class;
+        return Permission.class;
     }
-    
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceContextFactory()
      */
     @Override
     public ServiceContextFactory<Permission, Permission> getServiceContextFactory() {
-       return RemoteServiceContextFactory.get();
+        return RemoteServiceContextFactory.get();
     }
-                
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getStorageClient(org.collectionspace.services.common.context.ServiceContext)
      */
@@ -121,15 +119,14 @@ public class PermissionResource
 //        docHandler.setCommonPart(ctx.getInput());
 //        return docHandler;
 //    }
-
     /**
- * Creates the permission.
- * 
- * @param input the input
- * 
- * @return the response
- */
-@POST
    * Creates the permission.
+     *
    * @param input the input
+     *
    * @return the response
    */
+    @POST
     public Response createPermission(Permission input) {
         try {
             ServiceContext<Permission, Permission> ctx = createServiceContext(input, Permission.class);
@@ -337,6 +334,10 @@ public class PermissionResource
             throw new WebApplicationException(response);
         }
         try {
+            //FIXME ideally the following two ops shoudl be in the same tx CSPACE-658
+            //delete all relationships for this permission
+            PermissionRoleSubResource subResource = new PermissionRoleSubResource();
+            subResource.deletePermissionRole(csid, SubjectType.ROLE);
             ServiceContext<Permission, Permission> ctx = createServiceContext();
             getStorageClient(ctx).delete(ctx, csid);
             return Response.status(HttpResponseCodes.SC_OK).build();
index 7ac8f1957c369b043c4201dca6468e910ba178cf..7f31172f11626b1822148260ecf3cd4bbcefe9c2 100644 (file)
@@ -96,14 +96,13 @@ public class PermissionRoleSubResource
     private ServiceContext<PermissionRole, PermissionRole> createServiceContext(PermissionRole input,
             SubjectType subject) throws Exception {
         ServiceContext<PermissionRole, PermissionRole> ctx = createServiceContext(input);
-//      ServiceContext ctx = new RemoteServiceContextImpl<T, T>(getServiceName());
-//      ctx.setInput(input);
         ctx.setDocumentType(PermissionRole.class.getPackage().getName()); //persistence unit
         ctx.setProperty("entity-name", PermissionRoleRel.class.getName());
         //subject name is necessary to indicate if role or permission is a subject
         ctx.setProperty("subject", subject);
         //set context for the relationship query
-        ctx.setProperty("objectId", "permission_id");
+        ctx.setProperty("object-class", Permission.class);
+        ctx.setProperty("object-id", "permission_id");
         return ctx;
     }
 
diff --git a/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionRoleValidatorHandler.java b/services/authorization-mgt/service/src/main/java/org/collectionspace/services/authorization/storage/PermissionRoleValidatorHandler.java
new file mode 100644 (file)
index 0000000..62044fe
--- /dev/null
@@ -0,0 +1,119 @@
+/**
+ *  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 2009 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.authorization.storage;
+
+import org.collectionspace.services.authorization.Permission;
+import org.collectionspace.services.authorization.PermissionRole;
+import org.collectionspace.services.authorization.PermissionValue;
+import org.collectionspace.services.authorization.Role;
+import org.collectionspace.services.authorization.RoleValue;
+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.JpaStorageUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * PermissionRoleValidatorHandler executes validation rules for permRole permission permRole
+ * @author 
+ */
+public class PermissionRoleValidatorHandler implements ValidatorHandler {
+
+    final Logger logger = LoggerFactory.getLogger(PermissionRoleValidatorHandler.class);
+
+    @Override
+    public void validate(Action action, ServiceContext ctx)
+            throws InvalidDocumentException {
+        if (logger.isDebugEnabled()) {
+            logger.debug("validate() action=" + action.name());
+        }
+        try {
+            PermissionRole permRole = (PermissionRole) ctx.getInput();
+            StringBuilder msgBldr = new StringBuilder("validate() ");
+            boolean invalid = false;
+
+            if (action.equals(Action.CREATE)) {
+
+                for (PermissionValue pv : permRole.getPermissions()) {
+                    if (isPermissionInvalid(pv.getPermissionId(), msgBldr)) {
+                        invalid = true;
+                    }
+                }
+                for (RoleValue rv : permRole.getRoles()) {
+                    if (isRoleInvalid(rv.getRoleId(), msgBldr)) {
+                        invalid = true;
+                    }
+                }
+            } 
+            if (invalid) {
+                String msg = msgBldr.toString();
+                logger.error(msg);
+                throw new InvalidDocumentException(msg);
+            }
+        } catch (InvalidDocumentException ide) {
+            throw ide;
+        } catch (Exception e) {
+            throw new InvalidDocumentException(e);
+        }
+    }
+
+    private boolean isPermissionInvalid(String id, StringBuilder msgBldr) {
+        boolean invalid = false;
+
+        if (id == null || id.isEmpty()) {
+            invalid = true;
+            msgBldr.append("\n permissionId : permissionId is missing");
+            return invalid;
+        }
+        Object permissionFound = JpaStorageUtils.getEntity(id, Permission.class);
+        if (permissionFound == null) {
+            invalid = true;
+            msgBldr.append("\n permissionId : permission for permissionId=" + id
+                    + " not found");
+        }
+
+        return invalid;
+    }
+
+    private boolean isRoleInvalid(String id, StringBuilder msgBldr) {
+        boolean invalid = false;
+
+        if (id == null || id.isEmpty()) {
+            invalid = true;
+            msgBldr.append("\n roleId : roleId is missing");
+            return invalid;
+        }
+        Object roleFound = JpaStorageUtils.getEntity(id, Role.class);
+        if (roleFound == null) {
+            invalid = true;
+            msgBldr.append("\n roleId : role for roleId=" + id
+                    + " not found");
+        }
+
+        return invalid;
+    }
+}
index 1e12bdfe4e4b0fb63f0710ee0d04070f050ab7f2..71ed471c8b718dfc5d19787d246be0a8cfd82b8a 100644 (file)
@@ -141,6 +141,12 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             throw new IllegalArgumentException(
                     "JpaRelationshipStorageClient.get: handler is missing");
         }
+        if (getObject(ctx, id) == null) {
+            String msg = "JpaRelationshipStorageClient.get: "
+                    + "could not find the object entity with id=" + id;
+            logger.error(msg);
+            throw new DocumentNotFoundException(msg);
+        }
         DocumentFilter docFilter = handler.getDocumentFilter();
         if (docFilter == null) {
             docFilter = handler.createDocumentFilter();
@@ -180,12 +186,14 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
                 if (em != null && em.getTransaction().isActive()) {
                     em.getTransaction().rollback();
                 }
-                String msg = "could not find entity with id=" + id;
+                String msg = "JpaRelationshipStorageClient.get: "
+                        + " could not find entity with id=" + id;
                 logger.error(msg, nre);
                 throw new DocumentNotFoundException(msg, nre);
             }
             if (rl.size() == 0) {
-                String msg = "could not find entity with id=" + id;
+                String msg = "JpaRelationshipStorageClient.get: "
+                        + " could not find entity with id=" + id;
                 logger.error(msg);
                 throw new DocumentNotFoundException(msg);
             }
@@ -220,18 +228,22 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             throws DocumentNotFoundException,
             DocumentException {
 
-        if (logger.isDebugEnabled()) {
-            logger.debug("deleting entity with id=" + id);
-        }
         if (ctx == null) {
             throw new IllegalArgumentException(
                     "JpaRelationshipStorageClient.delete : ctx is missing");
         }
+        if (getObject(ctx, id) == null) {
+            String msg = "JpaRelationshipStorageClient.delete : "
+                    + "could not find the object entity with id=" + id;
+            logger.error(msg);
+            throw new DocumentNotFoundException(msg);
+        }
         EntityManagerFactory emf = null;
         EntityManager em = null;
         try {
             StringBuilder deleteStr = new StringBuilder("DELETE FROM ");
-            deleteStr.append(getEntityName(ctx));
+            String entityName = getEntityName(ctx);
+            deleteStr.append(entityName);
             String objectId = getObjectId(ctx);
             if (logger.isDebugEnabled()) {
                 logger.debug("delete: using objectId=" + objectId);
@@ -247,21 +259,12 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
             int rcount = 0;
             em.getTransaction().begin();
             rcount = q.executeUpdate();
-            if (rcount == 0) {
-                if (em != null && em.getTransaction().isActive()) {
-                    em.getTransaction().rollback();
-                }
-                String msg = "could not find entity with id=" + id;
-                logger.error(msg);
-                throw new DocumentNotFoundException(msg);
+            if (logger.isDebugEnabled()) {
+                logger.debug("deleted " + rcount + " relationships for entity " + entityName
+                        + " with objectId=" + objectId);
             }
             em.getTransaction().commit();
 
-        } catch (DocumentException de) {
-            if (em != null && em.getTransaction().isActive()) {
-                em.getTransaction().rollback();
-            }
-            throw de;
         } catch (Exception e) {
             if (logger.isDebugEnabled()) {
                 logger.debug("Caught exception ", e);
@@ -278,13 +281,29 @@ public class JpaRelationshipStorageClient<T> extends JpaStorageClientImpl {
     }
 
     protected String getObjectId(ServiceContext ctx) {
-        String objectId = (String) ctx.getProperty("objectId");
+        String objectId = (String) ctx.getProperty("object-id");
         if (objectId == null) {
-            String msg = "objectId is missing in the context";
+            String msg = "object-id is missing in the context";
             logger.error(msg);
             throw new IllegalArgumentException(msg);
         }
 
         return objectId;
     }
+
+    /**
+     * getObject returns the object in the relationship
+     * @param ctx
+     * @param id
+     * @return
+     */
+    protected Object getObject(ServiceContext ctx, String id) {
+        Class objectClass = (Class) ctx.getProperty("object-class");
+        if (objectClass == null) {
+            String msg = "object-class is missing in the context";
+            logger.error(msg);
+            throw new IllegalArgumentException(msg);
+        }
+        return JpaStorageUtils.getEntity(id, objectClass);
+    }
 }
index 03286a81f377dbf07f86912582bab38bfbec3020..2fa6f554ee5011e8673c4fe29951f139157343a9 100644 (file)
@@ -179,15 +179,13 @@ public class JpaStorageClientImpl implements StorageClient {
         try {
             handler.prepare(Action.GET);
             Object o = null;
-            try {
-                o = JpaStorageUtils.getEntity(getEntityName(ctx), id, docFilter);
-            } catch (NoResultException nre) {
+            o = JpaStorageUtils.getEntity(getEntityName(ctx), id, docFilter);
+            if (null == o) {
                 if (em != null && em.getTransaction().isActive()) {
                     em.getTransaction().rollback();
                 }
                 String msg = "could not find entity with id=" + id;
-                logger.error(msg, nre);
-                throw new DocumentNotFoundException(msg, nre);
+                throw new DocumentNotFoundException(msg);
             }
             DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(o);
             handler.handle(Action.GET, wrapDoc);
@@ -459,8 +457,6 @@ public class JpaStorageClientImpl implements StorageClient {
         }
     }
 
-
-
     /**
      * getValue gets invokes specified accessor method on given object. Assumption
      * is that this is used for JavaBean pattern getXXX methods only.
index e676993140308751e4d9afaef290cd77ca44e0fc..5ea04e183483b0dac17d4b60e35a5a6a34eb4ceb 100644 (file)
@@ -26,6 +26,7 @@ package org.collectionspace.services.common.storage.jpa;
 import java.util.List;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
+import javax.persistence.NoResultException;
 import javax.persistence.Persistence;
 import javax.persistence.Query;
 import org.collectionspace.services.common.document.DocumentFilter;
@@ -47,7 +48,6 @@ public class JpaStorageUtils {
      * @param id
      * @param entityClazz
      * @return null if entity is not found
-     * @throws Exception
      */
     public static Object getEntity(String id, Class entityClazz) {
         EntityManagerFactory emf = null;
@@ -75,11 +75,9 @@ public class JpaStorageUtils {
      * @param entityName fully qualified entity name
      * @param id
      * @param docFilter
-     * @return
-     * @throws Exception
+     * @return null if entity is not found
      */
-    public static Object getEntity(String entityName, String id, DocumentFilter docFilter)
-            throws Exception {
+    public static Object getEntity(String entityName, String id, DocumentFilter docFilter) {
         EntityManagerFactory emf = null;
         EntityManager em = null;
         Object o = null;
@@ -96,7 +94,6 @@ public class JpaStorageUtils {
             if ((null != where) && (where.length() > 0)) {
                 queryStrBldr.append(" AND " + where);
             }
-
             emf = getEntityManagerFactory();
             em = emf.createEntityManager();
             String queryStr = queryStrBldr.toString(); //for debugging
@@ -107,11 +104,15 @@ public class JpaStorageUtils {
             for (DocumentFilter.ParamBinding p : params) {
                 q.setParameter(p.getName(), p.getValue());
             }
-
-            //require transaction for get?
-            em.getTransaction().begin();
             o = q.getSingleResult();
-            em.getTransaction().commit();
+        } catch (NoResultException nre) {
+            if (em != null && em.getTransaction().isActive()) {
+                em.getTransaction().rollback();
+            }
+            if (logger.isDebugEnabled()) {
+                logger.debug("could not find entity with id=" + id);
+            }
+            //returns null
         } finally {
             if (em != null) {
                 releaseEntityManagerFactory(emf);