@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
}
// ---------------------------------------------------------------
/** 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();
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);
// }
/* (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;
}
// 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);
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) {
}
-
@POST
@Path("{csid}/accountroles")
public Response createAccountRole(@PathParam("csid") String accCsid,
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;
//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();
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.
* @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;
}
return storageClient;
}
-
/**
* createAccountRole creates one or more account-role relationships
* between object (account/role) and subject (role/account)
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);
@Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
dependsOnMethods = {"create"})
public void createList(String testName) throws Exception {
-
}
// Failure outcomes
@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
}
// ---------------------------------------------------------------
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));
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));
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));
/** 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);
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)
*/
// 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);
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();
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;
}
--- /dev/null
+/**
+ * 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;
+ }
+}
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();
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);
}
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);
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);
}
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);
+ }
}
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);
}
}
-
-
/**
* getValue gets invokes specified accessor method on given object. Assumption
* is that this is used for JavaBean pattern getXXX methods only.
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;
* @param id
* @param entityClazz
* @return null if entity is not found
- * @throws Exception
*/
public static Object getEntity(String id, Class entityClazz) {
EntityManagerFactory emf = null;
* @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;
if ((null != where) && (where.length() > 0)) {
queryStrBldr.append(" AND " + where);
}
-
emf = getEntityManagerFactory();
em = emf.createEntityManager();
String queryStr = queryStrBldr.toString(); //for debugging
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);