com.mycompany.CRMFly.hibernateAccess.MyUserDetailService.java Source code

Java tutorial

Introduction

Here is the source code for com.mycompany.CRMFly.hibernateAccess.MyUserDetailService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ??
 */
package com.mycompany.CRMFly.hibernateAccess;

//import com.mycompany.CRMFly.Security.IChangePassword;
import com.mycompany.CRMFly.entities.UserAccount;
import com.mycompany.CRMFly.entities.UserAuthority;
import com.mycompany.CRMFly.entities.UserGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author ??
 */
@Repository
public class MyUserDetailService implements CustomUserDetailService {

    //    @PersistenceContext
    //  private EntityManager em;

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public UserAccount loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        UserAccount userDetails = null;

        try {
            userDetails = (UserAccount) sessionFactory.getCurrentSession().createCriteria(UserAccount.class)
                    .add(Restrictions.eq("username", username)).uniqueResult();

            //    createQuery("from com.mycompany.CRMFly.entities.USERS where username = :username")
            //    .setParameter("username", username).uniqueResult();
            /*    userDetails = em.createQuery("from UserAccount where username = :username", UserAccount.class)
                .setParameter("username", username)
                .getSingleResult(); */
        } catch (Exception e) {
            throw new UsernameNotFoundException(null);
        }
        if (userDetails == null)
            throw new UsernameNotFoundException(null);

        //    userDetails = (UserDetails) temp;
        return userDetails;
    }

    @Transactional
    public UserGroup loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
        return (UserGroup) sessionFactory.getCurrentSession()
                .createQuery("from com.mycompany.CRMFly.entities.UserGroup where groupName = :groupname")
                .setParameter("groupname", groupname).uniqueResult();
    }

    @Transactional
    public Set<UserAccount> getUsersForGroup(Long id) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("groups-with-users");
        UserGroup group = (UserGroup) sess.get(UserGroup.class, id);
        return group.getAccounts();
    }

    @Transactional
    public Set<UserGroup> getGroupsOfUser(Long id) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("users-with-groups");
        UserAccount account = (UserAccount) sess.get(UserAccount.class, id);
        return account.getGroups();
    }

    @Transactional
    public void addUserToGroup(UserAccount acc, UserGroup group) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("users-with-groups");
        acc = (UserAccount) sess.load(UserAccount.class, acc.getId());
        sess.enableFetchProfile("groups-with-users");
        group = (UserGroup) sess.load(UserGroup.class, group.getId());
        acc.getGroups().add(group);
        group.getAccounts().add(acc);
        updateUser(acc);
        updateGroup(group);
    }

    @Transactional
    public void removeUserFromGroup(UserAccount acc, UserGroup group) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("users-with-groups");
        acc = (UserAccount) sess.load(UserAccount.class, acc.getId());
        sess.enableFetchProfile("groups-with-users");
        group = (UserGroup) sess.load(UserGroup.class, group.getId());
        acc.getGroups().remove(group);
        group.getAccounts().remove(acc);
        updateUser(acc);
        updateGroup(group);
    }

    @Transactional
    public void clearGroup(UserGroup group) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("groups-with-users");
        group = (UserGroup) sess.load(UserGroup.class, group.getId());
        Set<UserAccount> users = group.getAccounts();
        for (UserAccount user : users) {
            user.getGroups().remove(group);
            updateUser(user);
        }
        updateGroup(group);
    }

    @Transactional
    public void deleteUser(UserAccount account) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("users-with-groups");
        account = (UserAccount) sess.load(UserAccount.class, account.getId());
        Set<UserGroup> groups = account.getGroups();
        account.setGroups(null);
        for (UserGroup group : groups) {
            group.getAccounts().remove(account);
            updateGroup(group);
        }
        Collection<UserAuthority> authorities = account.getUserAuthorities();
        account.setUserAuthorities(null);
        for (UserAuthority auth : authorities) {
            auth.setAccount(null);
            deleteAuthority(auth);
        }
        sessionFactory.getCurrentSession().delete(account);
    }

    @Transactional
    public List<UserAuthority> getAllGroupAuthoritiesFotUser(UserAccount account) {
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("users-with-groups");
        Boolean reprise = false;
        account = (UserAccount) sess.load(UserAccount.class, account.getId());
        Set<UserGroup> groups = account.getGroups();
        List<UserAuthority> nessAuth = new ArrayList<UserAuthority>();
        List<String> Sorted = new ArrayList<String>();
        List<UserAuthority> SortedAuth = new ArrayList<UserAuthority>();
        for (UserGroup group : groups) {
            nessAuth.addAll(group.getAuthorities());
        }
        /*   for(int i=0; i<nessAuth.size(); i++)
           {
         String auth = nessAuth.get(i).getAuthority();
         for (int j=0; j<i; j++)
         {
             if (Sorted.get(j).equals(auth))
             {reprise = true;
             break;}  
         }
         if (reprise==false)
         {
         Sorted.add(auth);
         SortedAuth.add(nessAuth.get(i));
         }
           }
           return SortedAuth;*/
        return nessAuth;

    }

    // @Transactional

    @Transactional
    public void changeUsername(String username, String newUsername) {
        UserAccount userDetails = (UserAccount) sessionFactory.getCurrentSession()
                .createQuery("from UserAccount where username = :username").setParameter("username", username)
                .uniqueResult();

        userDetails.setUsername(newUsername);
        sessionFactory.getCurrentSession().merge(userDetails);

    }

    @Transactional
    public void updateUser(UserAccount userDetails) {
        sessionFactory.getCurrentSession().merge(userDetails);
    }

    @Transactional
    public void updateGroup(UserGroup group) {
        sessionFactory.getCurrentSession().merge(group);
    }

    @Transactional
    public void saveAuthority(UserAuthority auth) {
        sessionFactory.getCurrentSession().save(auth);
    }

    @Transactional
    public UserAuthority getAuthority(String username, String authority) {
        return (UserAuthority) sessionFactory.getCurrentSession().createCriteria(UserAuthority.class)
                .add(Restrictions.eq("username", username)).add(Restrictions.eq("authority", authority))
                .uniqueResult();

    }

    @Transactional
    public void deleteAuthority(UserAuthority auth) {

        sessionFactory.getCurrentSession().delete(auth);
    }

    @Transactional
    public void addGroup(UserGroup newGroup) {
        sessionFactory.getCurrentSession().save(newGroup);
    }

    @Transactional
    public void deleteGroup(UserGroup group) {
        sessionFactory.getCurrentSession().delete(group);
    }

    @Transactional
    public List<UserGroup> getAllGroups() {
        return sessionFactory.getCurrentSession().createQuery("from com.mycompany.CRMFly.entities.UserGroup")
                .list();

    }

    @Transactional
    public List<UserAccount> getAllUsers() {
        return sessionFactory.getCurrentSession().createQuery("from com.mycompany.CRMFly.entities.UserAccount")
                .list();
    }

}