Package org.internna.iwebmvc.dao

Source Code of org.internna.iwebmvc.dao.SecurityDAOImpl

/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed 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.
*/
package org.internna.iwebmvc.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.internna.iwebmvc.IWebMvcException;
import org.internna.iwebmvc.model.Role;
import org.internna.iwebmvc.model.User;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.utils.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
* Suitable ACEGI DAO. Avoids default DAO to facilitate security.
*
* @author Jose Noheda
*/
public class SecurityDAOImpl implements SecurityDAO {

    protected Log logger = LogFactory.getLog(getClass());

    protected Class<? extends User> userClass;
    protected Class<? extends Role> roleClass;

    @Required
    public void setRoleClass(Class<? extends Role> roleClass) {
        this.roleClass = roleClass;
    }

    @Required
    public void setUserClass(Class<? extends User> userClass) {
        this.userClass = userClass;
    }

    @PersistenceContext private EntityManager entityManager;

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    @Override public Role findAuthority(String authority) {
        return entityManager.find(roleClass, authority);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    @Override public boolean isAuthority(String authority) {
         return findAuthority(authority) != null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override public void createAuthority(String authority) {
        Assert.hasText(authority);
        if (!isAuthority(authority)) {
            try {
                Role role = roleClass.newInstance();
                entityManager.persist(role.setRole(authority));
            } catch (Exception ex) {
                throw new IWebMvcException("Could not create new role", ex);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override public Role updateAuthority(Role authority) {
        Assert.notNull(authority);
        return entityManager.merge(authority);
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    @Override public List<Role> findAuthorities() {
        Query query = entityManager.createQuery("SELECT r FROM " + roleClass.getSimpleName() + " r");
        return query.getResultList();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override public void createUser(User user) {
        Assert.notNull(user);
        entityManager.persist(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public User updateUser(User user) {
        Assert.notNull(user);
        return entityManager.merge(user);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    @Override public User findUser(String userName) {
        if (StringUtils.hasText(userName)) {
            Query query = entityManager.createQuery("SELECT u FROM " + userClass.getSimpleName() + " u where LOWER(USERNAME) = :username");
            query.setParameter("username", userName.toLowerCase());
            try {
                return (User) query.getSingleResult();
            } catch (Exception e) {
                if (logger.isDebugEnabled()) logger.debug("Could not find user [" + userName + "] in database: " + e.getMessage());
            }
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public List<User> findUsers(String username, String name, String role, int offset, int number) {
        String queryString = "SELECT u from " + userClass.getSimpleName() + " u";
        if (StringUtils.hasText(username)) queryString += " WHERE LOWER(username) LIKE :username";
        if (StringUtils.hasText(name)) {
            queryString += queryString.indexOf("WHERE") < 0 ? " WHERE " : " AND ";
            queryString += " LOWER(name) LIKE :name";
        }
        if (StringUtils.hasText(role)) {
            queryString += queryString.indexOf("WHERE") < 0 ? " WHERE " : " AND ";
            queryString += " :role IN ELEMENTS(u.roles)";
        }
        Query query = entityManager.createQuery(queryString);
        query.setFirstResult(offset > 0 ? offset : 0);
        query.setMaxResults(number > 0 ? number : 0);
        if (StringUtils.hasText(name)) query.setParameter("name", name.toLowerCase() + "%");
        if (StringUtils.hasText(username)) query.setParameter("username", username.toLowerCase() + "%");
        if (StringUtils.hasText(role)) query.setParameter("role", role);
        return query.getResultList();
    }

}
TOP

Related Classes of org.internna.iwebmvc.dao.SecurityDAOImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.