com.seajas.search.utilities.spring.security.dao.UserDAO.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.utilities.spring.security.dao.UserDAO.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.utilities.spring.security.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.seajas.search.utilities.spring.security.model.User;

/**
 * Simple data access object for user data.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
@SuppressWarnings("deprecation")
public class UserDAO {
    /**
     * The logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);

    /**
     * The JDBC template (for DDL operations.
     */
    private final JdbcOperations jdbc;

    /**
     * Initialize the database tables.
     * 
     * @param dataSource
     */
    @Autowired
    public UserDAO(final DataSource dataSource) {
        this.jdbc = new JdbcTemplate(dataSource);

        try {
            this.jdbc.execute(
                    "CREATE TABLE user (id INT IDENTITY, username VARCHAR(255), password VARCHAR(255), fullname VARCHAR(255), is_enabled INTEGER DEFAULT 1)");
        } catch (DataAccessException e) {
            if (logger.isDebugEnabled())
                logger.debug("Table 'user' likely already exists as it could not be created");
        }
    }

    /**
     * Find a given user by username.
     * 
     * @param username
     * @return User
     */
    public User findUserByUsername(final String username) {
        String sql = "SELECT id, username, password, fullname, is_enabled FROM user WHERE username = ?";

        RowMapper<User> mapper = new RowMapper<User>() {
            @Override
            public User mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
                Integer id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String fullname = resultSet.getString("fullname");
                Boolean isEnabled = resultSet.getInt("is_enabled") == 1 ? true : false;

                return new User(id, username, password, fullname, isEnabled);
            }
        };

        try {
            return jdbc.queryForObject(sql, mapper, username);
        } catch (DataAccessException e) {
            return null;
        }
    }

    /**
     * Find all users.
     * 
     * @return List<User>
     */
    public List<User> findAllUsers() {
        String sql = "SELECT id, username, password, fullname, is_enabled FROM user";

        RowMapper<User> mapper = new RowMapper<User>() {
            @Override
            public User mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
                Integer id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String fullname = resultSet.getString("fullname");
                Boolean isEnabled = resultSet.getInt("is_enabled") == 1 ? true : false;

                return new User(id, username, password, fullname, isEnabled);
            }
        };

        return jdbc.query(sql, mapper);
    }

    /**
     * Determine whether a given username already exists.
     * 
     * @param username
     * @return Boolean
     */
    public boolean existsUsername(final String username) {
        try {
            return jdbc.queryForObject("SELECT COUNT(1) FROM user where username = ?", Integer.class,
                    username) == 1;
        } catch (DataAccessException e) {
            if (logger.isDebugEnabled())
                logger.debug("Could not determine whether user '" + username + "' already exists");
        }

        return false;
    }

    /**
     * Add a new user.
     * 
     * @param username
     * @param password
     * @param fullname
     * @return boolean
     */
    public boolean addUser(final String username, final String password, final String fullname) {
        try {
            return jdbc.update("INSERT INTO user (username, password, fullname, is_enabled) VALUES(?, ?, ?, 1)",
                    username, DigestUtils.md5Hex(password), fullname) == 1;
        } catch (DataAccessException e) {
            logger.error("Could not add user '" + username + "'", e);
        }

        return false;
    }

    /**
     * Delete a user.
     * 
     * @param id
     * @return boolean
     */
    public boolean deleteUser(final Long id) {
        try {
            return jdbc.update("DELETE FROM user WHERE id = ?", id) == 1;
        } catch (DataAccessException e) {
            logger.error("Could not delete user with ID " + id, e);
        }

        return false;
    }

    /**
     * Modify the user.
     * 
     * @param id
     * @param username
     * @param password
     * @param fullname
     * @return boolean
     */
    public boolean modifyUser(final Long id, final String username, final String password, final String fullname) {
        boolean result = true;

        try {
            result = jdbc.update("UPDATE user SET username = ?, fullname = ? WHERE id = ?", username, fullname,
                    id) == 1 && result;

            if (password != null)
                result = jdbc.update("UPDATE user SET password = ? WHERE id = ?", DigestUtils.md5Hex(password),
                        id) == 1 && result;
        } catch (DataAccessException e) {
            logger.error("Could not modify user '" + username + "'", e);
        }

        return result;
    }
}