Friday, April 18, 2014

Spring Security 3.2 - Users, Roles, Permissions - Part 2

This post builds on the code from part 1 of this series,Spring Security 3.2 - Users, Roles, Permissions - Part 1.  In this post, we will add/update the DAO layer to accommodate the addition of the Permission class.

1. We will start by creating our two exception classes needed in this layer.
package com.dtr.oas.dao;

public class DuplicatePermissionException extends Exception {

    private static final long serialVersionUID = 4248723875829158068L;

    public DuplicatePermissionException() {
    }

    public DuplicatePermissionException(String arg0) {
        super(arg0);
    }

    public DuplicatePermissionException(Throwable arg0) {
        super(arg0);
    }

    public DuplicatePermissionException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    public DuplicatePermissionException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
        super(arg0, arg1, arg2, arg3);
    }
}
package com.dtr.oas.dao;

public class PermissionNotFoundException extends Exception {

    private static final long serialVersionUID = 6975301468402274579L;

    public PermissionNotFoundException() {
    }

    public PermissionNotFoundException(String message) {
        super(message);
    }

    public PermissionNotFoundException(Throwable cause) {
        super(cause);
    }

    public PermissionNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public PermissionNotFoundException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

2. Next we will create the interface for the Permission DAO. This interface is nearly identical in functionality to the other DAO interfaces.
package com.dtr.oas.dao;
import java.util.List;
import com.dtr.oas.model.Permission;

public interface PermissionDAO {

    public void addPermission(Permission permission) throws DuplicatePermissionException;

    public Permission getPermission(int id) throws PermissionNotFoundException;

    public Permission getPermission(String permissionName) throws PermissionNotFoundException;

    public void updatePermission(Permission permission) throws PermissionNotFoundException;

    public void deletePermission(int id) throws PermissionNotFoundException;

    public List<Permission> getPermissions();

}

3. The implementation of the Permission DAO is shown below. This class should look pretty similar to the other DAO implementation classes we've created in on this blog.
package com.dtr.oas.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dtr.oas.model.Permission;

@Repository
public class PermissionDAOImpl implements PermissionDAO {
    static Logger logger = LoggerFactory.getLogger(PermissionDAOImpl.class);

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void addPermission(Permission permission) throws DuplicatePermissionException {
        logger.debug("PermissionDAOImpl.addPermission() - [" + permission.getPermissionname() + "]");
        try {
            // if the permission is not found, then a PermissionNotFoundException is
            // thrown from the getPermission method call, and the new permission will be 
            // added.
            //
            // if the permission is found, then the flow will continue from the getPermission
            // method call and the DuplicatePermissionException will be thrown.
            Permission permCheck = getPermission(permission.getPermissionname());
            String message = "The permission [" + permCheck.getPermissionname() + "] already exists";
            throw new DuplicatePermissionException(message);
        } catch (PermissionNotFoundException e) {
            getCurrentSession().save(permission);
        }
    }

    @Override
    public Permission getPermission(int permission_id) throws PermissionNotFoundException {
        Permission permObject = (Permission) getCurrentSession().get(Permission.class, permission_id);
        if (permObject == null ) {
            throw new PermissionNotFoundException("Permission id [" + permission_id + "] not found");
        } else {
            return permObject;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Permission getPermission(String usersPermission) throws PermissionNotFoundException {
        logger.debug("PermissionDAOImpl.getPermission() - [" + usersPermission + "]");
        Query query = getCurrentSession().createQuery("from Permission where permissionname = :usersPermission ");
        query.setString("usersPermission", usersPermission);
        
        logger.debug(query.toString());
        if (query.list().size() == 0 ) {
            throw new PermissionNotFoundException("Permission [" + usersPermission + "] not found");
        } else {
            logger.debug("Permission List Size: " + query.list().size());
            List<Permission> list = (List<Permission>)query.list();
            Permission permObject = (Permission) list.get(0);

            return permObject;
        }
    }

    @Override
    public void updatePermission(Permission permission) throws PermissionNotFoundException {
        Permission permissionToUpdate = getPermission(permission.getId());
        permissionToUpdate.setId(permission.getId());
        permissionToUpdate.setPermissionname(permission.getPermissionname());
        getCurrentSession().update(permissionToUpdate);
    }

    @Override
    public void deletePermission(int permission_id) throws PermissionNotFoundException {
        Permission permission = getPermission(permission_id);
        if (permission != null) {
            getCurrentSession().delete(permission);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Permission> getPermissions() {
        return getCurrentSession().createQuery("from Permission").list();
    }
}

4. The only other change in this layer is to modify the updateUser() method in the User DAO implementation. In this method, we will now need to call setRoles()/getRoles() rather than setRole()/getRole() as highlighted in the code fragment below.
...
@Override
    public void updateUser(User user) throws UserNotFoundException {
        User userToUpdate = getUser(user.getId());
        userToUpdate.setUsername(user.getUsername());
        userToUpdate.setPassword(user.getPassword());
        userToUpdate.setEnabled(user.getEnabled());
        userToUpdate.setRoles(user.getRoles());
        getCurrentSession().update(userToUpdate);
    }
...

In the next post, we will add/update the Service layer

No comments:

Post a Comment