--- /dev/null
+package org.apache.archiva.redback.rbac.jdo;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+import org.apache.archiva.redback.rbac.AbstractRBACManager;
+import org.apache.archiva.redback.rbac.Operation;
+import org.apache.archiva.redback.rbac.RBACManagerListener;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.rbac.RbacPermanentException;
+import org.apache.archiva.redback.rbac.Resource;
+import org.apache.archiva.redback.rbac.Role;
+import org.apache.archiva.redback.rbac.UserAssignment;
+import org.apache.archiva.redback.rbac.Permission;
+import org.apache.archiva.redback.rbac.RBACObjectAssertions;
+import org.codehaus.plexus.redback.rbac.jdo.JdoOperation;
+import org.codehaus.plexus.redback.rbac.jdo.JdoPermission;
+import org.codehaus.plexus.redback.rbac.jdo.JdoResource;
+import org.codehaus.plexus.redback.rbac.jdo.JdoRole;
+import org.codehaus.plexus.redback.rbac.jdo.JdoUserAssignment;
+import org.codehaus.plexus.redback.rbac.jdo.RbacJdoModelModelloMetadata;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import javax.jdo.JDOHelper;
+import javax.jdo.PersistenceManager;
+import javax.jdo.Transaction;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * JdoRbacManager:
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @author Jesse McConnell <jmcconnell@apache.org>
+ * @version $Id$
+ */
+@Service( "rBACManager#jdo" )
+public class JdoRbacManager
+ extends AbstractRBACManager
+ implements RBACManagerListener
+{
+ @Inject
+ private JdoTool jdo;
+
+ private boolean enableCache = true;
+
+ // private static final String ROLE_DETAIL = "role-child-detail";
+ private static final String ROLE_DETAIL = null;
+
+ // ----------------------------------------------------------------------
+ // Role methods
+ // ----------------------------------------------------------------------
+
+ /**
+ * Creates an implementation specific {@link Role}.
+ * <p/>
+ * Note: this method does not add the {@link Role} to the underlying store.
+ * a call to {@link #saveRole(Role)} is required to track the role created with this
+ * method call.
+ *
+ * @param name the name.
+ * @return the new {@link Role} object with an empty (non-null) {@link Role#getChildRoleNames()} object.
+ * @throws RbacManagerException
+ */
+ public Role createRole( String name )
+ {
+ Role role;
+
+ try
+ {
+ role = getRole( name );
+ }
+ catch ( RbacManagerException e )
+ {
+ role = new JdoRole();
+ role.setName( name );
+ }
+
+ return role;
+ }
+
+ /**
+ * Method addRole
+ *
+ * @param role
+ */
+ public Role saveRole( Role role )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( role );
+
+ return (Role) jdo.saveObject( role, new String[]{ ROLE_DETAIL } );
+ }
+
+ public boolean roleExists( Role role )
+ {
+ return jdo.objectExists( role );
+ }
+
+ public boolean roleExists( String name )
+ {
+ try
+ {
+ return jdo.objectExistsById( JdoRole.class, name );
+ }
+ catch ( RbacManagerException e )
+ {
+ return false;
+ }
+ }
+
+ /**
+ * @param roleName
+ * @return
+ * @throws RbacObjectNotFoundException
+ * @throws RbacManagerException
+ */
+ public Role getRole( String roleName )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ return (Role) jdo.getObjectById( JdoRole.class, roleName, ROLE_DETAIL );
+ }
+
+ /**
+ * Method getRoles
+ */
+ @SuppressWarnings( "unchecked" )
+ public List<Role> getAllRoles()
+ throws RbacManagerException
+ {
+ return (List<Role>) jdo.getAllObjects( JdoRole.class );
+ }
+
+ public void removeRole( Role role )
+ throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( role );
+
+ if ( role.isPermanent() )
+ {
+ throw new RbacPermanentException( "Unable to delete permanent role [" + role.getName() + "]" );
+ }
+
+ jdo.removeObject( role );
+ }
+
+ public void saveRoles( Collection<Role> roles )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ if ( roles == null )
+ {
+ // Nothing to do.
+ return;
+ }
+
+ // This is done in JdoRbacManager as opposed to JdoTool as we need to assertValid() on each role and
+ // also wrap the entire collection into a single atomic save/makePersistent.
+
+ PersistenceManager pm = jdo.getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ for ( Role role : roles )
+ {
+ if ( ( JDOHelper.getObjectId( role ) != null ) && !JDOHelper.isDetached( role ) )
+ {
+ // This is a fatal error that means we need to fix our code.
+ // Leave it as a JDOUserException, it's intentional.
+ throw new RbacManagerException( "Existing Role is not detached: " + role );
+ }
+
+ RBACObjectAssertions.assertValid( role );
+
+ pm.makePersistent( role );
+ }
+
+ tx.commit();
+ }
+ finally
+ {
+ jdo.rollbackIfActive( tx );
+ }
+ }
+
+ // ----------------------------------------------------------------------
+ // Permission methods
+ // ----------------------------------------------------------------------
+
+ /**
+ * Creates an implementation specific {@link Permission}.
+ * <p/>
+ * Note: this method does not add the {@link Permission} to the underlying store.
+ * a call to {@link #savePermission(Permission)} is required to track the permission created
+ * with this method call.
+ *
+ * @param name the name.
+ * @return the new Permission.
+ * @throws RbacManagerException
+ */
+ public Permission createPermission( String name )
+ throws RbacManagerException
+ {
+ Permission permission;
+
+ try
+ {
+ permission = getPermission( name );
+ log.debug( "Create Permission [{}] Returning Existing.", name );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ permission = new JdoPermission();
+ permission.setName( name );
+ log.debug( "Create Permission [{}] New JdoPermission.", name );
+ }
+
+ return permission;
+ }
+
+ /**
+ * Creates an implementation specific {@link Permission} with specified {@link Operation},
+ * and {@link Resource} identifiers.
+ * <p/>
+ * Note: this method does not add the Permission, Operation, or Resource to the underlying store.
+ * a call to {@link #savePermission(Permission)} is required to track the permission, operation,
+ * or resource created with this method call.
+ *
+ * @param name the name.
+ * @param operationName the {@link Operation#setName(String)} value
+ * @param resourceIdentifier the {@link Resource#setIdentifier(String)} value
+ * @return the new Permission.
+ * @throws RbacManagerException
+ */
+ public Permission createPermission( String name, String operationName, String resourceIdentifier )
+ throws RbacManagerException
+ {
+ Permission permission = new JdoPermission();
+ permission.setName( name );
+
+ Operation operation;
+ try
+ {
+ operation = getOperation( operationName );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ operation = new JdoOperation();
+ operation.setName( operationName );
+ }
+ permission.setOperation( operation );
+
+ Resource resource;
+ try
+ {
+ resource = getResource( resourceIdentifier );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ resource = new JdoResource();
+ resource.setIdentifier( resourceIdentifier );
+ }
+ permission.setResource( resource );
+
+ return permission;
+ }
+
+ public Permission savePermission( Permission permission )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( permission );
+
+ return (Permission) jdo.saveObject( permission, null );
+ }
+
+ public boolean permissionExists( Permission permission )
+ {
+ return jdo.objectExists( permission );
+ }
+
+ public boolean permissionExists( String name )
+ {
+ try
+ {
+ return jdo.objectExistsById( JdoPermission.class, name );
+ }
+ catch ( RbacManagerException e )
+ {
+ return false;
+ }
+ }
+
+ public Permission getPermission( String permissionName )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ return (Permission) jdo.getObjectById( JdoPermission.class, permissionName, null );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ public List<Permission> getAllPermissions()
+ throws RbacManagerException
+ {
+ return (List<Permission>) jdo.getAllObjects( JdoPermission.class );
+ }
+
+ public void removePermission( Permission permission )
+ throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( permission );
+
+ if ( permission.isPermanent() )
+ {
+ throw new RbacPermanentException( "Unable to delete permanent permission [" + permission.getName() + "]" );
+ }
+
+ jdo.removeObject( permission );
+ }
+
+ // ----------------------------------------------------------------------
+ // Operation methods
+ // ----------------------------------------------------------------------
+
+ /**
+ * Creates an implementation specific {@link Operation}.
+ * <p/>
+ * Note: this method does not add the {@link Operation} to the underlying store.
+ * a call to {@link #saveOperation(Operation)} is required to track the operation created
+ * with this method call.
+ *
+ * @param name the name.
+ * @return the new Operation.
+ * @throws RbacManagerException
+ */
+ public Operation createOperation( String name )
+ throws RbacManagerException
+ {
+ Operation operation;
+
+ try
+ {
+ operation = getOperation( name );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ operation = new JdoOperation();
+ operation.setName( name );
+ }
+
+ return operation;
+ }
+
+ public Operation saveOperation( Operation operation )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( operation );
+ return (Operation) jdo.saveObject( operation, null );
+ }
+
+ public boolean operationExists( Operation operation )
+ {
+ return jdo.objectExists( operation );
+ }
+
+ public boolean operationExists( String name )
+ {
+ try
+ {
+ return jdo.objectExistsById( JdoOperation.class, name );
+ }
+ catch ( RbacManagerException e )
+ {
+ return false;
+ }
+ }
+
+ public Operation getOperation( String operationName )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ return (Operation) jdo.getObjectById( JdoOperation.class, operationName, null );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ public List<Operation> getAllOperations()
+ throws RbacManagerException
+ {
+ return (List<Operation>) jdo.getAllObjects( JdoOperation.class );
+ }
+
+ public void removeOperation( Operation operation )
+ throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( operation );
+
+ if ( operation.isPermanent() )
+ {
+ throw new RbacPermanentException( "Unable to delete permanent operation [" + operation.getName() + "]" );
+ }
+
+ jdo.removeObject( operation );
+ }
+
+ // ----------------------------------------------------------------------
+ // Resource methods
+ // ----------------------------------------------------------------------
+
+ /**
+ * Creates an implementation specific {@link Resource}.
+ * <p/>
+ * Note: this method does not add the {@link Resource} to the underlying store.
+ * a call to {@link #saveResource(Resource)} is required to track the resource created
+ * with this method call.
+ *
+ * @param identifier the identifier.
+ * @return the new Resource.
+ * @throws RbacManagerException
+ */
+ public Resource createResource( String identifier )
+ throws RbacManagerException
+ {
+ Resource resource;
+
+ try
+ {
+ resource = getResource( identifier );
+ log.debug( "Create Resource [ {} ] Returning Existing.", identifier );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ resource = new JdoResource();
+ resource.setIdentifier( identifier );
+ log.debug( "Create Resource [ {} ] New JdoResource.", identifier );
+ }
+
+ return resource;
+ }
+
+ public Resource saveResource( Resource resource )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( resource );
+ return (Resource) jdo.saveObject( resource, null );
+ }
+
+ public boolean resourceExists( Resource resource )
+ {
+ return jdo.objectExists( resource );
+ }
+
+ public boolean resourceExists( String identifier )
+ {
+ try
+ {
+ return jdo.objectExistsById( JdoResource.class, identifier );
+ }
+ catch ( RbacManagerException e )
+ {
+ return false;
+ }
+ }
+
+ public Resource getResource( String resourceIdentifier )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ return (Resource) jdo.getObjectById( JdoResource.class, resourceIdentifier, null );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ public List<Resource> getAllResources()
+ throws RbacManagerException
+ {
+ return (List<Resource>) jdo.getAllObjects( JdoResource.class );
+ }
+
+ public void removeResource( Resource resource )
+ throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( resource );
+
+ if ( resource.isPermanent() )
+ {
+ throw new RbacPermanentException(
+ "Unable to delete permanent resource [" + resource.getIdentifier() + "]" );
+ }
+
+ jdo.removeObject( resource );
+ }
+
+ // ----------------------------------------------------------------------
+ // User Assignment methods
+ // ----------------------------------------------------------------------
+
+ /**
+ * Creates an implementation specific {@link UserAssignment}.
+ * <p/>
+ * Note: this method does not add the {@link UserAssignment} to the underlying store.
+ * a call to {@link #saveUserAssignment(UserAssignment)} is required to track the user
+ * assignment created with this method call.
+ *
+ * @param principal the principal reference to the user.
+ * @return the new UserAssignment with an empty (non-null) {@link UserAssignment#getRoleNames()} object.
+ * @throws RbacManagerException
+ */
+ public UserAssignment createUserAssignment( String principal )
+ {
+ UserAssignment ua;
+
+ try
+ {
+ ua = getUserAssignment( principal );
+ }
+ catch ( RbacManagerException e )
+ {
+ ua = new JdoUserAssignment();
+ ua.setPrincipal( principal );
+ }
+
+ return ua;
+ }
+
+ /**
+ * Method addUserAssignment
+ *
+ * @param userAssignment
+ */
+ public UserAssignment saveUserAssignment( UserAssignment userAssignment )
+ throws RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( "Save User Assignment", userAssignment );
+
+ fireRbacUserAssignmentSaved( userAssignment );
+
+ return (UserAssignment) jdo.saveObject( userAssignment, new String[]{ ROLE_DETAIL } );
+ }
+
+ public boolean userAssignmentExists( String principal )
+ {
+ try
+ {
+ return jdo.objectExistsById( JdoUserAssignment.class, principal );
+ }
+ catch ( RbacManagerException e )
+ {
+ return false;
+ }
+ }
+
+ public boolean userAssignmentExists( UserAssignment assignment )
+ {
+ return jdo.objectExists( assignment );
+ }
+
+ public UserAssignment getUserAssignment( String principal )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ return (UserAssignment) jdo.getObjectById( JdoUserAssignment.class, principal, ROLE_DETAIL );
+ }
+
+ /**
+ * Method getAssignments
+ */
+ @SuppressWarnings( "unchecked" )
+ public List<UserAssignment> getAllUserAssignments()
+ throws RbacManagerException
+ {
+ return (List<UserAssignment>) jdo.getAllObjects( JdoUserAssignment.class );
+ }
+
+ /**
+ * Method getUserAssignmentsForRoles
+ */
+ @SuppressWarnings( "unchecked" )
+ public List<UserAssignment> getUserAssignmentsForRoles( Collection<String> roleNames )
+ throws RbacManagerException
+ {
+ return (List<UserAssignment>) jdo.getUserAssignmentsForRoles( JdoUserAssignment.class, null, roleNames );
+ }
+
+ /**
+ * Method removeAssignment
+ *
+ * @param userAssignment
+ */
+ public void removeUserAssignment( UserAssignment userAssignment )
+ throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
+ {
+ RBACObjectAssertions.assertValid( userAssignment );
+
+ if ( userAssignment.isPermanent() )
+ {
+ throw new RbacPermanentException(
+ "Unable to delete permanent user assignment [" + userAssignment.getPrincipal() + "]" );
+ }
+
+ fireRbacUserAssignmentRemoved( userAssignment );
+
+ jdo.removeObject( userAssignment );
+ }
+
+ public void eraseDatabase()
+ {
+ // Must delete in order so that FK constraints don't get violated
+ jdo.removeAll( JdoRole.class );
+ jdo.removeAll( JdoPermission.class );
+ jdo.removeAll( JdoOperation.class );
+ jdo.removeAll( JdoResource.class );
+ jdo.removeAll( JdoUserAssignment.class );
+ jdo.removeAll( RbacJdoModelModelloMetadata.class );
+ }
+
+ @PostConstruct
+ public void initialize()
+ {
+ super.initialize();
+
+ jdo.setListener( this );
+ if ( enableCache )
+ {
+ jdo.enableCache( JdoRole.class );
+ jdo.enableCache( JdoOperation.class );
+ jdo.enableCache( JdoResource.class );
+ jdo.enableCache( JdoUserAssignment.class );
+ jdo.enableCache( JdoPermission.class );
+ }
+ }
+
+ public void rbacInit( boolean freshdb )
+ {
+ fireRbacInit( freshdb );
+ }
+
+ public void rbacPermissionRemoved( Permission permission )
+ {
+ fireRbacPermissionRemoved( permission );
+ }
+
+ public void rbacPermissionSaved( Permission permission )
+ {
+ fireRbacPermissionSaved( permission );
+ }
+
+ public void rbacRoleRemoved( Role role )
+ {
+ fireRbacRoleRemoved( role );
+ }
+
+ public void rbacRoleSaved( Role role )
+ {
+ fireRbacRoleSaved( role );
+ }
+
+
+ public void rbacUserAssignmentSaved( UserAssignment userAssignment )
+ {
+ fireRbacUserAssignmentSaved( userAssignment );
+ }
+
+ public void rbacUserAssignmentRemoved( UserAssignment userAssignment )
+ {
+ fireRbacUserAssignmentRemoved( userAssignment );
+ }
+
+ public JdoTool getJdo()
+ {
+ return jdo;
+ }
+
+ public void setJdo( JdoTool jdo )
+ {
+ this.jdo = jdo;
+ }
+
+ public boolean isEnableCache()
+ {
+ return enableCache;
+ }
+
+ public void setEnableCache( boolean enableCache )
+ {
+ this.enableCache = enableCache;
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.rbac.jdo;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+import org.apache.archiva.redback.rbac.Permission;
+import org.apache.archiva.redback.rbac.RBACManagerListener;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
+import org.apache.archiva.redback.rbac.Role;
+import org.codehaus.plexus.jdo.JdoFactory;
+import org.codehaus.plexus.redback.rbac.jdo.JdoRole;
+import org.codehaus.plexus.util.StringUtils;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.jdo.Extent;
+import javax.jdo.JDOException;
+import javax.jdo.JDOHelper;
+import javax.jdo.JDOObjectNotFoundException;
+import javax.jdo.JDOUserException;
+import javax.jdo.PersistenceManager;
+import javax.jdo.PersistenceManagerFactory;
+import javax.jdo.Query;
+import javax.jdo.Transaction;
+import javax.jdo.datastore.DataStoreCache;
+import javax.jdo.listener.DeleteLifecycleListener;
+import javax.jdo.listener.InstanceLifecycleEvent;
+import javax.jdo.listener.StoreLifecycleListener;
+import javax.jdo.spi.Detachable;
+import javax.jdo.spi.PersistenceCapable;
+import java.io.PrintStream;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * JdoTool - RBAC JDO Tools.
+ *
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+@Service("jdoTool")
+public class JdoTool
+ implements DeleteLifecycleListener, StoreLifecycleListener
+{
+
+ @Resource(name="jdoFactory#users")
+ private JdoFactory jdoFactory;
+
+ private PersistenceManagerFactory pmf;
+
+ private RBACManagerListener listener;
+
+ @PostConstruct
+ public void initialize()
+ {
+ pmf = jdoFactory.getPersistenceManagerFactory();
+
+ pmf.addInstanceLifecycleListener( this, null );
+ }
+
+ public static void dumpObjectState( PrintStream out, Object o )
+ {
+ final String STATE = "[STATE] ";
+ final String INDENT = " ";
+
+ if ( o == null )
+ {
+ out.println( STATE + "Object is null." );
+ return;
+ }
+
+ out.println( STATE + "Object " + o.getClass().getName() );
+
+ if ( !( o instanceof PersistenceCapable ) )
+ {
+ out.println( INDENT + "is NOT PersistenceCapable (not a jdo object?)" );
+ return;
+ }
+
+ out.println( INDENT + "is PersistenceCapable." );
+ if ( o instanceof Detachable )
+ {
+ out.println( INDENT + "is Detachable" );
+ }
+
+ out.println( INDENT + "is new : " + Boolean.toString( JDOHelper.isNew( o ) ) );
+ out.println( INDENT + "is transactional : " + Boolean.toString( JDOHelper.isTransactional( o ) ) );
+ out.println( INDENT + "is deleted : " + Boolean.toString( JDOHelper.isDeleted( o ) ) );
+ out.println( INDENT + "is detached : " + Boolean.toString( JDOHelper.isDetached( o ) ) );
+ out.println( INDENT + "is dirty : " + Boolean.toString( JDOHelper.isDirty( o ) ) );
+ out.println( INDENT + "is persistent : " + Boolean.toString( JDOHelper.isPersistent( o ) ) );
+
+ out.println( INDENT + "object id : " + JDOHelper.getObjectId( o ) );
+ }
+
+ public PersistenceManager getPersistenceManager()
+ {
+ PersistenceManager pm = pmf.getPersistenceManager();
+
+ pm.getFetchPlan().setMaxFetchDepth( -1 );
+
+ triggerInit();
+
+ return pm;
+ }
+
+ private boolean hasTriggeredInit = false;
+
+ @SuppressWarnings("unchecked")
+ public void triggerInit()
+ {
+ if ( !hasTriggeredInit )
+ {
+ hasTriggeredInit = true;
+
+ List<Role> roles = (List<Role>) getAllObjects( JdoRole.class );
+
+ listener.rbacInit( roles.isEmpty() );
+ }
+ }
+
+ public void enableCache( Class<?> clazz )
+ {
+ DataStoreCache cache = pmf.getDataStoreCache();
+ if ( cache.getClass().getName().equals( "org.jpox.cache.EhcacheClassBasedLevel2Cache" )
+ || cache.getClass().getName().equals( "org.jpox.cache.EhcacheLevel2Cache" ) )
+ {
+ /* Ehcache adapters don't support pinAll, the caching is handled in the configuration */
+ return;
+ }
+ cache.pinAll( clazz, false ); // Pin all objects of type clazz from now on
+ }
+
+ public Object saveObject( Object object )
+ {
+ return saveObject( object, null );
+ }
+
+ public Object saveObject( Object object, String[] fetchGroups )
+ {
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ if ( ( JDOHelper.getObjectId( object ) != null ) && !JDOHelper.isDetached( object ) )
+ {
+ // This is a fatal error that means we need to fix our code.
+ // Leave it as a JDOUserException, it's intentional.
+ throw new JDOUserException( "Existing object is not detached: " + object, object );
+ }
+
+ if ( fetchGroups != null )
+ {
+ for ( int i = 0; i >= fetchGroups.length; i++ )
+ {
+ pm.getFetchPlan().addGroup( fetchGroups[i] );
+ }
+ }
+
+ pm.makePersistent( object );
+
+ object = pm.detachCopy( object );
+
+ tx.commit();
+
+ return object;
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public List<?> getAllObjects( Class<?> clazz )
+ {
+ return getAllObjects( clazz, null, null );
+ }
+
+ public List<?> getAllObjects( Class<?> clazz, String ordering )
+ {
+ return getAllObjects( clazz, ordering, null );
+ }
+
+ public List<?> getAllObjects( Class<?> clazz, String ordering, String fetchGroup )
+ {
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ Extent extent = pm.getExtent( clazz, true );
+
+ Query query = pm.newQuery( extent );
+
+ if ( ordering != null )
+ {
+ query.setOrdering( ordering );
+ }
+
+ if ( fetchGroup != null )
+ {
+ pm.getFetchPlan().addGroup( fetchGroup );
+ }
+
+ List<?> result = (List<?>) query.execute();
+
+ result = (List<?>) pm.detachCopyAll( result );
+
+ tx.commit();
+
+ return result;
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public List<?> getUserAssignmentsForRoles( Class<?> clazz, String ordering, Collection<String> roleNames )
+ {
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ Extent extent = pm.getExtent( clazz, true );
+
+ Query query = pm.newQuery( extent );
+
+ if ( ordering != null )
+ {
+ query.setOrdering( ordering );
+ }
+
+ query.declareImports( "import java.lang.String" );
+
+ StringBuffer filter = new StringBuffer();
+
+ if ( roleNames.size() > 0 )
+ {
+ Iterator<String> i = roleNames.iterator();
+
+ filter.append( "this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
+
+ while ( i.hasNext() )
+ {
+ filter.append( " || this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
+ }
+
+ query.setFilter( filter.toString() );
+ }
+
+ List<?> result = (List<?>) query.execute();
+
+ result = (List<?>) pm.detachCopyAll( result );
+
+ tx.commit();
+
+ return result;
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public Object getObjectById( Class<?> clazz, String id, String fetchGroup )
+ throws RbacObjectNotFoundException, RbacManagerException
+ {
+ if ( StringUtils.isEmpty( id ) )
+ {
+ throw new RbacObjectNotFoundException(
+ "Unable to get object '" + clazz.getName() + "' from jdo using null/empty id." );
+ }
+
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ if ( fetchGroup != null )
+ {
+ pm.getFetchPlan().addGroup( fetchGroup );
+ }
+
+ Object objectId = pm.newObjectIdInstance( clazz, id );
+
+ Object object = pm.getObjectById( objectId );
+
+ object = pm.detachCopy( object );
+
+ tx.commit();
+
+ return object;
+ }
+ catch ( JDOObjectNotFoundException e )
+ {
+ throw new RbacObjectNotFoundException( "Unable to find RBAC Object '" + id + "' of type " +
+ clazz.getName() + " using fetch-group '" + fetchGroup + "'", e, id );
+ }
+ catch ( JDOException e )
+ {
+ throw new RbacManagerException( "Error in JDO during get of RBAC object id '" + id + "' of type " +
+ clazz.getName() + " using fetch-group '" + fetchGroup + "'", e );
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public boolean objectExists( Object object )
+ {
+ return ( JDOHelper.getObjectId( object ) != null );
+ }
+
+ public boolean objectExistsById( Class<?> clazz, String id )
+ throws RbacManagerException
+ {
+ try
+ {
+ Object o = getObjectById( clazz, id, null );
+ return ( o != null );
+ }
+ catch ( RbacObjectNotFoundException e )
+ {
+ return false;
+ }
+ }
+
+ public Object removeObject( Object o )
+ throws RbacManagerException
+ {
+ if ( o == null )
+ {
+ throw new RbacManagerException( "Unable to remove null object" );
+ }
+
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ o = pm.getObjectById( pm.getObjectId( o ) );
+
+ pm.deletePersistent( o );
+
+ tx.commit();
+
+ return o;
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public void rollbackIfActive( Transaction tx )
+ {
+ PersistenceManager pm = tx.getPersistenceManager();
+
+ try
+ {
+ if ( tx.isActive() )
+ {
+ tx.rollback();
+ }
+ }
+ finally
+ {
+ closePersistenceManager( pm );
+ }
+ }
+
+ public void closePersistenceManager( PersistenceManager pm )
+ {
+ try
+ {
+ pm.close();
+ }
+ catch ( JDOUserException e )
+ {
+ // ignore
+ }
+ }
+
+ public RBACManagerListener getListener()
+ {
+ return listener;
+ }
+
+ public void setListener( RBACManagerListener listener )
+ {
+ this.listener = listener;
+ }
+
+ public void postDelete( InstanceLifecycleEvent evt )
+ {
+ PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
+
+ if ( obj == null )
+ {
+ // Do not track null objects.
+ // These events are typically a product of an internal lifecycle event.
+ return;
+ }
+
+ if ( obj instanceof Role )
+ {
+ listener.rbacRoleRemoved( (Role) obj );
+ }
+ else if ( obj instanceof Permission )
+ {
+ listener.rbacPermissionRemoved( (Permission) obj );
+ }
+ }
+
+ public void preDelete( InstanceLifecycleEvent evt )
+ {
+ // ignore
+ }
+
+ public void postStore( InstanceLifecycleEvent evt )
+ {
+ PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
+
+ if ( obj instanceof Role )
+ {
+ listener.rbacRoleSaved( (Role) obj );
+ }
+ else if ( obj instanceof Permission )
+ {
+ listener.rbacPermissionSaved( (Permission) obj );
+ }
+ }
+
+ public void preStore( InstanceLifecycleEvent evt )
+ {
+ // ignore
+ }
+
+ public void removeAll( Class<?> aClass )
+ {
+ PersistenceManager pm = getPersistenceManager();
+ Transaction tx = pm.currentTransaction();
+
+ try
+ {
+ tx.begin();
+
+ Query query = pm.newQuery( aClass );
+ query.deletePersistentAll();
+
+ tx.commit();
+ }
+ finally
+ {
+ rollbackIfActive( tx );
+ }
+ }
+
+ public JdoFactory getJdoFactory()
+ {
+ return jdoFactory;
+ }
+
+ public void setJdoFactory( JdoFactory jdoFactory )
+ {
+ this.jdoFactory = jdoFactory;
+ }
+}
+++ /dev/null
-package org.codehaus.plexus.redback.rbac.jdo;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.
- */
-
-import org.apache.archiva.redback.rbac.AbstractRBACManager;
-import org.apache.archiva.redback.rbac.Operation;
-import org.apache.archiva.redback.rbac.RBACManagerListener;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.RbacObjectInvalidException;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.apache.archiva.redback.rbac.RbacPermanentException;
-import org.apache.archiva.redback.rbac.Resource;
-import org.apache.archiva.redback.rbac.Role;
-import org.apache.archiva.redback.rbac.UserAssignment;
-import org.apache.archiva.redback.rbac.Permission;
-import org.apache.archiva.redback.rbac.RBACObjectAssertions;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import javax.jdo.JDOHelper;
-import javax.jdo.PersistenceManager;
-import javax.jdo.Transaction;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * JdoRbacManager:
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @author Jesse McConnell <jmcconnell@apache.org>
- * @version $Id$
- */
-@Service( "rBACManager#jdo" )
-public class JdoRbacManager
- extends AbstractRBACManager
- implements RBACManagerListener
-{
- @Inject
- private JdoTool jdo;
-
- private boolean enableCache = true;
-
- // private static final String ROLE_DETAIL = "role-child-detail";
- private static final String ROLE_DETAIL = null;
-
- // ----------------------------------------------------------------------
- // Role methods
- // ----------------------------------------------------------------------
-
- /**
- * Creates an implementation specific {@link Role}.
- * <p/>
- * Note: this method does not add the {@link Role} to the underlying store.
- * a call to {@link #saveRole(Role)} is required to track the role created with this
- * method call.
- *
- * @param name the name.
- * @return the new {@link Role} object with an empty (non-null) {@link Role#getChildRoleNames()} object.
- * @throws RbacManagerException
- */
- public Role createRole( String name )
- {
- Role role;
-
- try
- {
- role = getRole( name );
- }
- catch ( RbacManagerException e )
- {
- role = new JdoRole();
- role.setName( name );
- }
-
- return role;
- }
-
- /**
- * Method addRole
- *
- * @param role
- */
- public Role saveRole( Role role )
- throws RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( role );
-
- return (Role) jdo.saveObject( role, new String[]{ ROLE_DETAIL } );
- }
-
- public boolean roleExists( Role role )
- {
- return jdo.objectExists( role );
- }
-
- public boolean roleExists( String name )
- {
- try
- {
- return jdo.objectExistsById( JdoRole.class, name );
- }
- catch ( RbacManagerException e )
- {
- return false;
- }
- }
-
- /**
- * @param roleName
- * @return
- * @throws RbacObjectNotFoundException
- * @throws RbacManagerException
- */
- public Role getRole( String roleName )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- return (Role) jdo.getObjectById( JdoRole.class, roleName, ROLE_DETAIL );
- }
-
- /**
- * Method getRoles
- */
- @SuppressWarnings( "unchecked" )
- public List<Role> getAllRoles()
- throws RbacManagerException
- {
- return (List<Role>) jdo.getAllObjects( JdoRole.class );
- }
-
- public void removeRole( Role role )
- throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( role );
-
- if ( role.isPermanent() )
- {
- throw new RbacPermanentException( "Unable to delete permanent role [" + role.getName() + "]" );
- }
-
- jdo.removeObject( role );
- }
-
- public void saveRoles( Collection<Role> roles )
- throws RbacObjectInvalidException, RbacManagerException
- {
- if ( roles == null )
- {
- // Nothing to do.
- return;
- }
-
- // This is done in JdoRbacManager as opposed to JdoTool as we need to assertValid() on each role and
- // also wrap the entire collection into a single atomic save/makePersistent.
-
- PersistenceManager pm = jdo.getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- for ( Role role : roles )
- {
- if ( ( JDOHelper.getObjectId( role ) != null ) && !JDOHelper.isDetached( role ) )
- {
- // This is a fatal error that means we need to fix our code.
- // Leave it as a JDOUserException, it's intentional.
- throw new RbacManagerException( "Existing Role is not detached: " + role );
- }
-
- RBACObjectAssertions.assertValid( role );
-
- pm.makePersistent( role );
- }
-
- tx.commit();
- }
- finally
- {
- jdo.rollbackIfActive( tx );
- }
- }
-
- // ----------------------------------------------------------------------
- // Permission methods
- // ----------------------------------------------------------------------
-
- /**
- * Creates an implementation specific {@link Permission}.
- * <p/>
- * Note: this method does not add the {@link Permission} to the underlying store.
- * a call to {@link #savePermission(Permission)} is required to track the permission created
- * with this method call.
- *
- * @param name the name.
- * @return the new Permission.
- * @throws RbacManagerException
- */
- public Permission createPermission( String name )
- throws RbacManagerException
- {
- Permission permission;
-
- try
- {
- permission = getPermission( name );
- log.debug( "Create Permission [{}] Returning Existing.", name );
- }
- catch ( RbacObjectNotFoundException e )
- {
- permission = new JdoPermission();
- permission.setName( name );
- log.debug( "Create Permission [{}] New JdoPermission.", name );
- }
-
- return permission;
- }
-
- /**
- * Creates an implementation specific {@link Permission} with specified {@link Operation},
- * and {@link Resource} identifiers.
- * <p/>
- * Note: this method does not add the Permission, Operation, or Resource to the underlying store.
- * a call to {@link #savePermission(Permission)} is required to track the permission, operation,
- * or resource created with this method call.
- *
- * @param name the name.
- * @param operationName the {@link Operation#setName(String)} value
- * @param resourceIdentifier the {@link Resource#setIdentifier(String)} value
- * @return the new Permission.
- * @throws RbacManagerException
- */
- public Permission createPermission( String name, String operationName, String resourceIdentifier )
- throws RbacManagerException
- {
- Permission permission = new JdoPermission();
- permission.setName( name );
-
- Operation operation;
- try
- {
- operation = getOperation( operationName );
- }
- catch ( RbacObjectNotFoundException e )
- {
- operation = new JdoOperation();
- operation.setName( operationName );
- }
- permission.setOperation( operation );
-
- Resource resource;
- try
- {
- resource = getResource( resourceIdentifier );
- }
- catch ( RbacObjectNotFoundException e )
- {
- resource = new JdoResource();
- resource.setIdentifier( resourceIdentifier );
- }
- permission.setResource( resource );
-
- return permission;
- }
-
- public Permission savePermission( Permission permission )
- throws RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( permission );
-
- return (Permission) jdo.saveObject( permission, null );
- }
-
- public boolean permissionExists( Permission permission )
- {
- return jdo.objectExists( permission );
- }
-
- public boolean permissionExists( String name )
- {
- try
- {
- return jdo.objectExistsById( JdoPermission.class, name );
- }
- catch ( RbacManagerException e )
- {
- return false;
- }
- }
-
- public Permission getPermission( String permissionName )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- return (Permission) jdo.getObjectById( JdoPermission.class, permissionName, null );
- }
-
- @SuppressWarnings( "unchecked" )
- public List<Permission> getAllPermissions()
- throws RbacManagerException
- {
- return (List<Permission>) jdo.getAllObjects( JdoPermission.class );
- }
-
- public void removePermission( Permission permission )
- throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( permission );
-
- if ( permission.isPermanent() )
- {
- throw new RbacPermanentException( "Unable to delete permanent permission [" + permission.getName() + "]" );
- }
-
- jdo.removeObject( permission );
- }
-
- // ----------------------------------------------------------------------
- // Operation methods
- // ----------------------------------------------------------------------
-
- /**
- * Creates an implementation specific {@link Operation}.
- * <p/>
- * Note: this method does not add the {@link Operation} to the underlying store.
- * a call to {@link #saveOperation(Operation)} is required to track the operation created
- * with this method call.
- *
- * @param name the name.
- * @return the new Operation.
- * @throws RbacManagerException
- */
- public Operation createOperation( String name )
- throws RbacManagerException
- {
- Operation operation;
-
- try
- {
- operation = getOperation( name );
- }
- catch ( RbacObjectNotFoundException e )
- {
- operation = new JdoOperation();
- operation.setName( name );
- }
-
- return operation;
- }
-
- public Operation saveOperation( Operation operation )
- throws RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( operation );
- return (Operation) jdo.saveObject( operation, null );
- }
-
- public boolean operationExists( Operation operation )
- {
- return jdo.objectExists( operation );
- }
-
- public boolean operationExists( String name )
- {
- try
- {
- return jdo.objectExistsById( JdoOperation.class, name );
- }
- catch ( RbacManagerException e )
- {
- return false;
- }
- }
-
- public Operation getOperation( String operationName )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- return (Operation) jdo.getObjectById( JdoOperation.class, operationName, null );
- }
-
- @SuppressWarnings( "unchecked" )
- public List<Operation> getAllOperations()
- throws RbacManagerException
- {
- return (List<Operation>) jdo.getAllObjects( JdoOperation.class );
- }
-
- public void removeOperation( Operation operation )
- throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( operation );
-
- if ( operation.isPermanent() )
- {
- throw new RbacPermanentException( "Unable to delete permanent operation [" + operation.getName() + "]" );
- }
-
- jdo.removeObject( operation );
- }
-
- // ----------------------------------------------------------------------
- // Resource methods
- // ----------------------------------------------------------------------
-
- /**
- * Creates an implementation specific {@link Resource}.
- * <p/>
- * Note: this method does not add the {@link Resource} to the underlying store.
- * a call to {@link #saveResource(Resource)} is required to track the resource created
- * with this method call.
- *
- * @param identifier the identifier.
- * @return the new Resource.
- * @throws RbacManagerException
- */
- public Resource createResource( String identifier )
- throws RbacManagerException
- {
- Resource resource;
-
- try
- {
- resource = getResource( identifier );
- log.debug( "Create Resource [ {} ] Returning Existing.", identifier );
- }
- catch ( RbacObjectNotFoundException e )
- {
- resource = new JdoResource();
- resource.setIdentifier( identifier );
- log.debug( "Create Resource [ {} ] New JdoResource.", identifier );
- }
-
- return resource;
- }
-
- public Resource saveResource( Resource resource )
- throws RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( resource );
- return (Resource) jdo.saveObject( resource, null );
- }
-
- public boolean resourceExists( Resource resource )
- {
- return jdo.objectExists( resource );
- }
-
- public boolean resourceExists( String identifier )
- {
- try
- {
- return jdo.objectExistsById( JdoResource.class, identifier );
- }
- catch ( RbacManagerException e )
- {
- return false;
- }
- }
-
- public Resource getResource( String resourceIdentifier )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- return (Resource) jdo.getObjectById( JdoResource.class, resourceIdentifier, null );
- }
-
- @SuppressWarnings( "unchecked" )
- public List<Resource> getAllResources()
- throws RbacManagerException
- {
- return (List<Resource>) jdo.getAllObjects( JdoResource.class );
- }
-
- public void removeResource( Resource resource )
- throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( resource );
-
- if ( resource.isPermanent() )
- {
- throw new RbacPermanentException(
- "Unable to delete permanent resource [" + resource.getIdentifier() + "]" );
- }
-
- jdo.removeObject( resource );
- }
-
- // ----------------------------------------------------------------------
- // User Assignment methods
- // ----------------------------------------------------------------------
-
- /**
- * Creates an implementation specific {@link UserAssignment}.
- * <p/>
- * Note: this method does not add the {@link UserAssignment} to the underlying store.
- * a call to {@link #saveUserAssignment(UserAssignment)} is required to track the user
- * assignment created with this method call.
- *
- * @param principal the principal reference to the user.
- * @return the new UserAssignment with an empty (non-null) {@link UserAssignment#getRoleNames()} object.
- * @throws RbacManagerException
- */
- public UserAssignment createUserAssignment( String principal )
- {
- UserAssignment ua;
-
- try
- {
- ua = getUserAssignment( principal );
- }
- catch ( RbacManagerException e )
- {
- ua = new JdoUserAssignment();
- ua.setPrincipal( principal );
- }
-
- return ua;
- }
-
- /**
- * Method addUserAssignment
- *
- * @param userAssignment
- */
- public UserAssignment saveUserAssignment( UserAssignment userAssignment )
- throws RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( "Save User Assignment", userAssignment );
-
- fireRbacUserAssignmentSaved( userAssignment );
-
- return (UserAssignment) jdo.saveObject( userAssignment, new String[]{ ROLE_DETAIL } );
- }
-
- public boolean userAssignmentExists( String principal )
- {
- try
- {
- return jdo.objectExistsById( JdoUserAssignment.class, principal );
- }
- catch ( RbacManagerException e )
- {
- return false;
- }
- }
-
- public boolean userAssignmentExists( UserAssignment assignment )
- {
- return jdo.objectExists( assignment );
- }
-
- public UserAssignment getUserAssignment( String principal )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- return (UserAssignment) jdo.getObjectById( JdoUserAssignment.class, principal, ROLE_DETAIL );
- }
-
- /**
- * Method getAssignments
- */
- @SuppressWarnings( "unchecked" )
- public List<UserAssignment> getAllUserAssignments()
- throws RbacManagerException
- {
- return (List<UserAssignment>) jdo.getAllObjects( JdoUserAssignment.class );
- }
-
- /**
- * Method getUserAssignmentsForRoles
- */
- @SuppressWarnings( "unchecked" )
- public List<UserAssignment> getUserAssignmentsForRoles( Collection<String> roleNames )
- throws RbacManagerException
- {
- return (List<UserAssignment>) jdo.getUserAssignmentsForRoles( JdoUserAssignment.class, null, roleNames );
- }
-
- /**
- * Method removeAssignment
- *
- * @param userAssignment
- */
- public void removeUserAssignment( UserAssignment userAssignment )
- throws RbacObjectNotFoundException, RbacObjectInvalidException, RbacManagerException
- {
- RBACObjectAssertions.assertValid( userAssignment );
-
- if ( userAssignment.isPermanent() )
- {
- throw new RbacPermanentException(
- "Unable to delete permanent user assignment [" + userAssignment.getPrincipal() + "]" );
- }
-
- fireRbacUserAssignmentRemoved( userAssignment );
-
- jdo.removeObject( userAssignment );
- }
-
- public void eraseDatabase()
- {
- // Must delete in order so that FK constraints don't get violated
- jdo.removeAll( JdoRole.class );
- jdo.removeAll( JdoPermission.class );
- jdo.removeAll( JdoOperation.class );
- jdo.removeAll( JdoResource.class );
- jdo.removeAll( JdoUserAssignment.class );
- jdo.removeAll( RbacJdoModelModelloMetadata.class );
- }
-
- @PostConstruct
- public void initialize()
- {
- super.initialize();
-
- jdo.setListener( this );
- if ( enableCache )
- {
- jdo.enableCache( JdoRole.class );
- jdo.enableCache( JdoOperation.class );
- jdo.enableCache( JdoResource.class );
- jdo.enableCache( JdoUserAssignment.class );
- jdo.enableCache( JdoPermission.class );
- }
- }
-
- public void rbacInit( boolean freshdb )
- {
- fireRbacInit( freshdb );
- }
-
- public void rbacPermissionRemoved( Permission permission )
- {
- fireRbacPermissionRemoved( permission );
- }
-
- public void rbacPermissionSaved( Permission permission )
- {
- fireRbacPermissionSaved( permission );
- }
-
- public void rbacRoleRemoved( Role role )
- {
- fireRbacRoleRemoved( role );
- }
-
- public void rbacRoleSaved( Role role )
- {
- fireRbacRoleSaved( role );
- }
-
-
- public void rbacUserAssignmentSaved( UserAssignment userAssignment )
- {
- fireRbacUserAssignmentSaved( userAssignment );
- }
-
- public void rbacUserAssignmentRemoved( UserAssignment userAssignment )
- {
- fireRbacUserAssignmentRemoved( userAssignment );
- }
-
- public JdoTool getJdo()
- {
- return jdo;
- }
-
- public void setJdo( JdoTool jdo )
- {
- this.jdo = jdo;
- }
-
- public boolean isEnableCache()
- {
- return enableCache;
- }
-
- public void setEnableCache( boolean enableCache )
- {
- this.enableCache = enableCache;
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.rbac.jdo;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.
- */
-
-import org.apache.archiva.redback.rbac.Permission;
-import org.apache.archiva.redback.rbac.RBACManagerListener;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.apache.archiva.redback.rbac.RbacObjectNotFoundException;
-import org.apache.archiva.redback.rbac.Role;
-import org.codehaus.plexus.jdo.JdoFactory;
-import org.codehaus.plexus.util.StringUtils;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.Resource;
-import javax.jdo.Extent;
-import javax.jdo.JDOException;
-import javax.jdo.JDOHelper;
-import javax.jdo.JDOObjectNotFoundException;
-import javax.jdo.JDOUserException;
-import javax.jdo.PersistenceManager;
-import javax.jdo.PersistenceManagerFactory;
-import javax.jdo.Query;
-import javax.jdo.Transaction;
-import javax.jdo.datastore.DataStoreCache;
-import javax.jdo.listener.DeleteLifecycleListener;
-import javax.jdo.listener.InstanceLifecycleEvent;
-import javax.jdo.listener.StoreLifecycleListener;
-import javax.jdo.spi.Detachable;
-import javax.jdo.spi.PersistenceCapable;
-import java.io.PrintStream;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * JdoTool - RBAC JDO Tools.
- *
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-@Service("jdoTool")
-public class JdoTool
- implements DeleteLifecycleListener, StoreLifecycleListener
-{
-
- @Resource(name="jdoFactory#users")
- private JdoFactory jdoFactory;
-
- private PersistenceManagerFactory pmf;
-
- private RBACManagerListener listener;
-
- @PostConstruct
- public void initialize()
- {
- pmf = jdoFactory.getPersistenceManagerFactory();
-
- pmf.addInstanceLifecycleListener( this, null );
- }
-
- public static void dumpObjectState( PrintStream out, Object o )
- {
- final String STATE = "[STATE] ";
- final String INDENT = " ";
-
- if ( o == null )
- {
- out.println( STATE + "Object is null." );
- return;
- }
-
- out.println( STATE + "Object " + o.getClass().getName() );
-
- if ( !( o instanceof PersistenceCapable ) )
- {
- out.println( INDENT + "is NOT PersistenceCapable (not a jdo object?)" );
- return;
- }
-
- out.println( INDENT + "is PersistenceCapable." );
- if ( o instanceof Detachable )
- {
- out.println( INDENT + "is Detachable" );
- }
-
- out.println( INDENT + "is new : " + Boolean.toString( JDOHelper.isNew( o ) ) );
- out.println( INDENT + "is transactional : " + Boolean.toString( JDOHelper.isTransactional( o ) ) );
- out.println( INDENT + "is deleted : " + Boolean.toString( JDOHelper.isDeleted( o ) ) );
- out.println( INDENT + "is detached : " + Boolean.toString( JDOHelper.isDetached( o ) ) );
- out.println( INDENT + "is dirty : " + Boolean.toString( JDOHelper.isDirty( o ) ) );
- out.println( INDENT + "is persistent : " + Boolean.toString( JDOHelper.isPersistent( o ) ) );
-
- out.println( INDENT + "object id : " + JDOHelper.getObjectId( o ) );
- }
-
- public PersistenceManager getPersistenceManager()
- {
- PersistenceManager pm = pmf.getPersistenceManager();
-
- pm.getFetchPlan().setMaxFetchDepth( -1 );
-
- triggerInit();
-
- return pm;
- }
-
- private boolean hasTriggeredInit = false;
-
- @SuppressWarnings("unchecked")
- public void triggerInit()
- {
- if ( !hasTriggeredInit )
- {
- hasTriggeredInit = true;
-
- List<Role> roles = (List<Role>) getAllObjects( JdoRole.class );
-
- listener.rbacInit( roles.isEmpty() );
- }
- }
-
- public void enableCache( Class<?> clazz )
- {
- DataStoreCache cache = pmf.getDataStoreCache();
- if ( cache.getClass().getName().equals( "org.jpox.cache.EhcacheClassBasedLevel2Cache" )
- || cache.getClass().getName().equals( "org.jpox.cache.EhcacheLevel2Cache" ) )
- {
- /* Ehcache adapters don't support pinAll, the caching is handled in the configuration */
- return;
- }
- cache.pinAll( clazz, false ); // Pin all objects of type clazz from now on
- }
-
- public Object saveObject( Object object )
- {
- return saveObject( object, null );
- }
-
- public Object saveObject( Object object, String[] fetchGroups )
- {
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- if ( ( JDOHelper.getObjectId( object ) != null ) && !JDOHelper.isDetached( object ) )
- {
- // This is a fatal error that means we need to fix our code.
- // Leave it as a JDOUserException, it's intentional.
- throw new JDOUserException( "Existing object is not detached: " + object, object );
- }
-
- if ( fetchGroups != null )
- {
- for ( int i = 0; i >= fetchGroups.length; i++ )
- {
- pm.getFetchPlan().addGroup( fetchGroups[i] );
- }
- }
-
- pm.makePersistent( object );
-
- object = pm.detachCopy( object );
-
- tx.commit();
-
- return object;
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public List<?> getAllObjects( Class<?> clazz )
- {
- return getAllObjects( clazz, null, null );
- }
-
- public List<?> getAllObjects( Class<?> clazz, String ordering )
- {
- return getAllObjects( clazz, ordering, null );
- }
-
- public List<?> getAllObjects( Class<?> clazz, String ordering, String fetchGroup )
- {
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- Extent extent = pm.getExtent( clazz, true );
-
- Query query = pm.newQuery( extent );
-
- if ( ordering != null )
- {
- query.setOrdering( ordering );
- }
-
- if ( fetchGroup != null )
- {
- pm.getFetchPlan().addGroup( fetchGroup );
- }
-
- List<?> result = (List<?>) query.execute();
-
- result = (List<?>) pm.detachCopyAll( result );
-
- tx.commit();
-
- return result;
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public List<?> getUserAssignmentsForRoles( Class<?> clazz, String ordering, Collection<String> roleNames )
- {
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- Extent extent = pm.getExtent( clazz, true );
-
- Query query = pm.newQuery( extent );
-
- if ( ordering != null )
- {
- query.setOrdering( ordering );
- }
-
- query.declareImports( "import java.lang.String" );
-
- StringBuffer filter = new StringBuffer();
-
- if ( roleNames.size() > 0 )
- {
- Iterator<String> i = roleNames.iterator();
-
- filter.append( "this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
-
- while ( i.hasNext() )
- {
- filter.append( " || this.roleNames.contains(\"" ).append( i.next() ).append( "\")" );
- }
-
- query.setFilter( filter.toString() );
- }
-
- List<?> result = (List<?>) query.execute();
-
- result = (List<?>) pm.detachCopyAll( result );
-
- tx.commit();
-
- return result;
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public Object getObjectById( Class<?> clazz, String id, String fetchGroup )
- throws RbacObjectNotFoundException, RbacManagerException
- {
- if ( StringUtils.isEmpty( id ) )
- {
- throw new RbacObjectNotFoundException(
- "Unable to get object '" + clazz.getName() + "' from jdo using null/empty id." );
- }
-
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- if ( fetchGroup != null )
- {
- pm.getFetchPlan().addGroup( fetchGroup );
- }
-
- Object objectId = pm.newObjectIdInstance( clazz, id );
-
- Object object = pm.getObjectById( objectId );
-
- object = pm.detachCopy( object );
-
- tx.commit();
-
- return object;
- }
- catch ( JDOObjectNotFoundException e )
- {
- throw new RbacObjectNotFoundException( "Unable to find RBAC Object '" + id + "' of type " +
- clazz.getName() + " using fetch-group '" + fetchGroup + "'", e, id );
- }
- catch ( JDOException e )
- {
- throw new RbacManagerException( "Error in JDO during get of RBAC object id '" + id + "' of type " +
- clazz.getName() + " using fetch-group '" + fetchGroup + "'", e );
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public boolean objectExists( Object object )
- {
- return ( JDOHelper.getObjectId( object ) != null );
- }
-
- public boolean objectExistsById( Class<?> clazz, String id )
- throws RbacManagerException
- {
- try
- {
- Object o = getObjectById( clazz, id, null );
- return ( o != null );
- }
- catch ( RbacObjectNotFoundException e )
- {
- return false;
- }
- }
-
- public Object removeObject( Object o )
- throws RbacManagerException
- {
- if ( o == null )
- {
- throw new RbacManagerException( "Unable to remove null object" );
- }
-
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- o = pm.getObjectById( pm.getObjectId( o ) );
-
- pm.deletePersistent( o );
-
- tx.commit();
-
- return o;
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public void rollbackIfActive( Transaction tx )
- {
- PersistenceManager pm = tx.getPersistenceManager();
-
- try
- {
- if ( tx.isActive() )
- {
- tx.rollback();
- }
- }
- finally
- {
- closePersistenceManager( pm );
- }
- }
-
- public void closePersistenceManager( PersistenceManager pm )
- {
- try
- {
- pm.close();
- }
- catch ( JDOUserException e )
- {
- // ignore
- }
- }
-
- public RBACManagerListener getListener()
- {
- return listener;
- }
-
- public void setListener( RBACManagerListener listener )
- {
- this.listener = listener;
- }
-
- public void postDelete( InstanceLifecycleEvent evt )
- {
- PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
-
- if ( obj == null )
- {
- // Do not track null objects.
- // These events are typically a product of an internal lifecycle event.
- return;
- }
-
- if ( obj instanceof Role )
- {
- listener.rbacRoleRemoved( (Role) obj );
- }
- else if ( obj instanceof Permission )
- {
- listener.rbacPermissionRemoved( (Permission) obj );
- }
- }
-
- public void preDelete( InstanceLifecycleEvent evt )
- {
- // ignore
- }
-
- public void postStore( InstanceLifecycleEvent evt )
- {
- PersistenceCapable obj = ( (PersistenceCapable) evt.getSource() );
-
- if ( obj instanceof Role )
- {
- listener.rbacRoleSaved( (Role) obj );
- }
- else if ( obj instanceof Permission )
- {
- listener.rbacPermissionSaved( (Permission) obj );
- }
- }
-
- public void preStore( InstanceLifecycleEvent evt )
- {
- // ignore
- }
-
- public void removeAll( Class<?> aClass )
- {
- PersistenceManager pm = getPersistenceManager();
- Transaction tx = pm.currentTransaction();
-
- try
- {
- tx.begin();
-
- Query query = pm.newQuery( aClass );
- query.deletePersistentAll();
-
- tx.commit();
- }
- finally
- {
- rollbackIfActive( tx );
- }
- }
-
- public JdoFactory getJdoFactory()
- {
- return jdoFactory;
- }
-
- public void setJdoFactory( JdoFactory jdoFactory )
- {
- this.jdoFactory = jdoFactory;
- }
-}
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd"
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
- <bean name="rBACManager#jdo" class="org.codehaus.plexus.redback.rbac.jdo.JdoRbacManager" init-method="initialize">
+ <bean name="rBACManager#jdo" class="org.apache.archiva.redback.rbac.jdo.JdoRbacManager" init-method="initialize">
<property name="jdo" ref="jdoTool"/>
</bean>
- <bean id="jdoTool" class="org.codehaus.plexus.redback.rbac.jdo.JdoTool" init-method="initialize" lazy-init="true">
+ <bean id="jdoTool" class="org.apache.archiva.redback.rbac.jdo.JdoTool" init-method="initialize" lazy-init="true">
<property name="jdoFactory" ref="jdoFactory#users"/>
</bean>
</beans>
\ No newline at end of file
--- /dev/null
+package org.apache.archiva.redback.rbac.jdo;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+import net.sf.ehcache.CacheManager;
+import org.apache.archiva.redback.rbac.RbacManagerException;
+import org.apache.archiva.redback.rbac.jdo.JdoRbacManager;
+import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory;
+import org.apache.archiva.redback.common.jdo.test.StoreManagerDebug;
+import org.apache.archiva.redback.rbac.RBACManager;
+import org.codehaus.plexus.redback.tests.AbstractRbacManagerTestCase;
+import org.jpox.AbstractPersistenceManagerFactory;
+import org.jpox.SchemaTool;
+import org.junit.Before;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.jdo.PersistenceManager;
+import javax.jdo.PersistenceManagerFactory;
+import java.io.File;
+import java.net.URL;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * JdoRbacManagerTest:
+ *
+ * @author Jesse McConnell <jmcconnell@apache.org>
+ * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
+ * @version $Id$
+ */
+public class JdoRbacManagerTest
+ extends AbstractRbacManagerTestCase
+{
+ private StoreManagerDebug storeManager;
+
+ @Inject
+ @Named( value = "jdoFactory#users" )
+ DefaultConfigurableJdoFactory jdoFactory;
+
+ @Inject
+ @Named( value = "rBACManager#jdo" )
+ RBACManager rbacManager;
+
+ /**
+ * Creates a new RbacStore which contains no data.
+ */
+ @Before
+ public void setUp()
+ throws Exception
+ {
+
+ super.setUp();
+
+ assertEquals( DefaultConfigurableJdoFactory.class.getName(), jdoFactory.getClass().getName() );
+
+ jdoFactory.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" ); //$NON-NLS-1$
+
+ jdoFactory.setDriverName(
+ System.getProperty( "jdo.test.driver", "org.hsqldb.jdbcDriver" ) ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ jdoFactory.setUrl(
+ System.getProperty( "jdo.test.url", "jdbc:hsqldb:mem:" + getName() ) ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ jdoFactory.setUserName( System.getProperty( "jdo.test.user", "sa" ) ); //$NON-NLS-1$
+
+ jdoFactory.setPassword( System.getProperty( "jdo.test.pass", "" ) ); //$NON-NLS-1$
+
+ jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ jdoFactory.setProperty( "org.jpox.autoCreateTables", "true" );
+
+ jdoFactory.setProperty( "javax.jdo.option.RetainValues", "true" );
+
+ jdoFactory.setProperty( "javax.jdo.option.RestoreValues", "true" );
+
+ // jdoFactory.setProperty( "org.jpox.autoCreateColumns", "true" );
+
+ jdoFactory.setProperty( "org.jpox.validateTables", "true" );
+
+ jdoFactory.setProperty( "org.jpox.validateColumns", "true" );
+
+ jdoFactory.setProperty( "org.jpox.validateConstraints", "true" );
+
+ /* Enable the level 2 Ehcache class-based cache */
+ jdoFactory.setProperty( "org.jpox.cache.level2", "true" );
+ jdoFactory.setProperty( "org.jpox.cache.level2.type", "ehcacheclassbased" );
+ jdoFactory.setProperty( "org.jpox.cache.level2.configurationFile", "/ehcache.xml" ); // ehcache config
+ jdoFactory.setProperty( "org.jpox.cache.level2.cacheName", "default" ); // default cache name
+
+ Properties properties = jdoFactory.getProperties();
+
+ for ( Map.Entry<Object, Object> entry : properties.entrySet() )
+ {
+ System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
+ }
+
+ URL[] jdoFileUrls =
+ new URL[]{ getClass().getResource( "/org/codehaus/plexus/redback/rbac/jdo/package.jdo" ) }; //$NON-NLS-1$
+
+
+
+ if ( ( jdoFileUrls == null ) || ( jdoFileUrls[0] == null ) )
+ {
+ fail( "Unable to process test " + getName() + " - missing package.jdo." );
+ }
+
+ File propsFile = null; // intentional
+ boolean verbose = true;
+
+ PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
+
+ assertNotNull( pmf );
+
+ /* set our own Store Manager to allow counting SQL statements */
+ StoreManagerDebug.setup( (AbstractPersistenceManagerFactory) pmf );
+
+ /* clean up the db */
+ SchemaTool.deleteSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose );
+ SchemaTool.createSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose, null );
+
+ PersistenceManager pm = pmf.getPersistenceManager();
+
+ pm.close();
+
+ setRbacManager( rbacManager );
+
+ /* save the store manager to access the queries executed */
+ JdoRbacManager rbacManager = (JdoRbacManager) getRbacManager();
+ storeManager = StoreManagerDebug.getConfiguredStoreManager( rbacManager.getJdo().getPersistenceManager() );
+ }
+
+
+ @Override
+ public void testGetAssignedRoles()
+ throws RbacManagerException
+ {
+ storeManager.resetCounter();
+ super.testGetAssignedRoles();
+ int counter = storeManager.counter();
+ /* without Level 2 cache: 15 queries */
+ /* with Level 2 cache: 8 queries */
+ assertEquals( "Number of SQL queries", 8, counter );
+ }
+
+ @Override
+ public void testGetAssignedPermissionsDeep()
+ throws RbacManagerException
+ {
+ super.testGetAssignedPermissionsDeep();
+ int counter = storeManager.counter();
+ /* without Level 2 cache: 26 queries */
+ /* with Level 2 cache: 10 queries */
+ assertEquals( "Number of SQL queries", 10, counter );
+ }
+
+ @Override
+ protected void afterSetup()
+ {
+ super.afterSetup();
+ storeManager.resetCounter();
+ }
+
+ @Override
+ public void testLargeApplicationInit()
+ throws RbacManagerException
+ {
+ for (String cacheName : CacheManager.getInstance().getCacheNames())
+ {
+ CacheManager.getInstance().getCache( cacheName ).removeAll();
+ }
+ super.testLargeApplicationInit();
+ }
+
+ @Override
+ public void testGetRolesDeep()
+ throws RbacManagerException
+ {
+ for (String cacheName : CacheManager.getInstance().getCacheNames())
+ {
+ CacheManager.getInstance().getCache( cacheName ).removeAll();
+ }
+ super.testGetRolesDeep();
+ }
+
+
+ @Override
+ public void testStoreInitialization()
+ throws Exception
+ {
+ rbacManager.eraseDatabase();
+ eventTracker.rbacInit( true );
+ super.testStoreInitialization();
+ }
+}
--- /dev/null
+package org.apache.archiva.redback.rbac.jdo;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+import javax.xml.stream.XMLStreamException;
+
+import junit.framework.TestCase;
+
+import org.apache.archiva.redback.rbac.Operation;
+import org.apache.archiva.redback.rbac.Resource;
+import org.codehaus.plexus.redback.rbac.jdo.JdoOperation;
+import org.codehaus.plexus.redback.rbac.jdo.JdoPermission;
+import org.codehaus.plexus.redback.rbac.jdo.JdoResource;
+import org.codehaus.plexus.redback.rbac.jdo.JdoRole;
+import org.codehaus.plexus.redback.rbac.jdo.JdoUserAssignment;
+import org.codehaus.plexus.redback.rbac.jdo.RbacDatabase;
+import org.codehaus.plexus.redback.rbac.jdo.io.stax.RbacJdoModelStaxReader;
+import org.codehaus.plexus.redback.rbac.jdo.io.stax.RbacJdoModelStaxWriter;
+
+/**
+ * Test the StAX reader and writer generated.
+ */
+public class RbacJdoModelStaxTest
+ extends TestCase
+{
+ @SuppressWarnings("unchecked")
+ public void testStax()
+ throws IOException, XMLStreamException
+ {
+ RbacDatabase database = new RbacDatabase();
+
+ JdoRole role = new JdoRole();
+ role.setAssignable( true );
+ role.setDescription( "descriptor" );
+ role.setName( "name" );
+ role.setPermanent( true );
+ role.addChildRoleName( "childRole1" );
+ role.addChildRoleName( "childRole2" );
+
+ JdoPermission permission = new JdoPermission();
+ permission.setDescription( "permDesc" );
+ permission.setName( "permName" );
+
+ JdoOperation operation = new JdoOperation();
+ operation.setDescription( "opDesc" );
+ operation.setName( "opName" );
+ operation.setPermanent( true );
+ operation.setResourceRequired( true );
+ permission.setOperation( operation );
+ database.addOperation( operation );
+
+ JdoResource resource = new JdoResource();
+ resource.setIdentifier( "resId" );
+ resource.setPattern( true );
+ resource.setPermanent( true );
+ permission.setResource( resource );
+ database.addResource( resource );
+ permission.setPermanent( true );
+ role.addPermission( permission );
+ database.addPermission( permission );
+
+ database.addRole( role );
+
+ JdoUserAssignment assignment = new JdoUserAssignment();
+ assignment.setPermanent( false );
+ assignment.setPrincipal( "principal" );
+ assignment.setTimestamp( new Date() );
+ assignment.addRoleName( "name" );
+
+ database.addUserAssignment( assignment );
+
+ StringWriter w = new StringWriter();
+ new RbacJdoModelStaxWriter().write( w, database );
+
+ RbacDatabase newDatabase = new RbacJdoModelStaxReader().read( new StringReader( w.toString() ) );
+
+ List<JdoRole> expectedRoles = database.getRoles();
+ List<JdoRole> roles = newDatabase.getRoles();
+ assertEquals( expectedRoles.size(), roles.size() );
+ for ( JdoRole r : roles )
+ {
+ boolean found = false;
+ for ( JdoRole expectedRole : expectedRoles )
+ {
+ if ( expectedRole.getName().equals( r.getName() ) )
+ {
+ found = true;
+
+ assertRole( expectedRole, r );
+ }
+ }
+ if ( !found )
+ {
+ fail( "Couldn't find role: " + r.getName() );
+ }
+ }
+
+ List<JdoUserAssignment> expectedUserAssignments = database.getUserAssignments();
+ List<JdoUserAssignment> userAssignments = newDatabase.getUserAssignments();
+ assertEquals( expectedUserAssignments.size(), userAssignments.size() );
+ for ( JdoUserAssignment a : userAssignments )
+ {
+ boolean found = false;
+ for ( JdoUserAssignment expectedAssignment : expectedUserAssignments )
+ {
+ if ( expectedAssignment.getPrincipal().equals( a.getPrincipal() ) )
+ {
+ found = true;
+
+ assertUserAssignment( expectedAssignment, a );
+ }
+ }
+ if ( !found )
+ {
+ fail( "Couldn't find assignment: " + a.getPrincipal() );
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void assertRole( JdoRole expectedRole, JdoRole role )
+ {
+ assertEquals( expectedRole.getDescription(), role.getDescription() );
+ assertPermissions( expectedRole.getPermissions(), role.getPermissions() );
+ assertEquals( expectedRole.getChildRoleNames(), role.getChildRoleNames() );
+ }
+
+ private void assertUserAssignment( JdoUserAssignment expectedAssignment, JdoUserAssignment assignment )
+ {
+ SimpleDateFormat sdf = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z", Locale.US );
+ assertNotNull( expectedAssignment.getTimestamp() );
+ assertNotNull( assignment.getTimestamp() );
+
+ assertEquals( sdf.format( expectedAssignment.getTimestamp() ), sdf.format( assignment.getTimestamp() ) );
+ assertEquals( expectedAssignment.getRoleNames(), assignment.getRoleNames() );
+ }
+
+ private void assertPermissions( List<JdoPermission> expectedPermissions, List<JdoPermission> permissions )
+ {
+ assertEquals( expectedPermissions.size(), permissions.size() );
+ for ( JdoPermission permission : permissions )
+ {
+ boolean found = false;
+ for ( JdoPermission expectedPermission : expectedPermissions )
+ {
+ if ( expectedPermission.getName().equals( permission.getName() ) )
+ {
+ found = true;
+
+ assertPermission( expectedPermission, permission );
+ }
+ }
+ if ( !found )
+ {
+ fail( "Couldn't find permission: " + permission.getName() );
+ }
+ }
+ }
+
+ private void assertPermission( JdoPermission expectedPermission, JdoPermission permission )
+ {
+ assertEquals( expectedPermission.getDescription(), permission.getDescription() );
+ assertOperation( expectedPermission.getOperation(), permission.getOperation() );
+ assertResource( expectedPermission.getResource(), permission.getResource() );
+ }
+
+ private void assertResource( Resource expectedResource, Resource resource )
+ {
+ assertEquals( expectedResource.getIdentifier(), resource.getIdentifier() );
+ }
+
+ private void assertOperation( Operation expectedOperation, Operation operation )
+ {
+ assertEquals( expectedOperation.getName(), operation.getName() );
+ assertEquals( expectedOperation.getDescription(), operation.getDescription() );
+ }
+}
+++ /dev/null
-package org.codehaus.plexus.redback.rbac.jdo;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.
- */
-
-import net.sf.ehcache.CacheManager;
-import org.apache.archiva.redback.rbac.RbacManagerException;
-import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory;
-import org.apache.archiva.redback.common.jdo.test.StoreManagerDebug;
-import org.apache.archiva.redback.rbac.RBACManager;
-import org.codehaus.plexus.redback.tests.AbstractRbacManagerTestCase;
-import org.jpox.AbstractPersistenceManagerFactory;
-import org.jpox.SchemaTool;
-import org.junit.Before;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.jdo.PersistenceManager;
-import javax.jdo.PersistenceManagerFactory;
-import java.io.File;
-import java.net.URL;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * JdoRbacManagerTest:
- *
- * @author Jesse McConnell <jmcconnell@apache.org>
- * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
- * @version $Id$
- */
-public class JdoRbacManagerTest
- extends AbstractRbacManagerTestCase
-{
- private StoreManagerDebug storeManager;
-
- @Inject
- @Named( value = "jdoFactory#users" )
- DefaultConfigurableJdoFactory jdoFactory;
-
- @Inject
- @Named( value = "rBACManager#jdo" )
- RBACManager rbacManager;
-
- /**
- * Creates a new RbacStore which contains no data.
- */
- @Before
- public void setUp()
- throws Exception
- {
-
- super.setUp();
-
- assertEquals( DefaultConfigurableJdoFactory.class.getName(), jdoFactory.getClass().getName() );
-
- jdoFactory.setPersistenceManagerFactoryClass( "org.jpox.PersistenceManagerFactoryImpl" ); //$NON-NLS-1$
-
- jdoFactory.setDriverName(
- System.getProperty( "jdo.test.driver", "org.hsqldb.jdbcDriver" ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
- jdoFactory.setUrl(
- System.getProperty( "jdo.test.url", "jdbc:hsqldb:mem:" + getName() ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
- jdoFactory.setUserName( System.getProperty( "jdo.test.user", "sa" ) ); //$NON-NLS-1$
-
- jdoFactory.setPassword( System.getProperty( "jdo.test.pass", "" ) ); //$NON-NLS-1$
-
- jdoFactory.setProperty( "org.jpox.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
-
- jdoFactory.setProperty( "org.jpox.poid.transactionIsolation", "READ_COMMITTED" ); //$NON-NLS-1$ //$NON-NLS-2$
-
- jdoFactory.setProperty( "org.jpox.autoCreateSchema", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
-
- jdoFactory.setProperty( "org.jpox.autoCreateTables", "true" );
-
- jdoFactory.setProperty( "javax.jdo.option.RetainValues", "true" );
-
- jdoFactory.setProperty( "javax.jdo.option.RestoreValues", "true" );
-
- // jdoFactory.setProperty( "org.jpox.autoCreateColumns", "true" );
-
- jdoFactory.setProperty( "org.jpox.validateTables", "true" );
-
- jdoFactory.setProperty( "org.jpox.validateColumns", "true" );
-
- jdoFactory.setProperty( "org.jpox.validateConstraints", "true" );
-
- /* Enable the level 2 Ehcache class-based cache */
- jdoFactory.setProperty( "org.jpox.cache.level2", "true" );
- jdoFactory.setProperty( "org.jpox.cache.level2.type", "ehcacheclassbased" );
- jdoFactory.setProperty( "org.jpox.cache.level2.configurationFile", "/ehcache.xml" ); // ehcache config
- jdoFactory.setProperty( "org.jpox.cache.level2.cacheName", "default" ); // default cache name
-
- Properties properties = jdoFactory.getProperties();
-
- for ( Map.Entry<Object, Object> entry : properties.entrySet() )
- {
- System.setProperty( (String) entry.getKey(), (String) entry.getValue() );
- }
-
- URL[] jdoFileUrls =
- new URL[]{ getClass().getResource( "/org/codehaus/plexus/redback/rbac/jdo/package.jdo" ) }; //$NON-NLS-1$
-
-
-
- if ( ( jdoFileUrls == null ) || ( jdoFileUrls[0] == null ) )
- {
- fail( "Unable to process test " + getName() + " - missing package.jdo." );
- }
-
- File propsFile = null; // intentional
- boolean verbose = true;
-
- PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory();
-
- assertNotNull( pmf );
-
- /* set our own Store Manager to allow counting SQL statements */
- StoreManagerDebug.setup( (AbstractPersistenceManagerFactory) pmf );
-
- /* clean up the db */
- SchemaTool.deleteSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose );
- SchemaTool.createSchemaTables( jdoFileUrls, new URL[]{ }, propsFile, verbose, null );
-
- PersistenceManager pm = pmf.getPersistenceManager();
-
- pm.close();
-
- setRbacManager( rbacManager );
-
- /* save the store manager to access the queries executed */
- JdoRbacManager rbacManager = (JdoRbacManager) getRbacManager();
- storeManager = StoreManagerDebug.getConfiguredStoreManager( rbacManager.getJdo().getPersistenceManager() );
- }
-
-
- @Override
- public void testGetAssignedRoles()
- throws RbacManagerException
- {
- storeManager.resetCounter();
- super.testGetAssignedRoles();
- int counter = storeManager.counter();
- /* without Level 2 cache: 15 queries */
- /* with Level 2 cache: 8 queries */
- assertEquals( "Number of SQL queries", 8, counter );
- }
-
- @Override
- public void testGetAssignedPermissionsDeep()
- throws RbacManagerException
- {
- super.testGetAssignedPermissionsDeep();
- int counter = storeManager.counter();
- /* without Level 2 cache: 26 queries */
- /* with Level 2 cache: 10 queries */
- assertEquals( "Number of SQL queries", 10, counter );
- }
-
- @Override
- protected void afterSetup()
- {
- super.afterSetup();
- storeManager.resetCounter();
- }
-
- @Override
- public void testLargeApplicationInit()
- throws RbacManagerException
- {
- for (String cacheName : CacheManager.getInstance().getCacheNames())
- {
- CacheManager.getInstance().getCache( cacheName ).removeAll();
- }
- super.testLargeApplicationInit();
- }
-
- @Override
- public void testGetRolesDeep()
- throws RbacManagerException
- {
- for (String cacheName : CacheManager.getInstance().getCacheNames())
- {
- CacheManager.getInstance().getCache( cacheName ).removeAll();
- }
- super.testGetRolesDeep();
- }
-
-
- @Override
- public void testStoreInitialization()
- throws Exception
- {
- rbacManager.eraseDatabase();
- eventTracker.rbacInit( true );
- super.testStoreInitialization();
- }
-}
+++ /dev/null
-package org.codehaus.plexus.redback.rbac.jdo;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * 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.
- */
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-
-import javax.xml.stream.XMLStreamException;
-
-import junit.framework.TestCase;
-
-import org.apache.archiva.redback.rbac.Operation;
-import org.apache.archiva.redback.rbac.Resource;
-import org.codehaus.plexus.redback.rbac.jdo.io.stax.RbacJdoModelStaxReader;
-import org.codehaus.plexus.redback.rbac.jdo.io.stax.RbacJdoModelStaxWriter;
-
-/**
- * Test the StAX reader and writer generated.
- */
-public class RbacJdoModelStaxTest
- extends TestCase
-{
- @SuppressWarnings("unchecked")
- public void testStax()
- throws IOException, XMLStreamException
- {
- RbacDatabase database = new RbacDatabase();
-
- JdoRole role = new JdoRole();
- role.setAssignable( true );
- role.setDescription( "descriptor" );
- role.setName( "name" );
- role.setPermanent( true );
- role.addChildRoleName( "childRole1" );
- role.addChildRoleName( "childRole2" );
-
- JdoPermission permission = new JdoPermission();
- permission.setDescription( "permDesc" );
- permission.setName( "permName" );
-
- JdoOperation operation = new JdoOperation();
- operation.setDescription( "opDesc" );
- operation.setName( "opName" );
- operation.setPermanent( true );
- operation.setResourceRequired( true );
- permission.setOperation( operation );
- database.addOperation( operation );
-
- JdoResource resource = new JdoResource();
- resource.setIdentifier( "resId" );
- resource.setPattern( true );
- resource.setPermanent( true );
- permission.setResource( resource );
- database.addResource( resource );
- permission.setPermanent( true );
- role.addPermission( permission );
- database.addPermission( permission );
-
- database.addRole( role );
-
- JdoUserAssignment assignment = new JdoUserAssignment();
- assignment.setPermanent( false );
- assignment.setPrincipal( "principal" );
- assignment.setTimestamp( new Date() );
- assignment.addRoleName( "name" );
-
- database.addUserAssignment( assignment );
-
- StringWriter w = new StringWriter();
- new RbacJdoModelStaxWriter().write( w, database );
-
- RbacDatabase newDatabase = new RbacJdoModelStaxReader().read( new StringReader( w.toString() ) );
-
- List<JdoRole> expectedRoles = database.getRoles();
- List<JdoRole> roles = newDatabase.getRoles();
- assertEquals( expectedRoles.size(), roles.size() );
- for ( JdoRole r : roles )
- {
- boolean found = false;
- for ( JdoRole expectedRole : expectedRoles )
- {
- if ( expectedRole.getName().equals( r.getName() ) )
- {
- found = true;
-
- assertRole( expectedRole, r );
- }
- }
- if ( !found )
- {
- fail( "Couldn't find role: " + r.getName() );
- }
- }
-
- List<JdoUserAssignment> expectedUserAssignments = database.getUserAssignments();
- List<JdoUserAssignment> userAssignments = newDatabase.getUserAssignments();
- assertEquals( expectedUserAssignments.size(), userAssignments.size() );
- for ( JdoUserAssignment a : userAssignments )
- {
- boolean found = false;
- for ( JdoUserAssignment expectedAssignment : expectedUserAssignments )
- {
- if ( expectedAssignment.getPrincipal().equals( a.getPrincipal() ) )
- {
- found = true;
-
- assertUserAssignment( expectedAssignment, a );
- }
- }
- if ( !found )
- {
- fail( "Couldn't find assignment: " + a.getPrincipal() );
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void assertRole( JdoRole expectedRole, JdoRole role )
- {
- assertEquals( expectedRole.getDescription(), role.getDescription() );
- assertPermissions( expectedRole.getPermissions(), role.getPermissions() );
- assertEquals( expectedRole.getChildRoleNames(), role.getChildRoleNames() );
- }
-
- private void assertUserAssignment( JdoUserAssignment expectedAssignment, JdoUserAssignment assignment )
- {
- SimpleDateFormat sdf = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z", Locale.US );
- assertNotNull( expectedAssignment.getTimestamp() );
- assertNotNull( assignment.getTimestamp() );
-
- assertEquals( sdf.format( expectedAssignment.getTimestamp() ), sdf.format( assignment.getTimestamp() ) );
- assertEquals( expectedAssignment.getRoleNames(), assignment.getRoleNames() );
- }
-
- private void assertPermissions( List<JdoPermission> expectedPermissions, List<JdoPermission> permissions )
- {
- assertEquals( expectedPermissions.size(), permissions.size() );
- for ( JdoPermission permission : permissions )
- {
- boolean found = false;
- for ( JdoPermission expectedPermission : expectedPermissions )
- {
- if ( expectedPermission.getName().equals( permission.getName() ) )
- {
- found = true;
-
- assertPermission( expectedPermission, permission );
- }
- }
- if ( !found )
- {
- fail( "Couldn't find permission: " + permission.getName() );
- }
- }
- }
-
- private void assertPermission( JdoPermission expectedPermission, JdoPermission permission )
- {
- assertEquals( expectedPermission.getDescription(), permission.getDescription() );
- assertOperation( expectedPermission.getOperation(), permission.getOperation() );
- assertResource( expectedPermission.getResource(), permission.getResource() );
- }
-
- private void assertResource( Resource expectedResource, Resource resource )
- {
- assertEquals( expectedResource.getIdentifier(), resource.getIdentifier() );
- }
-
- private void assertOperation( Operation expectedOperation, Operation operation )
- {
- assertEquals( expectedOperation.getName(), operation.getName() );
- assertEquals( expectedOperation.getDescription(), operation.getDescription() );
- }
-}
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="jdoFactory#users" class="org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory">
<property name="driverName" value="org.hsqldb.jdbcDriver"/>
* under the License.
*/
+import org.apache.archiva.redback.rbac.jdo.JdoRbacManager;
import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory;
-import org.codehaus.plexus.redback.rbac.jdo.JdoRbacManager;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
<alias name="roleManager" alias="roleManager#jpox"/>
- <bean name="rBACManager#jdo" class="org.codehaus.plexus.redback.rbac.jdo.JdoRbacManager">
+ <bean name="rBACManager#jdo" class="org.apache.archiva.redback.rbac.jdo.JdoRbacManager">
<property name="jdo" ref="jdoTool"/>
<property name="enableCache" value="false"/>
</bean>