org.gaixie.jibu.security.service.impl.AuthorityServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.gaixie.jibu.security.service.impl.AuthorityServiceImpl.java

Source

/*
 *  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.
 */
package org.gaixie.jibu.security.service.impl;

import com.google.inject.Inject;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.dbutils.DbUtils;
import org.gaixie.jibu.JibuException;
import org.gaixie.jibu.cache.Cache;
import org.gaixie.jibu.utils.CacheUtils;
import org.gaixie.jibu.utils.ConnectionUtils;
import org.gaixie.jibu.security.dao.AuthorityDAO;
import org.gaixie.jibu.security.dao.RoleDAO;
import org.gaixie.jibu.security.model.Authority;
import org.gaixie.jibu.security.model.Role;
import org.gaixie.jibu.security.model.User;
import org.gaixie.jibu.security.service.AuthorityService;
import org.gaixie.jibu.security.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Authority ??
 * <p>
 */
public class AuthorityServiceImpl implements AuthorityService {
    Logger logger = LoggerFactory.getLogger(AuthorityServiceImpl.class);
    private final AuthorityDAO authDAO;
    private final RoleDAO roleDAO;

    /**
     *  Guice  DAO ?
     * <p>
     */
    @Inject
    public AuthorityServiceImpl(AuthorityDAO authDAO, RoleDAO roleDAO) {
        this.authDAO = authDAO;
        this.roleDAO = roleDAO;
    }

    public Authority get(int id) {
        Connection conn = null;
        Authority auth = null;
        try {
            conn = ConnectionUtils.getConnection();
            auth = authDAO.get(conn, id);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auth;
    }

    public Authority get(String value) {
        Connection conn = null;
        Authority auth = null;
        try {
            conn = ConnectionUtils.getConnection();
            auth = authDAO.get(conn, value);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auth;
    }

    /**
     * {@inheritDoc}
     * <p>
     * ? Cache  authorities  value
     * @see #getAll()
     */
    public void add(Authority auth) throws JibuException {
        Connection conn = null;
        try {
            conn = ConnectionUtils.getConnection();
            authDAO.save(conn, auth);
            DbUtils.commitAndClose(conn);
            Cache cache = CacheUtils.getAuthCache();
            cache.remove("authorities");
        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            throw new JibuException(e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     * <p>
     *  Cache  authorities  value  DAO 
     * value  Cache
     */
    public List<Authority> getAll() {
        Connection conn = null;
        List<Authority> auths = null;

        Cache cache = CacheUtils.getAuthCache();
        auths = (List<Authority>) cache.get("authorities");
        if (null != auths)
            return auths;
        try {
            conn = ConnectionUtils.getConnection();
            auths = authDAO.getAll(conn);
            cache.put("authorities", auths);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auths;
    }

    private List<String> findRoleNamesByUsername(String username) {
        Connection conn = null;
        Cache cache = CacheUtils.getUserCache();
        List<String> names = (List<String>) cache.get(username);
        if (null != names)
            return names;

        try {
            conn = ConnectionUtils.getConnection();
            names = roleDAO.findByUsername(conn, username);
            cache.put(username, names);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return names;
    }

    private void putTreeMap(Map<String, String> map, Authority auth) {
        String[] sp = auth.getName().split("\\.");
        String key = "";
        for (int i = 0; i < sp.length - 1; i++) {
            key = (i == 0) ? sp[i] : key + "." + sp[i];
            map.put(key, "#");
        }
        map.put(auth.getName(), auth.getValue());
    }

    /**
     * {@inheritDoc}
     * <p>
     * ??? Cache Cache <br>
     *  Authority  username ?
     * ?  Map<br>
     *  authority.name ? 5?? Map
     * ???????
     */
    public Map<String, String> findMapByUsername(String username) {
        Map<String, String> treemap = new TreeMap<String, String>();
        List<Authority> auths = getAll();

        List<String> urole = findRoleNamesByUsername(username);
        if (null == urole)
            return treemap;

        for (Authority auth : auths) {
            if (auth.getName().length() < 5)
                continue;
            // ROLE_ADMIN?
            if (urole.contains("ROLE_ADMIN")) {
                putTreeMap(treemap, auth);
                continue;
            }

            List<String> arole = findRoleNamesByValue(auth.getValue());
            // map.size()==0 authRole??
            if (arole.size() == 0) {
                putTreeMap(treemap, auth);
                continue;
            }
            for (String role : arole) {
                if (urole.contains(role)) {
                    putTreeMap(treemap, auth);
                    break;
                }
            }
        }
        return treemap;
    }

    private List<String> findRoleNamesByValue(String value) {
        Connection conn = null;
        Cache cache = CacheUtils.getAuthCache();
        List<String> names = (List<String>) cache.get(value);
        if (null != names)
            return names;
        try {
            conn = ConnectionUtils.getConnection();
            Authority auth = authDAO.get(conn, value);
            if (null != auth) {
                names = roleDAO.findByAuthid(conn, auth.getId());
                cache.put(value, names);
            }
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return names;
    }

    /**
     * {@inheritDoc}
     * <p>
     * ??? Cache Cache <br>
     * ????
     * <ul>
     * <li> username  Role??? false</li>
     * <li> username ? ROLE_ADMIN ??? true</li>
     * <li> value ? Authority?
     *  false</li>
     * <li>? Authority  Role????
     *  true</li>
     * </ul>
     *
     */
    public boolean verify(String value, String username) {
        List<String> userRoles = findRoleNamesByUsername(username);
        if (null == userRoles)
            return false;
        if (userRoles.contains("ROLE_ADMIN"))
            return true;
        List<String> authRoles = findRoleNamesByValue(value);
        // ???auth
        if (null == authRoles)
            return false;
        if (authRoles.size() == 0)
            return true;

        for (String role : authRoles) {
            if (userRoles.contains(role)) {
                return true;
            }
        }
        return false;
    }

    /**
     * {@inheritDoc}
     * <p>
     * ? Cache  authorities  value
     * @see #getAll()
     */
    public void delete(Authority auth) throws JibuException {
        Connection conn = null;
        try {
            conn = ConnectionUtils.getConnection();
            authDAO.delete(conn, auth);
            DbUtils.commitAndClose(conn);
            Cache cache = CacheUtils.getAuthCache();
            cache.remove("authorities");
        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            throw new JibuException(e.getMessage());
        }
    }

    /**
     * {@inheritDoc}
     * <p>
     * ? Cache  authorities  value 
     * key = auth.getValue() ?
     * @see #getAll()
     */
    public void update(Authority auth) throws JibuException {
        Connection conn = null;
        try {
            conn = ConnectionUtils.getConnection();
            Authority old = authDAO.get(conn, auth.getId());
            authDAO.update(conn, auth);
            DbUtils.commitAndClose(conn);
            Cache cache = CacheUtils.getAuthCache();
            cache.remove("authorities");
            cache.remove(old.getValue());
        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            throw new JibuException(e.getMessage());
        }
    }

    public List<Authority> findByName(String name) {
        Connection conn = null;
        List<Authority> auths = null;
        try {
            conn = ConnectionUtils.getConnection();
            auths = authDAO.findByName(conn, name);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auths;
    }

    public List<Authority> find(Authority auth) {
        if (null == auth)
            return this.getAll();
        Connection conn = null;
        List<Authority> auths = null;
        try {
            conn = ConnectionUtils.getConnection();
            auths = authDAO.find(conn, auth);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auths;
    }

    public List<Authority> find(User user) {
        Connection conn = null;
        List<Authority> auths = null;
        try {
            conn = ConnectionUtils.getConnection();
            auths = authDAO.find(conn, user);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auths;
    }

    public List<Authority> find(Role role) {
        Connection conn = null;
        List<Authority> auths = null;
        try {
            conn = ConnectionUtils.getConnection();
            auths = authDAO.find(conn, role);
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            DbUtils.closeQuietly(conn);
        }
        return auths;
    }
}