Projects >> resthub-spring-stack >>22f757f952870513b33f3167229a288004d46991

Chunk
Conflicting content
 */
public interface GroupService extends GenericResourceService, TracableService {

<<<<<<< HEAD
	/**
	 * Kind of changes notified by this service
	 */
	enum GroupServiceChange {
		/**
		 * Group creation. Arguments : 
		 * 1- created group.
		 */
		GROUP_CREATION, 
		/**
		 * Group deletion. Arguments : 
		 * 1- deleted group.
		 */
		GROUP_DELETION, 
		/**
		 * Group addition to a group. Arguments : 
		 * 1- added group.
		 * 2- concerned parent group.
		 */
		GROUP_ADDED_TO_GROUP, 
		/**
		 * Group removal from a group. Arguments : 
		 * 1- removed group.
		 * 2- concerned parent group.
		 */
		GROUP_REMOVED_FROM_GROUP 
	};
	
	/**
	 * Finds group by name.
	 * @param name
	 * 		the group's Name
	 * @return the group or null if no group with this name is found
	 */
	public Group findByName( String name );
=======
    /**
     * Finds group by name.
     * @param name
     * 		the group's Name
     * @return the group or null if no group with this name is found
     */
    public Group findByName(String name);
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b

    /**
     * Find all groups available.
Solution content
package org.resthub.identity.service;

import java.util.List;

import org.resthub.core.service.GenericResourceService;
import org.resthub.identity.model.Group;
import org.resthub.identity.service.tracability.TracableService;
import org.springframework.transaction.annotation.Transactional;

/**
 * Group services interface.
 * @author Guillaume Zurbach
 */
public interface GroupService extends GenericResourceService, TracableService {

    /**
     * Kind of changes notified by this service
     */
    enum GroupServiceChange {

        /**
         * Group creation. Arguments :
         * 1- created group.
         */
        GROUP_CREATION,
        /**
         * Group deletion. Arguments :
         * 1- deleted group.
         */
        GROUP_DELETION,
        /**
         * Group addition to a group. Arguments :
         * 1- added group.
         * 2- concerned parent group.
         */
        GROUP_ADDED_TO_GROUP,
        /**
         * Group removal from a group. Arguments :
         * 1- removed group.
         * 2- concerned parent group.
         */
        GROUP_REMOVED_FROM_GROUP
    };

    /**
     * Finds group by name.
     * @param name
     * 		the group's Name
     * @return the group or null if no group with this name is found
     */
    public Group findByName(String name);

    /**
     * Find all groups available.
     * @return a list of groups.
     */
    public List findAllGroups();

    /**
     * Remove a group from one group's group
     *
     * @param groupName
     *            the name of the group to whom the groups should be removed
     * @param subGroupName
     *            the name of the group to remove

     */
    public void removeGroupFromGroup(String groupName, String subGroupName);

    /**
     * gets the Groups direct Permissions
     *
     * @param groupName
     *            the name of the Group
     * @return permissions of the group.
     */
    public List getGroupDirectPermissions(String groupName);

    /**
     * Add a permission to a group
     *
     * @param groupName
     *            the name of the group
     * @param permission
     *            the permission to be added
     */
    public void addPermissionToGroup(String groupName, String permission);

    /**
     * Remove the permission for the given group
     *
     * @param groupName
     *            the name of the group
     * @param permission
     *            the permission to delete
     */
    public void removePermissionFromGroup(String groupName, String permission);

    /**
     * Add a group from one group's groups
     *
     * @param groupName
     *            the name of the group to whom to group should be added
     * @param subGroupName
     *            the name of the group to add from the group's group list
     */
    @Transactional
    public void addGroupToGroup(String groupName, String subGroupName);

    /**
     * Add a role to a group.
     * @param groupName Group to which the role will be added.
     * @param roleName The role that will be added.
     */
    void addRoleToGroup(String groupName, String roleName);

    /**
     * Remove a role from a group.
     * @param groupName Group to which the role will be removed.
     * @param roleName The role that will be removed.
     */
    void removeRoleFromGroup(String groupName, String roleName);
}
File
GroupService.java
Developer's decision
Manual
Kind of conflict
Comment
Enum declaration
Method interface
Chunk
Conflicting content
        // Proceed with the actual delete
        super.delete(group);
<<<<<<< HEAD
        
        // Publish notification
        publishChange(GroupServiceChange.GROUP_DELETION.name(), group);
    } // delete().
    
=======
    }

>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
    /**
     * {@inheritDoc}
     */
Solution content
package org.resthub.identity.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.resthub.core.service.GenericResourceServiceImpl;
import org.resthub.identity.dao.PermissionsOwnerDao;
import org.resthub.identity.dao.RoleDao;
import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a Group Service
* It's based on both {@link GenericResourceServiceImpl} and * {@link GroupService} * * It's a bean whose name is "groupService" * */ @Named("groupService") public class GroupServiceImpl extends GenericResourceServiceImpl> implements GroupService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); /** * The userDao
* This class need it in order to be able to deal with users */ @Inject @Named("userDao") protected UserDao userDao; protected RoleService roleService; @Inject @Named("roleService") protected void setRoleDao(RoleService roleService) { this.roleService = roleService; } @Inject @Named("groupDao") public void setResourceDao(PermissionsOwnerDao groupDao) { super.setDao(groupDao); } /** * {@inheritDoc} */ @Override public Group findByName(String name) { Assert.notNull(name, "Group name can't be null"); List result = this.dao.findEquals("name", name); int size = result.size(); Group g = null; if (size == 1) { g = result.get(0); } return g; } /** * {@inheritDoc} */ @Override public List findAllGroups() { return this.dao.readAll(); } /** * add a group to a group * * @param groupName * the name of the group to whom the subGroup should be added * @param subGroupName * the name of the group which should be added * */ @Override @Transactional public void addGroupToGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (!contain) { group.getGroups().add(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_ADDED_TO_GROUP.name(), subGroup, group); } } } } /** * add a permission to a group * * @param groupName * the name of the group * @param permission * the permission to be added */ @Override @Transactional public void addPermissionToGroup(String groupName, String permission) { if (groupName != null && permission != null) { Group g = this.findByName(groupName); if (g != null) { boolean contains = g.getPermissions().contains(permission); if (!contains) { g.getPermissions().add(permission); } } } } /** * Get the groups direct Permissions * * @param the * name of the group to whom the permisisons are requested * * @return the list of permissions that the group has directly (non * Inherited) * */ @Override @Transactional public List getGroupDirectPermissions(String groupName) { List permissions = null; if (groupName != null) { Group g = this.findByName(groupName); if (g != null) { permissions = g.getPermissions(); } } return permissions; } /** * remove a group from a group * * @param groupName * the name of the group to which the subGroup should be remove * * @param subGroupName * the name of the subGroup which should be removed from the * other group list * */ @Override public void removeGroupFromGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (contain) { group.getGroups().remove(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_REMOVED_FROM_GROUP.name(), subGroup, group); } } } } /** * Remove a permission from a group * * @param groupName * the name of the group from which the permission should be * removed * * @param permission * the permission which should be removed * */ @Override @Transactional public void removePermissionFromGroup(String groupName, String permission) { Group g = this.findByName(groupName); if (g != null && permission != null) { List permissions = g.getPermissions(); while (permissions.contains(permission)) { permissions.remove(permission); } } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Long id) { // Get the actual group Group group = this.findById(id); // Let the other delete method do the job this.delete(group); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public Group create(Group created) { // Overriden method call. created = super.create(created); // Publish notification publishChange(GroupServiceChange.GROUP_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Group group) { // Find the users who are in this group List users = userDao.getUsersFromGroup(group.getName()); // Unlink each user from this group for (User user : users) { user.getGroups().remove(group); } userDao.save(users); // Proceed with the actual delete super.delete(group); // Publish notification publishChange(GroupServiceChange.GROUP_DELETION.name(), group); } // delete(). /** * {@inheritDoc} */ @Override @Transactional public void addRoleToGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!g.getRoles().contains(r)) { g.getRoles().add(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (g.getRoles().contains(r)) { g.getRoles().remove(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
GroupServiceImpl.java
Developer's decision
Manual
Kind of conflict
Comment
Method invocation
Chunk
Conflicting content
    } // addListener().
     * {@inheritDoc}
     */
    @Override
<<<<<<< HEAD
    public void addListener(ServiceListener listener) {
    	// Adds a new listener if needed.
    	if (!listeners.contains(listener)) {
    		listeners.add(listener);
    	}
    
=======
    @Transactional
    public void addRoleToGroup(String groupName, String roleName) {
        Group g = this.findByName(groupName);
        if (g != null) {
            Role r = roleService.findByName(roleName);
            if (r != null) {
                if (!g.getRoles().contains(r)) {
                    g.getRoles().add(r);
                    this.dao.save(g);
                }
            }
        }
    }

>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
    /**
     * {@inheritDoc}
     */
Solution content
    }

    /**
package org.resthub.identity.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.resthub.core.service.GenericResourceServiceImpl;
import org.resthub.identity.dao.PermissionsOwnerDao;
import org.resthub.identity.dao.RoleDao;
import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a Group Service
* It's based on both {@link GenericResourceServiceImpl} and * {@link GroupService} * * It's a bean whose name is "groupService" * */ @Named("groupService") public class GroupServiceImpl extends GenericResourceServiceImpl> implements GroupService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); /** * The userDao
* This class need it in order to be able to deal with users */ @Inject @Named("userDao") protected UserDao userDao; protected RoleService roleService; @Inject @Named("roleService") protected void setRoleDao(RoleService roleService) { this.roleService = roleService; } @Inject @Named("groupDao") public void setResourceDao(PermissionsOwnerDao groupDao) { super.setDao(groupDao); } /** * {@inheritDoc} */ @Override public Group findByName(String name) { Assert.notNull(name, "Group name can't be null"); List result = this.dao.findEquals("name", name); int size = result.size(); Group g = null; if (size == 1) { g = result.get(0); } return g; } /** * {@inheritDoc} */ @Override public List findAllGroups() { return this.dao.readAll(); * add a group to a group * * @param groupName * the name of the group to whom the subGroup should be added * @param subGroupName * the name of the group which should be added * */ @Override @Transactional public void addGroupToGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (!contain) { group.getGroups().add(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_ADDED_TO_GROUP.name(), subGroup, group); } } } } /** * add a permission to a group * * @param groupName * the name of the group * @param permission * the permission to be added */ @Override @Transactional public void addPermissionToGroup(String groupName, String permission) { if (groupName != null && permission != null) { Group g = this.findByName(groupName); if (g != null) { boolean contains = g.getPermissions().contains(permission); if (!contains) { g.getPermissions().add(permission); } } } } /** * Get the groups direct Permissions * * @param the * name of the group to whom the permisisons are requested * * @return the list of permissions that the group has directly (non * Inherited) * */ @Override @Transactional public List getGroupDirectPermissions(String groupName) { List permissions = null; if (groupName != null) { Group g = this.findByName(groupName); if (g != null) { permissions = g.getPermissions(); } } return permissions; } /** * remove a group from a group * * @param groupName * the name of the group to which the subGroup should be remove * * @param subGroupName * the name of the subGroup which should be removed from the * other group list * */ @Override public void removeGroupFromGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (contain) { group.getGroups().remove(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_REMOVED_FROM_GROUP.name(), subGroup, group); } } } } /** * Remove a permission from a group * * @param groupName * the name of the group from which the permission should be * removed * * @param permission * the permission which should be removed * */ @Override @Transactional public void removePermissionFromGroup(String groupName, String permission) { Group g = this.findByName(groupName); if (g != null && permission != null) { List permissions = g.getPermissions(); while (permissions.contains(permission)) { permissions.remove(permission); } } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Long id) { // Get the actual group Group group = this.findById(id); // Let the other delete method do the job this.delete(group); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public Group create(Group created) { // Overriden method call. created = super.create(created); // Publish notification publishChange(GroupServiceChange.GROUP_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Group group) { // Find the users who are in this group List users = userDao.getUsersFromGroup(group.getName()); // Unlink each user from this group for (User user : users) { user.getGroups().remove(group); } userDao.save(users); // Proceed with the actual delete super.delete(group); // Publish notification publishChange(GroupServiceChange.GROUP_DELETION.name(), group); } // delete(). /** * {@inheritDoc} */ @Override @Transactional public void addRoleToGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!g.getRoles().contains(r)) { g.getRoles().add(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (g.getRoles().contains(r)) { g.getRoles().remove(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
GroupServiceImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
     * {@inheritDoc}
     */
    @Override
<<<<<<< HEAD
    public void removeListener(ServiceListener listener) {
    	// Adds a new listener if needed.
    	if (listeners.contains(listener)) {
    		listeners.remove(listener);
    	}
    } // removeListener().
    
    /**
     * Sends a notification to every listernes registered.
     * Do not fail if a user thrown an exception (report exception in logs).
     * 
     * @param type Type of notification.
     * @param arguments Notification arguments.
     */
    protected void publishChange(String type, Object... arguments) {
	    for (ServiceListener listener : listeners) {           
	    	try {
	    		// Sends notification to each known listeners
	    		listener.onChange(type, arguments);
	        } catch (Exception exc) {
	        	// Log exception
	        	logger.warn("[publishChange] Cannot bublish " + type + " changes", exc);
	        }
	    }
    } // publishChange().

=======
    @Transactional
    public void removeRoleFromGroup(String groupName, String roleName) {
        Group g = this.findByName(groupName);
        if (g != null) {
            Role r = roleService.findByName(roleName);
            if (r != null) {
                if (g.getRoles().contains(r)) {
                    g.getRoles().remove(r);
                    this.dao.save(g);
                }
            }
        }
    }
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
}
Solution content
package org.resthub.identity.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.resthub.core.service.GenericResourceServiceImpl;
import org.resthub.identity.dao.PermissionsOwnerDao;
import org.resthub.identity.dao.RoleDao;
import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a Group Service
* It's based on both {@link GenericResourceServiceImpl} and * {@link GroupService} * * It's a bean whose name is "groupService" * */ @Named("groupService") public class GroupServiceImpl extends GenericResourceServiceImpl> implements GroupService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); /** * The userDao
* This class need it in order to be able to deal with users */ @Inject @Named("userDao") protected UserDao userDao; protected RoleService roleService; @Inject @Named("roleService") protected void setRoleDao(RoleService roleService) { this.roleService = roleService; } @Inject @Named("groupDao") public void setResourceDao(PermissionsOwnerDao groupDao) { super.setDao(groupDao); } /** * {@inheritDoc} */ @Override public Group findByName(String name) { Assert.notNull(name, "Group name can't be null"); List result = this.dao.findEquals("name", name); int size = result.size(); Group g = null; if (size == 1) { g = result.get(0); } return g; } /** * {@inheritDoc} */ @Override public List findAllGroups() { return this.dao.readAll(); } /** * add a group to a group * * @param groupName * the name of the group to whom the subGroup should be added * @param subGroupName * the name of the group which should be added * */ @Override @Transactional public void addGroupToGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (!contain) { group.getGroups().add(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_ADDED_TO_GROUP.name(), subGroup, group); } } } } /** * add a permission to a group * * @param groupName * the name of the group * @param permission * the permission to be added */ @Override @Transactional public void addPermissionToGroup(String groupName, String permission) { if (groupName != null && permission != null) { Group g = this.findByName(groupName); if (g != null) { boolean contains = g.getPermissions().contains(permission); if (!contains) { g.getPermissions().add(permission); } } } } /** * Get the groups direct Permissions * * @param the * name of the group to whom the permisisons are requested * * @return the list of permissions that the group has directly (non * Inherited) * */ @Override @Transactional public List getGroupDirectPermissions(String groupName) { List permissions = null; if (groupName != null) { Group g = this.findByName(groupName); if (g != null) { permissions = g.getPermissions(); } } return permissions; } /** * remove a group from a group * * @param groupName * the name of the group to which the subGroup should be remove * * @param subGroupName * the name of the subGroup which should be removed from the * other group list * */ @Override public void removeGroupFromGroup(String groupName, String subGroupName) { if (groupName != null && subGroupName != null) { Group group = this.findByName(groupName); Group subGroup = this.findByName(subGroupName); if (group != null && subGroup != null) { boolean contain = group.getGroups().contains(subGroup); if (contain) { group.getGroups().remove(subGroup); // Publish notification publishChange(GroupServiceChange.GROUP_REMOVED_FROM_GROUP.name(), subGroup, group); } } } } /** * Remove a permission from a group * * @param groupName * the name of the group from which the permission should be * removed * * @param permission * the permission which should be removed * */ @Override @Transactional public void removePermissionFromGroup(String groupName, String permission) { Group g = this.findByName(groupName); if (g != null && permission != null) { List permissions = g.getPermissions(); while (permissions.contains(permission)) { permissions.remove(permission); } } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Long id) { // Get the actual group Group group = this.findById(id); // Let the other delete method do the job this.delete(group); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public Group create(Group created) { // Overriden method call. created = super.create(created); // Publish notification publishChange(GroupServiceChange.GROUP_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(Group group) { // Find the users who are in this group List users = userDao.getUsersFromGroup(group.getName()); // Unlink each user from this group for (User user : users) { user.getGroups().remove(group); } userDao.save(users); // Proceed with the actual delete super.delete(group); // Publish notification publishChange(GroupServiceChange.GROUP_DELETION.name(), group); } // delete(). /** * {@inheritDoc} */ @Override @Transactional public void addRoleToGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!g.getRoles().contains(r)) { g.getRoles().add(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromGroup(String groupName, String roleName) { Group g = this.findByName(groupName); if (g != null) { Role r = roleService.findByName(roleName); if (r != null) { if (g.getRoles().contains(r)) { g.getRoles().remove(r); this.dao.save(g); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
GroupServiceImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
package org.resthub.identity.service;

<<<<<<< HEAD
import java.util.HashSet;
=======
import java.util.ArrayList;
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
import java.util.List;
import java.util.Set;
Solution content
    } // delete().
    
     * {@inheritDoc}
    /**
     * {@inheritDoc}
     */
package org.resthub.identity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import org.resthub.identity.dao.AbstractPermissionsOwnerDao;

import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.AbstractPermissionsOwner;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.resthub.identity.tools.PermissionsOwnerTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a UserService dealing with OAuth2 authentication 
* It is based on AbstractEncryptedPasswordUserService * * It is a bean whose name is userService * * */ @Named("userService") public class UserServiceImpl extends AbstractEncryptedPasswordUserService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); @Inject @Named("userDao") public void setResourceDao(UserDao userDao) { super.setDao(userDao); } @Inject @Named("groupService") protected GroupService groupService; @Inject @Named("roleService") protected RoleService roleService; @Inject @Named("abstractPermissionsOwnerDao") protected AbstractPermissionsOwnerDao abstractPermissionsOwnerDao; /** */ @Override @Transactional(readOnly=false) public User create(User user) { // Overloaded method call User created = super.create(user); // Publish notification publishChange(UserServiceChange.USER_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(Long id) { User deleted = findById(id); // Overloaded method call super.delete(id); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), deleted); @Override @Transactional(readOnly=false) public void delete(User user) { super.delete(user); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), user); } // delete(). /** * Retrieves a user by his login * * @param login * the login to look for * @return the corresponding User object if founded, null otherwise * */ public User findByLogin(String login) { Assert.notNull(login, "User login can't be null"); List result = this.dao.findEquals("login", login); int size = result.size(); return (size > 0) ? result.get(0) : null; } /** * Authenticate a user based on login and Password and returns the login if * successful * * @param login * @param password * @return login , the login of the user if the authentication succeed, null * otherwise */ public String getUser(String login, String password) { User u = this.authenticateUser(login, password); return (u != null) ? u.getLogin() : null; } /** * {@inheritDoc} */ @Override public List getUserPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = PermissionsOwnerTools.getInheritedPermission(u); } return p; } /** * gets the User's direct Permissions * * @param login * the login of the user * @return permissions of the user. */ public List getUserDirectPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = u.getPermissions(); } return p; } /** * Add a permission to an user * * @param userLogin * the login of the user * @param permission * the permission to be added */ @Transactional public void addPermissionToUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { boolean alreadyAllowed = u.getPermissions().contains(permission); if (!alreadyAllowed) { u.getPermissions().add(permission); } } } } /** * Remove the permission for the given user * * @param userLogin * the login of the user * @param permission * the permission to delete */ @Transactional public void removePermissionFromUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { while (u.getPermissions().contains(permission)) { u.getPermissions().remove(permission); } } } } /** * Add a group from one user's groups * * @param userLogin * the login of the user to whom to group should be added * @param groupeName * the name of the group to add from the user's group list */ @Transactional public void addGroupToUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().add(g); } // Publish notification publishChange(UserServiceChange.USER_ADDED_TO_GROUP.name(), u, g); } } /** * Remove a group from one user's groups * * @param userLogin * the login of the user to whom to group should be remove * @param groupeName * the name of the group to remove from the user's group list */ @Transactional public void removeGroupFromUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().remove(g); } // Publish notification publishChange(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), u, g); } } @Override public List getUsersFromGroup(String groupName) { List usersFromGroup = this.dao.getUsersFromGroup(groupName); return usersFromGroup; } /** * {@inheritDoc} */ @Override public List findAllUsersWithRoles(List roles) { List usersWithRole = new ArrayList(); // this list will hold all the users for the result // Start by finding the entities directly linked to the roles List withRoles = abstractPermissionsOwnerDao.getWithRoles(roles); // The query may have brought a mix of users and groups, // this loop will process them individually to form the final result. for (AbstractPermissionsOwner owner : withRoles) { this.getUsersFromRootElement(usersWithRole, owner); } return usersWithRole; } /** * Recursive method to get all the users in an AbstractPermissionsOwner, * if the owner is a user, it will be directly added to the list, * if the owner is a group, his subgroups will be explored to find users. * @param users User list to add users into, must not be null. * @param owner Root element to begin exploration. */ private void getUsersFromRootElement(List users, AbstractPermissionsOwner owner) { // Stop the processing if one of the parameters is null if (users != null && owner != null) { // The root element may be user or a group if (owner instanceof User) { User user = (User) owner; // If we have a user, we can't go further so add it if needed and finish. if (!users.contains(user)) { users.add(user); } } else if (owner instanceof Group) { // If we have a group, we must get both users and groups having this group as parent List withGroupAsParent = abstractPermissionsOwnerDao.getWithGroupAsParent((Group) owner); // Each result will be recursively evaluated using this method. for (AbstractPermissionsOwner child : withGroupAsParent) { this.getUsersFromRootElement(users, child); } } } } /** * {@inheritDoc} */ @Override @Transactional public void addRoleToUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!u.getRoles().contains(r)) { u.getRoles().add(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (u.getRoles().contains(r)) { u.getRoles().remove(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
UserServiceImpl.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
        List usersFromGroup = this.dao.getUsersFromGroup(groupName);
        return usersFromGroup;
    }
<<<<<<< HEAD
    
=======

>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
    /**
     * {@inheritDoc}
     */
Solution content
package org.resthub.identity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import org.resthub.identity.dao.AbstractPermissionsOwnerDao;

import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.AbstractPermissionsOwner;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.resthub.identity.tools.PermissionsOwnerTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a UserService dealing with OAuth2 authentication 
} * It is based on AbstractEncryptedPasswordUserService * * It is a bean whose name is userService * * */ @Named("userService") public class UserServiceImpl extends AbstractEncryptedPasswordUserService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); @Inject @Named("userDao") public void setResourceDao(UserDao userDao) { super.setDao(userDao); } @Inject @Named("groupService") protected GroupService groupService; @Inject @Named("roleService") protected RoleService roleService; @Inject @Named("abstractPermissionsOwnerDao") protected AbstractPermissionsOwnerDao abstractPermissionsOwnerDao; /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public User create(User user) { // Overloaded method call User created = super.create(user); // Publish notification publishChange(UserServiceChange.USER_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(Long id) { User deleted = findById(id); // Overloaded method call super.delete(id); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), deleted); } // delete(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(User user) { super.delete(user); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), user); } // delete(). /** * Retrieves a user by his login * * @param login * the login to look for * @return the corresponding User object if founded, null otherwise * */ public User findByLogin(String login) { Assert.notNull(login, "User login can't be null"); List result = this.dao.findEquals("login", login); int size = result.size(); return (size > 0) ? result.get(0) : null; } /** * Authenticate a user based on login and Password and returns the login if * successful * * @param login * @param password * @return login , the login of the user if the authentication succeed, null * otherwise */ public String getUser(String login, String password) { User u = this.authenticateUser(login, password); return (u != null) ? u.getLogin() : null; } /** * {@inheritDoc} */ @Override public List getUserPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = PermissionsOwnerTools.getInheritedPermission(u); } return p; /** * gets the User's direct Permissions * * @param login * the login of the user * @return permissions of the user. */ public List getUserDirectPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = u.getPermissions(); } return p; } /** * Add a permission to an user * * @param userLogin * the login of the user * @param permission * the permission to be added */ @Transactional public void addPermissionToUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { boolean alreadyAllowed = u.getPermissions().contains(permission); if (!alreadyAllowed) { u.getPermissions().add(permission); } } } } /** * Remove the permission for the given user * * @param userLogin * the login of the user * @param permission * the permission to delete */ @Transactional public void removePermissionFromUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { while (u.getPermissions().contains(permission)) { u.getPermissions().remove(permission); } } } } /** * Add a group from one user's groups * * @param userLogin * the login of the user to whom to group should be added * @param groupeName * the name of the group to add from the user's group list */ @Transactional public void addGroupToUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().add(g); } // Publish notification publishChange(UserServiceChange.USER_ADDED_TO_GROUP.name(), u, g); } } /** * Remove a group from one user's groups * * @param userLogin * the login of the user to whom to group should be remove * @param groupeName * the name of the group to remove from the user's group list */ @Transactional public void removeGroupFromUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().remove(g); } // Publish notification publishChange(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), u, g); } } @Override public List getUsersFromGroup(String groupName) { /** List usersFromGroup = this.dao.getUsersFromGroup(groupName); return usersFromGroup; } /** * {@inheritDoc} */ @Override public List findAllUsersWithRoles(List roles) { List usersWithRole = new ArrayList(); // this list will hold all the users for the result // Start by finding the entities directly linked to the roles List withRoles = abstractPermissionsOwnerDao.getWithRoles(roles); // The query may have brought a mix of users and groups, // this loop will process them individually to form the final result. for (AbstractPermissionsOwner owner : withRoles) { this.getUsersFromRootElement(usersWithRole, owner); } return usersWithRole; } /** * Recursive method to get all the users in an AbstractPermissionsOwner, * if the owner is a user, it will be directly added to the list, * if the owner is a group, his subgroups will be explored to find users. * @param users User list to add users into, must not be null. * @param owner Root element to begin exploration. */ private void getUsersFromRootElement(List users, AbstractPermissionsOwner owner) { // Stop the processing if one of the parameters is null if (users != null && owner != null) { // The root element may be user or a group if (owner instanceof User) { User user = (User) owner; // If we have a user, we can't go further so add it if needed and finish. if (!users.contains(user)) { users.add(user); } } else if (owner instanceof Group) { // If we have a group, we must get both users and groups having this group as parent List withGroupAsParent = abstractPermissionsOwnerDao.getWithGroupAsParent((Group) owner); // Each result will be recursively evaluated using this method. for (AbstractPermissionsOwner child : withGroupAsParent) { this.getUsersFromRootElement(users, child); } } } } /** * {@inheritDoc} */ @Override @Transactional public void addRoleToUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!u.getRoles().contains(r)) { u.getRoles().add(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (u.getRoles().contains(r)) { u.getRoles().remove(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
UserServiceImpl.java
Developer's decision
Manual
Kind of conflict
Blank
Chunk
Conflicting content
     * {@inheritDoc}
     */
    @Override
<<<<<<< HEAD
    public void addListener(ServiceListener listener) {
    	// Adds a new listener if needed.
    	if (!listeners.contains(listener)) {
    		listeners.add(listener);
    	}
    } // addListener().
    
=======
    public List findAllUsersWithRoles(List roles) {
        List usersWithRole = new ArrayList(); // this list will hold all the users for the result

        // Start by finding the entities directly linked to the roles
        List withRoles = abstractPermissionsOwnerDao.getWithRoles(roles);

        // The query may have brought a mix of users and groups,
        // this loop will process them individually to form the final result.
        for (AbstractPermissionsOwner owner : withRoles) {
            this.getUsersFromRootElement(usersWithRole, owner);
        }

        return usersWithRole;
    }

    /**
     * Recursive method to get all the users in an AbstractPermissionsOwner,
     * if the owner is a user, it will be directly added to the list,
     * if the owner is a group, his subgroups will be explored to find users.
     * @param users User list to add users into, must not be null.
     * @param owner Root element to begin exploration.
     */
    private void getUsersFromRootElement(List users, AbstractPermissionsOwner owner) {
        // Stop the processing if one of the parameters is null
        if (users != null && owner != null) {
            // The root element may be user or a group
            if (owner instanceof User) {
                User user = (User) owner;
                // If we have a user, we can't go further so add it if needed and finish.
                if (!users.contains(user)) {
                    users.add(user);
                }
            } else if (owner instanceof Group) {
                // If we have a group, we must get both users and groups having this group as parent
                List withGroupAsParent = abstractPermissionsOwnerDao.getWithGroupAsParent((Group) owner);

                // Each result will be recursively evaluated using this method.
                for (AbstractPermissionsOwner child : withGroupAsParent) {
                    this.getUsersFromRootElement(users, child);
                }
            }
        }
    }

>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
    /**
     * {@inheritDoc}
     */
Solution content
    protected RoleService roleService;
    @Inject
package org.resthub.identity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import org.resthub.identity.dao.AbstractPermissionsOwnerDao;

import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.AbstractPermissionsOwner;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.resthub.identity.tools.PermissionsOwnerTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a UserService dealing with OAuth2 authentication 
* It is based on AbstractEncryptedPasswordUserService * * It is a bean whose name is userService * * */ @Named("userService") public class UserServiceImpl extends AbstractEncryptedPasswordUserService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); @Inject @Named("userDao") public void setResourceDao(UserDao userDao) { super.setDao(userDao); } @Inject @Named("groupService") protected GroupService groupService; @Inject @Named("roleService") @Named("abstractPermissionsOwnerDao") protected AbstractPermissionsOwnerDao abstractPermissionsOwnerDao; /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public User create(User user) { // Overloaded method call User created = super.create(user); // Publish notification publishChange(UserServiceChange.USER_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(Long id) { User deleted = findById(id); // Overloaded method call super.delete(id); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), deleted); } // delete(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(User user) { super.delete(user); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), user); } // delete(). /** * Retrieves a user by his login * * @param login * the login to look for * @return the corresponding User object if founded, null otherwise * */ public User findByLogin(String login) { Assert.notNull(login, "User login can't be null"); List result = this.dao.findEquals("login", login); int size = result.size(); return (size > 0) ? result.get(0) : null; } /** * Authenticate a user based on login and Password and returns the login if * successful * * @param login * @param password * @return login , the login of the user if the authentication succeed, null * otherwise */ public String getUser(String login, String password) { User u = this.authenticateUser(login, password); return (u != null) ? u.getLogin() : null; } /** * {@inheritDoc} */ @Override public List getUserPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = PermissionsOwnerTools.getInheritedPermission(u); } return p; } /** * gets the User's direct Permissions * * @param login * the login of the user * @return permissions of the user. */ public List getUserDirectPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = u.getPermissions(); } return p; } /** * Add a permission to an user * * @param userLogin * the login of the user * @param permission * the permission to be added */ @Transactional public void addPermissionToUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { boolean alreadyAllowed = u.getPermissions().contains(permission); if (!alreadyAllowed) { u.getPermissions().add(permission); } } } } /** * Remove the permission for the given user * * @param userLogin * the login of the user * @param permission * the permission to delete */ @Transactional public void removePermissionFromUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { while (u.getPermissions().contains(permission)) { u.getPermissions().remove(permission); } } } } /** * Add a group from one user's groups * * @param userLogin * the login of the user to whom to group should be added * @param groupeName * the name of the group to add from the user's group list */ @Transactional public void addGroupToUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().add(g); } // Publish notification publishChange(UserServiceChange.USER_ADDED_TO_GROUP.name(), u, g); } } /** * Remove a group from one user's groups * * @param userLogin * the login of the user to whom to group should be remove * @param groupeName * the name of the group to remove from the user's group list */ @Transactional public void removeGroupFromUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().remove(g); } // Publish notification publishChange(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), u, g); } } @Override public List getUsersFromGroup(String groupName) { List usersFromGroup = this.dao.getUsersFromGroup(groupName); return usersFromGroup; } /** * {@inheritDoc} */ @Override public List findAllUsersWithRoles(List roles) { List usersWithRole = new ArrayList(); // this list will hold all the users for the result // Start by finding the entities directly linked to the roles List withRoles = abstractPermissionsOwnerDao.getWithRoles(roles); // The query may have brought a mix of users and groups, // this loop will process them individually to form the final result. for (AbstractPermissionsOwner owner : withRoles) { this.getUsersFromRootElement(usersWithRole, owner); } return usersWithRole; } /** * Recursive method to get all the users in an AbstractPermissionsOwner, * if the owner is a user, it will be directly added to the list, * if the owner is a group, his subgroups will be explored to find users. * @param users User list to add users into, must not be null. * @param owner Root element to begin exploration. */ private void getUsersFromRootElement(List users, AbstractPermissionsOwner owner) { // Stop the processing if one of the parameters is null if (users != null && owner != null) { // The root element may be user or a group if (owner instanceof User) { User user = (User) owner; // If we have a user, we can't go further so add it if needed and finish. if (!users.contains(user)) { users.add(user); } } else if (owner instanceof Group) { // If we have a group, we must get both users and groups having this group as parent List withGroupAsParent = abstractPermissionsOwnerDao.getWithGroupAsParent((Group) owner); // Each result will be recursively evaluated using this method. for (AbstractPermissionsOwner child : withGroupAsParent) { this.getUsersFromRootElement(users, child); } } } } /** * {@inheritDoc} */ @Override @Transactional public void addRoleToUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!u.getRoles().contains(r)) { u.getRoles().add(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (u.getRoles().contains(r)) { u.getRoles().remove(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ @Override public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
UserServiceImpl.java
Developer's decision
Manual
Kind of conflict
Comment
Method declaration
Chunk
Conflicting content
     * {@inheritDoc}
     */
    @Override
<<<<<<< HEAD
    public void removeListener(ServiceListener listener) {
    	// Adds a new listener if needed.
    	if (listeners.contains(listener)) {
    		listeners.remove(listener);
    	}
    } // removeListener().
    
    /**
     * Sends a notification to every listernes registered.
     * Do not fail if a user thrown an exception (report exception in logs).
     * 
     * @param type Type of notification.
     * @param arguments Notification arguments.
     */
    protected void publishChange(String type, Object... arguments) {
	    for (ServiceListener listener : listeners) {           
	    	try {
	    		// Sends notification to each known listeners
	    		listener.onChange(type, arguments);
	        } catch (Exception exc) {
	        	// Log exception
	        	logger.warn("[publishChange] Cannot bublish " + type + " changes", exc);
	        }
	    }
    } // publishChange().
=======
    @Transactional
    public void addRoleToUser(String userLogin, String roleName) {
        User u = this.findByLogin(userLogin);
        if (u != null) {
            Role r = roleService.findByName(roleName);
            if (r != null) {
                if (!u.getRoles().contains(r)) {
                    u.getRoles().add(r);
                    this.dao.save(u);
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Transactional
    public void removeRoleFromUser(String userLogin, String roleName) {
        User u = this.findByLogin(userLogin);
        if (u != null) {
            Role r = roleService.findByName(roleName);
            if (r != null) {
                if (u.getRoles().contains(r)) {
                    u.getRoles().remove(r);
                    this.dao.save(u);
                }
            }
        }
    }
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
}
Solution content
    @Override
    @Override
            }
            }
package org.resthub.identity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import org.resthub.identity.dao.AbstractPermissionsOwnerDao;

import org.resthub.identity.dao.UserDao;
import org.resthub.identity.model.AbstractPermissionsOwner;
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.tracability.ServiceListener;
import org.resthub.identity.tools.PermissionsOwnerTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * An implementation of a UserService dealing with OAuth2 authentication 
* It is based on AbstractEncryptedPasswordUserService * * It is a bean whose name is userService * * */ @Named("userService") public class UserServiceImpl extends AbstractEncryptedPasswordUserService { /** * Class logger */ final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); /** * Set of registered listeners */ protected Set listeners = new HashSet(); @Inject @Named("userDao") public void setResourceDao(UserDao userDao) { super.setDao(userDao); } @Inject @Named("groupService") protected GroupService groupService; @Inject @Named("roleService") protected RoleService roleService; @Inject @Named("abstractPermissionsOwnerDao") protected AbstractPermissionsOwnerDao abstractPermissionsOwnerDao; /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public User create(User user) { // Overloaded method call User created = super.create(user); // Publish notification publishChange(UserServiceChange.USER_CREATION.name(), created); return created; } // create(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(Long id) { User deleted = findById(id); // Overloaded method call super.delete(id); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), deleted); } // delete(). /** * {@inheritDoc} */ @Override @Transactional(readOnly=false) public void delete(User user) { super.delete(user); // Publish notification publishChange(UserServiceChange.USER_DELETION.name(), user); } // delete(). /** * Retrieves a user by his login * * @param login * the login to look for * @return the corresponding User object if founded, null otherwise * */ public User findByLogin(String login) { } Assert.notNull(login, "User login can't be null"); List result = this.dao.findEquals("login", login); int size = result.size(); return (size > 0) ? result.get(0) : null; } /** * Authenticate a user based on login and Password and returns the login if * successful * * @param login * @param password * @return login , the login of the user if the authentication succeed, null * otherwise */ public String getUser(String login, String password) { User u = this.authenticateUser(login, password); return (u != null) ? u.getLogin() : null; } /** * {@inheritDoc} */ public List getUserPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = PermissionsOwnerTools.getInheritedPermission(u); } return p; } /** * gets the User's direct Permissions * * @param login * the login of the user * @return permissions of the user. */ public List getUserDirectPermissions(String login) { List p = null; User u = this.findByLogin(login); if (u != null) { p = u.getPermissions(); } return p; } /** * Add a permission to an user * * @param userLogin * the login of the user * @param permission * the permission to be added */ @Transactional public void addPermissionToUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { boolean alreadyAllowed = u.getPermissions().contains(permission); if (!alreadyAllowed) { u.getPermissions().add(permission); } } } } /** * Remove the permission for the given user * * @param userLogin * the login of the user * @param permission * the permission to delete */ @Transactional public void removePermissionFromUser(String userLogin, String permission) { if (userLogin != null && permission != null) { User u = this.findByLogin(userLogin); if (u != null) { while (u.getPermissions().contains(permission)) { u.getPermissions().remove(permission); } } } } /** * Add a group from one user's groups * * @param userLogin * the login of the user to whom to group should be added * @param groupeName * the name of the group to add from the user's group list */ @Transactional public void addGroupToUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().add(g); // Publish notification publishChange(UserServiceChange.USER_ADDED_TO_GROUP.name(), u, g); } } /** * Remove a group from one user's groups * * @param userLogin * the login of the user to whom to group should be remove * @param groupeName * the name of the group to remove from the user's group list */ @Transactional public void removeGroupFromUser(String userLogin, String groupName) { if (userLogin != null && groupName != null) { User u = this.findByLogin(userLogin); Group g = groupService.findByName(groupName); if (u != null && g != null) { u.getGroups().remove(g); // Publish notification publishChange(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), u, g); } } @Override public List getUsersFromGroup(String groupName) { List usersFromGroup = this.dao.getUsersFromGroup(groupName); return usersFromGroup; } /** * {@inheritDoc} */ @Override public List findAllUsersWithRoles(List roles) { List usersWithRole = new ArrayList(); // this list will hold all the users for the result // Start by finding the entities directly linked to the roles List withRoles = abstractPermissionsOwnerDao.getWithRoles(roles); // The query may have brought a mix of users and groups, // this loop will process them individually to form the final result. for (AbstractPermissionsOwner owner : withRoles) { this.getUsersFromRootElement(usersWithRole, owner); } return usersWithRole; } /** * Recursive method to get all the users in an AbstractPermissionsOwner, * if the owner is a user, it will be directly added to the list, * if the owner is a group, his subgroups will be explored to find users. * @param users User list to add users into, must not be null. * @param owner Root element to begin exploration. */ private void getUsersFromRootElement(List users, AbstractPermissionsOwner owner) { // Stop the processing if one of the parameters is null if (users != null && owner != null) { // The root element may be user or a group if (owner instanceof User) { User user = (User) owner; // If we have a user, we can't go further so add it if needed and finish. if (!users.contains(user)) { users.add(user); } } else if (owner instanceof Group) { // If we have a group, we must get both users and groups having this group as parent List withGroupAsParent = abstractPermissionsOwnerDao.getWithGroupAsParent((Group) owner); // Each result will be recursively evaluated using this method. for (AbstractPermissionsOwner child : withGroupAsParent) { this.getUsersFromRootElement(users, child); } } } } /** * {@inheritDoc} */ @Override @Transactional public void addRoleToUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (!u.getRoles().contains(r)) { u.getRoles().add(r); this.dao.save(u); } } } /** * {@inheritDoc} */ @Override @Transactional public void removeRoleFromUser(String userLogin, String roleName) { User u = this.findByLogin(userLogin); if (u != null) { Role r = roleService.findByName(roleName); if (r != null) { if (u.getRoles().contains(r)) { u.getRoles().remove(r); this.dao.save(u); } } } } /** * {@inheritDoc} */ public void addListener(ServiceListener listener) { // Adds a new listener if needed. if (!listeners.contains(listener)) { listeners.add(listener); } } // addListener(). /** * {@inheritDoc} */ @Override public void removeListener(ServiceListener listener) { // Adds a new listener if needed. if (listeners.contains(listener)) { listeners.remove(listener); } } // removeListener(). /** * Sends a notification to every listernes registered. * Do not fail if a user thrown an exception (report exception in logs). * * @param type Type of notification. * @param arguments Notification arguments. */ protected void publishChange(String type, Object... arguments) { for (ServiceListener listener : listeners) { try { // Sends notification to each known listeners listener.onChange(type, arguments); } catch (Exception exc) { // Log exception logger.warn("[publishChange] Cannot bublish " + type + " changes", exc); } } } // publishChange(). }
File
UserServiceImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
<<<<<<< HEAD
import com.sun.jersey.api.client.WebResource;
=======
import javax.inject.Named;
import org.junit.Test;
import org.resthub.identity.model.Role;
import static org.junit.Assert.*;
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b

/**
 * 
Solution content
package org.resthub.identity.controller;

import java.util.Random;

import javax.inject.Inject;
import javax.ws.rs.core.MediaType;

import junit.framework.Assert;

import org.apache.log4j.Logger;
import org.resthub.identity.model.User;
import org.resthub.identity.service.UserService;
import org.resthub.web.test.controller.AbstractResourceControllerTest;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.ClientResponse.Status;
import javax.inject.Named;
import org.junit.Test;
import org.resthub.identity.model.Role;
import static org.junit.Assert.*;

/**
 * 
 * @author Guillaume Zurbach
 */
public class UserControllerTest extends AbstractResourceControllerTest {

    Logger logger = Logger.getLogger(UserControllerTest.class);
    @Inject
    @Named("roleController")
    protected RoleController roleController;

    @Override
    @Inject
    public void setController(UserController userController) {
        super.setController(userController);
    }

	@Override
	protected User createTestResource() throws Exception {
		logger.debug("UserControllerTest : createTestResource");
		String userLogin = "UserTestUserLogin"+ new Random().nextInt();
		String userPassword = "UserTestUserPassword";
		User u = new User();
		u.setLogin(userLogin);
		u.setPassword(userPassword);
		return u;
	}

    @Override
    public void testUpdate() throws Exception {
        logger.debug("UserControllerTest : testUpdate : START");
        User u1 = createTestResource();
        String userPassword = "UserTestUserPassword";

        WebResource r = resource().path("user");
        logger.debug("UserControllerTest : testUpdate : GonnaPost");
        u1 = r.type(MediaType.APPLICATION_XML).post(User.class, u1);
        logger.debug("UserControllerTest : testUpdate : DidPost");
        r = resource().path("user/" + u1.getId());
        User u2 = u1;
        u2.setPassword(userPassword);
        u2.setLogin("u2");
        // Update login
        ClientResponse cr = r.type(MediaType.APPLICATION_XML).accept(
                MediaType.APPLICATION_JSON).put(ClientResponse.class, u2);
        Assert.assertEquals("User not updated", Status.CREATED.getStatusCode(),
                cr.getStatus());
        String response = resource().path("user").accept(
                MediaType.APPLICATION_JSON).get(String.class);
        Assert.assertFalse("User not updated", response.contains("u1"));
        Assert.assertTrue("User not updated", response.contains("u2"));
    }

    @Test
    public void shouldAddRoleToUser() throws Exception {
        // Given a new role
        Role r = new Role("Role" + Math.round(Math.random() * 1000));
        r = resource().path("role").type(MediaType.APPLICATION_XML).post(Role.class, r);

        // Given a new user
        User u = this.createTestResource();
        u = resource().path("user").type(MediaType.APPLICATION_XML).post(User.class, u);

        // When I associate the user and the role
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).put();

        // Then I get the user with this role
        String userWithRole = resource().path("user/login/" + u.getLogin()).accept(MediaType.APPLICATION_JSON).get(String.class);
        assertTrue("The user should contain the role", userWithRole.contains(r.getName()));
    }

    @Test
    public void shouldRemoveRoleFromUser() throws Exception {
        // Given a new role
        Role r = new Role("Role" + Math.round(Math.random() * 1000));
        r = resource().path("role").type(MediaType.APPLICATION_XML).post(Role.class, r);

        // Given a new user
        User u = this.createTestResource();
        u = resource().path("user").type(MediaType.APPLICATION_XML).post(User.class, u);
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).put();

        // When I associate the user and the role
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).delete();

        // Then I get the user with this role
        String userWithRole = resource().path("user/login/" + u.getLogin()).accept(MediaType.APPLICATION_JSON).get(String.class);
        assertFalse("The user shouldn't contain the role", userWithRole.contains(r.getName()));
    }
}
File
UserControllerTest.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
    protected RoleController roleController;

    @Override
<<<<<<< HEAD
	@Inject
	public void setController(UserController userController) {
		super.setController(userController);
	}

	@Override
	protected User createTestResource() throws Exception {
		logger.debug("UserControllerTest : createTestResource");
		String userLogin = "UserTestUserLogin"+ new Random().nextInt();
		String userPassword = "UserTestUserPassword";
		User u = new User();
		u.setLogin(userLogin);
		u.setPassword(userPassword);
		return u;
	}

	@Override
	public void testUpdate() throws Exception {
		logger.debug("UserControllerTest : testUpdate : START");
		User u1 = createTestResource();
		String userPassword="UserTestUserPassword";
		
		WebResource r = resource().path("user");
		logger.debug("UserControllerTest : testUpdate : GonnaPost");	
		u1 = r.type(MediaType.APPLICATION_XML).post(User.class, u1);
		logger.debug("UserControllerTest : testUpdate : DidPost");
		r = resource().path("user/" + u1.getId());
		User u2 = u1;
		u2.setPassword(userPassword);
		u2.setLogin("u2");
		// Update login
		ClientResponse cr = r.type(MediaType.APPLICATION_XML).accept(
				MediaType.APPLICATION_JSON).put(ClientResponse.class, u2);
		Assert.assertEquals("User not updated", Status.CREATED.getStatusCode(),
				cr.getStatus());
		String response = resource().path("user").accept(
				MediaType.APPLICATION_JSON).get(String.class);
		Assert.assertFalse("User not updated", response.contains("u1"));
		Assert.assertTrue("User not updated", response.contains("u2"));
	}
=======
    @Inject
    public void setController(UserController userController) {
        super.setController(userController);
    }
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b

    @Override
    @SuppressWarnings("unchecked")
Solution content
package org.resthub.identity.controller;

import java.util.Random;

import javax.inject.Inject;
import javax.ws.rs.core.MediaType;

import junit.framework.Assert;

import org.apache.log4j.Logger;
import org.resthub.identity.model.User;
import org.resthub.identity.service.UserService;
import org.resthub.web.test.controller.AbstractResourceControllerTest;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.ClientResponse.Status;
import javax.inject.Named;
import org.junit.Test;
import org.resthub.identity.model.Role;
import static org.junit.Assert.*;

/**
 * 
 * @author Guillaume Zurbach
 */
public class UserControllerTest extends AbstractResourceControllerTest {

    Logger logger = Logger.getLogger(UserControllerTest.class);
    @Inject
    @Named("roleController")
    protected RoleController roleController;

    @Override
    @Inject
    public void setController(UserController userController) {
        super.setController(userController);
    }

	@Override
	protected User createTestResource() throws Exception {
		logger.debug("UserControllerTest : createTestResource");
		String userLogin = "UserTestUserLogin"+ new Random().nextInt();
		String userPassword = "UserTestUserPassword";
		User u = new User();
		u.setLogin(userLogin);
		u.setPassword(userPassword);
		return u;
	}

    @Override
    public void testUpdate() throws Exception {
        logger.debug("UserControllerTest : testUpdate : START");
        User u1 = createTestResource();
        String userPassword = "UserTestUserPassword";

        WebResource r = resource().path("user");
        logger.debug("UserControllerTest : testUpdate : GonnaPost");
        u1 = r.type(MediaType.APPLICATION_XML).post(User.class, u1);
        logger.debug("UserControllerTest : testUpdate : DidPost");
        r = resource().path("user/" + u1.getId());
        User u2 = u1;
        u2.setPassword(userPassword);
        u2.setLogin("u2");
        // Update login
        ClientResponse cr = r.type(MediaType.APPLICATION_XML).accept(
                MediaType.APPLICATION_JSON).put(ClientResponse.class, u2);
        Assert.assertEquals("User not updated", Status.CREATED.getStatusCode(),
                cr.getStatus());
        String response = resource().path("user").accept(
                MediaType.APPLICATION_JSON).get(String.class);
        Assert.assertFalse("User not updated", response.contains("u1"));
        Assert.assertTrue("User not updated", response.contains("u2"));
    }

    @Test
    public void shouldAddRoleToUser() throws Exception {
        // Given a new role
        Role r = new Role("Role" + Math.round(Math.random() * 1000));
        r = resource().path("role").type(MediaType.APPLICATION_XML).post(Role.class, r);

        // Given a new user
        User u = this.createTestResource();
        u = resource().path("user").type(MediaType.APPLICATION_XML).post(User.class, u);

        // When I associate the user and the role
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).put();

        // Then I get the user with this role
        String userWithRole = resource().path("user/login/" + u.getLogin()).accept(MediaType.APPLICATION_JSON).get(String.class);
        assertTrue("The user should contain the role", userWithRole.contains(r.getName()));
    }

    @Test
    public void shouldRemoveRoleFromUser() throws Exception {
        // Given a new role
        Role r = new Role("Role" + Math.round(Math.random() * 1000));
        r = resource().path("role").type(MediaType.APPLICATION_XML).post(Role.class, r);

        // Given a new user
        User u = this.createTestResource();
        u = resource().path("user").type(MediaType.APPLICATION_XML).post(User.class, u);
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).put();

        // When I associate the user and the role
        resource().path("user/name/" + u.getLogin() + "/roles/" + r.getName()).type(MediaType.APPLICATION_XML).delete();

        // Then I get the user with this role
        String userWithRole = resource().path("user/login/" + u.getLogin()).accept(MediaType.APPLICATION_JSON).get(String.class);
        assertFalse("The user shouldn't contain the role", userWithRole.contains(r.getName()));
    }
}
File
UserControllerTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
        this.resourceService.delete(u);
        this.groupService.delete(g);
    }
<<<<<<< HEAD
    
    @Test
    public void shouldCreationBeNotified() {
    	// Given a registered listener
    	TestListener listener = new TestListener();
    	userService.addListener(listener);
    	
    	// Given a user
    	User u = new User();
    	u.setLogin("user"+new Random().nextInt());
    	
    	// When saving it
    	u = userService.create(u);
    	
    	// Then a creation notification has been received
    	assertEquals(UserServiceChange.USER_CREATION.name(), listener.lastType);
    	assertArrayEquals(new Object[]{u}, listener.lastArguments);    	
    } // shouldCreationBeNotified().
    
    @Test
    public void shouldDeletionBeNotifiedById() {
    	// Given a registered listener
    	TestListener listener = new TestListener();
    	userService.addListener(listener);
    	
    	// Given a created user
    	User u = new User();
    	u.setLogin("user"+new Random().nextInt());
    	u = userService.create(u);
    	
    	// When removing it by id
    	userService.delete(u.getId());
    	
    	// Then a deletion notification has been received
    	assertEquals(UserServiceChange.USER_DELETION.name(), listener.lastType);
    	assertArrayEquals(new Object[]{u}, listener.lastArguments);    	
    } // shouldDeletionBeNotifiedById().
    
    @Test
    public void shouldDeletionBeNotifiedByUser() {
    	// Given a registered listener
    	TestListener listener = new TestListener();
    	userService.addListener(listener);
    	
    	// Given a created user
    	User u = new User();
    	u.setLogin("user"+new Random().nextInt());
    	u = userService.create(u);
    	
    	// When removing it
    	userService.delete(u);
    	
    	// Then a deletion notification has been received
    	assertEquals(UserServiceChange.USER_DELETION.name(), listener.lastType);
    	assertArrayEquals(new Object[]{u}, listener.lastArguments);    	
    } // shouldDeletionBeNotifiedByUser().
    
    @Test
    public void shouldUserAdditionToGroupBeNotified() {
    	// Given a registered listener
    	TestListener listener = new TestListener();
    	userService.addListener(listener);
    	
    	// Given a created user
    	User u = new User();
    	u.setLogin("user"+new Random().nextInt());
    	u = userService.create(u);
    	
    	// Given a group
    	Group g = new Group();
    	g.setName("group"+new Random().nextInt());
    	g = groupService.create(g);
    	
    	// When adding the user to the group
    	userService.addGroupToUser(u.getLogin(), g.getName());
    	
    	// Then a deletion notification has been received
    	assertEquals(UserServiceChange.USER_ADDED_TO_GROUP.name(), listener.lastType);
    	assertArrayEquals(new Object[]{u, g}, listener.lastArguments);    	
    } // shouldUserAdditionToGroupBeNotified().
    
    @Test
    public void shouldUserRemovalFromGroupBeNotified() {
    	// Given a registered listener
    	TestListener listener = new TestListener();
    	userService.addListener(listener);
    	
    	// Given a group
    	Group g = new Group();
    	g.setName("group"+new Random().nextInt());
    	g = groupService.create(g);

    	// Given a created user in this group
    	User u = new User();
    	u.setLogin("user"+new Random().nextInt());
    	u = userService.create(u);   	
    	userService.addGroupToUser(u.getLogin(), g.getName());
   	
    	// When adding the user to the group
    	userService.removeGroupFromUser(u.getLogin(), g.getName());
    	
    	// Then a deletion notification has been received
    	assertEquals(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), listener.lastType);
    	assertArrayEquals(new Object[]{u, g}, listener.lastArguments);    	
    } // shouldUserRemovalFromGroupBeNotified().
=======

    @Test
    public void shouldGetUsersWithDirectRole() {
        // Given some new roles
        Role r1 = new Role("role1");
        Role r2 = new Role("role2");
        r1 = this.roleService.create(r1);
        r2 = this.roleService.create(r2);

        // Given some new users
        // u1 with role1
        User u1 = this.createTestRessource();
        u1.getRoles().add(r1);
        // u2 without any role
        User u2 = this.createTestRessource();
        // u3 with role2
        User u3 = this.createTestRessource();
        u3.getRoles().add(r2);
        // u4 with both role1 and role2
        User u4 = this.createTestRessource();
        u4.getRoles().add(r1);
        u4.getRoles().add(r2);

        u1 = this.resourceService.create(u1);
        u2 = this.resourceService.create(u2);
        u3 = this.resourceService.create(u3);
        u4 = this.resourceService.create(u4);

        // When I look for users with roles
        List notExistingRoleUsers = this.resourceService.findAllUsersWithRoles(Arrays.asList("role"));
        List role1Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1"));
        List role2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2"));
        List role1AndRole2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1", "role2"));

        // Then the lists should only contain what I asked for
        assertTrue("A search with an unknown role shouldn't bring anything", notExistingRoleUsers.isEmpty());

        assertEquals("The list of users with role1 should contain 2 elements", 2, role1Users.size());
        assertTrue("The list of users with role1 should contain user1", role1Users.contains(u1));
        assertTrue("The list of users with role1 should contain user4", role1Users.contains(u4));

        assertEquals("The list of users with role2 should contain 2 elements", 2, role2Users.size());
        assertTrue("The list of users with role2 should contain user3", role2Users.contains(u3));
        assertTrue("The list of users with role2 should contain user4", role2Users.contains(u4));

        assertEquals("The list of users with role1 and role2 should contain 3 elements", 3, role1AndRole2Users.size());
        assertTrue("The list of users with role2 should contain user1", role1AndRole2Users.contains(u1));
        assertTrue("The list of users with role2 should contain user3", role1AndRole2Users.contains(u3));
        assertTrue("The list of users with role2 should contain user4", role1AndRole2Users.contains(u4));
    }

    /**
     * Here is a little scheme of the hierarchy that will be set in this test
     * g1 (r1)
     * |_g2 (r2)
     * | |_g4 (r4)
     * |   |_u1 (r1)
     * |   |_u3
     * |_g3 (r3)
     *   |_u2
     *   |_u3
     *   |_u4 (r4)
     */
    @Test
    public void shouldGetUsersWithInheritedRoles() {
        // Given some new roles
        Role r1 = new Role("role1");
        Role r2 = new Role("role2");
        Role r3 = new Role("role3");
        Role r4 = new Role("role4");
        r1 = this.roleService.create(r1);
        r2 = this.roleService.create(r2);
        r3 = this.roleService.create(r3);
        r4 = this.roleService.create(r4);

        // Given some new groups
        Group g1 = this.createTestGroup();
        Group g2 = this.createTestGroup();
        Group g3 = this.createTestGroup();
        Group g4 = this.createTestGroup();

        g1.getRoles().add(r1); // add role1 to g1
        g2.getGroups().add(g1); // add g1 as parent of g2
        g2.getRoles().add(r2); // add role2 to g2
        g3.getGroups().add(g1); // add g1 as parent of g3
        g3.getRoles().add(r3); // add role3 to g3
        g4.getGroups().add(g2); // add g2 as parent of g4
        g4.getRoles().add(r4); // add role4 to g4

        g1 = this.groupService.create(g1);
        g2 = this.groupService.create(g2);
        g3 = this.groupService.create(g3);
        g4 = this.groupService.create(g4);

        // Given some new users
        // u1 with direct role1 and inside group4
        User u1 = this.createTestRessource();
        u1.getRoles().add(r1); // add role1 to u1
        u1.getGroups().add(g4); // add group4 as parent of u1

        // u2 without any role and inside group3
        User u2 = this.createTestRessource();
        u2.getGroups().add(g3);

        // u3 without any role and inside group3 and group4
        User u3 = this.createTestRessource();
        u3.getGroups().add(g3);
        u3.getGroups().add(g4);

        // u4 with role4 and inside group3
        User u4 = this.createTestRessource();
        u4.getRoles().add(r4);
        u4.getGroups().add(g3);

        u1 = this.resourceService.create(u1);
        u2 = this.resourceService.create(u2);
        u3 = this.resourceService.create(u3);
        u4 = this.resourceService.create(u4);

        // When I look for users with roles
        List notExistingRoleUsers = this.resourceService.findAllUsersWithRoles(Arrays.asList("role"));
        List role1Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1"));
        List role2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2"));
        List role3Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role3"));
        List role4Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role4"));
        List role2AndRole3Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2", "role3"));

        // Then the lists should only contain what I asked for
        assertTrue("A search with an unknown role shouldn't bring anything", notExistingRoleUsers.isEmpty());

        assertEquals("The list of users with role1 should contain 4 elements", 4, role1Users.size());
        assertTrue("The list of users with role1 should contain user1", role1Users.contains(u1));
        assertTrue("The list of users with role1 should contain user2", role1Users.contains(u2));
        assertTrue("The list of users with role1 should contain user3", role1Users.contains(u3));
        assertTrue("The list of users with role1 should contain user4", role1Users.contains(u4));

        assertEquals("The list of users with role2 should contain 2 elements", 2, role2Users.size());
        assertTrue("The list of users with role2 should contain user1", role2Users.contains(u1));
        assertTrue("The list of users with role2 should contain user3", role2Users.contains(u3));

        assertEquals("The list of users with role3 should contain 3 elements", 3, role3Users.size());
        assertTrue("The list of users with role3 should contain user2", role3Users.contains(u2));
        assertTrue("The list of users with role3 should contain user3", role3Users.contains(u3));
        assertTrue("The list of users with role3 should contain user4", role3Users.contains(u4));

        assertEquals("The list of users with role4 should contain 3 elements", 3, role4Users.size());
        assertTrue("The list of users with role4 should contain user1", role4Users.contains(u1));
        assertTrue("The list of users with role4 should contain user3", role4Users.contains(u3));
        assertTrue("The list of users with role4 should contain user4", role4Users.contains(u4));

        assertEquals("The list of users with role2 and role3 should contain 4 elements", 4, role2AndRole3Users.size());
        assertTrue("The list of users with role2 and role3 should contain user1", role2AndRole3Users.contains(u1));
        assertTrue("The list of users with role2 and role3 should contain user2", role2AndRole3Users.contains(u2));
        assertTrue("The list of users with role2 and role3 should contain user3", role2AndRole3Users.contains(u3));
        assertTrue("The list of users with role2 and role3 should contain user4", role2AndRole3Users.contains(u4));
    }

    @Test
    public void shouldAddRoleToUser() {
        // Given a new role
        Role r = new Role("Role");
        r = this.roleService.create(r);

        // Given a new user
        User u = this.createTestRessource();
        u = this.resourceService.create(u);

        // When I associate the user and the role
        this.resourceService.addRoleToUser(u.getLogin(), r.getName());

        // Then I get the user with this role
        User userWithRole = this.resourceService.findById(u.getId());
        assertTrue("The user should contain the role", userWithRole.getRoles().contains(r));
    }

    @Test
    public void shouldRemoveRoleFromUser() {
        // Given a new role
        Role r = new Role("Role");
        r = this.roleService.create(r);

        // Given a new user associated to the previous role
        User u = this.createTestRessource();
        u = this.resourceService.create(u);
        this.resourceService.addRoleToUser(u.getLogin(), r.getName());
        // When I remove the role from the user
        this.resourceService.removeRoleFromUser(u.getLogin(), r.getName());

        // Then I get the user without this role
        User userWithRole = this.resourceService.findById(u.getId());
        assertFalse("The user shouldn't contain the role", userWithRole.getRoles().contains(r));
    }
>>>>>>> e971e839eadd419ecf3ffb1656c5b86b33365b2b
}
Solution content
package org.resthub.identity.service;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.inject.Inject;
import javax.inject.Named;

import junit.framework.Assert;

import org.junit.Test;
import org.resthub.core.test.service.AbstractResourceServiceTest;
        assertNull(retrievedUser);
import org.resthub.identity.model.Group;
import org.resthub.identity.model.Role;
import org.resthub.identity.model.User;
import org.resthub.identity.service.UserService.UserServiceChange;

public class UserServiceTest extends AbstractResourceServiceTest {

    @Inject
    @Named("userService")
    @Override
    public void setResourceService(UserService resourceService) {
        super.setResourceService(resourceService);
    }
    @Inject
    @Named("groupService")
    private GroupService groupService;
    @Inject
    @Named("roleService")
    private RoleService roleService;

    @Override
    public User createTestRessource() {
        String userLogin = "UserTestUserName" + Math.round(Math.random() * 1000);
        String userPassword = "UserTestUserPassword";
        User u = new User();
        u.setLogin(userLogin);
        u.setPassword(userPassword);
        return u;
    }

    public Group createTestGroup() {
        Group g = new Group();
        g.setName("TestGroup" + Math.round(Math.random() * 1000));
        return g;
    }
    /*
     * The UserService is needed because we have specific method for password
     * management
     */
    UserService userService;

    @Inject
    @Named("userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Test
    public void testMultiDeletion() throws Exception {

        User u1 = new User();
        u1.setLogin("u1");

        User u2 = new User();
        u2.setLogin("u2");

        u1 = resourceService.create(u1);
        u2 = resourceService.create(u2);

        resourceService.delete(u1);
        resourceService.delete(u2);

        Assert.assertNull(resourceService.findById(u1.getId()));
        Assert.assertNull(resourceService.findById(u2.getId()));

    }

    @Override
    @Test
    public void testUpdate() throws Exception {
        /* Given a new user */
        String firstName = "alexander";
        String firstNameAbr = "alex";
        String lastName = "testUpdate";
        String password = "testPassword";
        String login = "testLogin";

        User u = new User();
        u.setFirstName(firstName);
        u.setLastName(lastName);
        u.setPassword(password);
        u.setLogin(login);
        u = this.resourceService.create(u);


        this.resourceService.delete(u);
        // when we try to change some info (firstName) about the user and that we give the good password
        u = new User(u);
        u.setFirstName(firstNameAbr);
        u.setPassword(password);
        u = resourceService.update(u);

        // Then The modification is updated
        assertEquals(u.getFirstName(), firstNameAbr);

        this.resourceService.delete(u);
    }

    @Test
    public void shouldGetUserByAuthenticationInformationWhenOK() {
        /* Given a new user */

        String login = "alexOK";
        String password = "alex-pass";
        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        resourceService.create(u);
        // userService.create(u);

        /* When we search him with good login and password */
        // u = userService.authenticateUser(login, password);

        u = resourceService.authenticateUser(login, password);

        /* Then we retrieve the good user */
        assertNotNull(u);
        assertEquals(u.getLogin(), login);
        resourceService.delete(u);
        // userService.delete(u);
    }

    @Test
    public void shouldGetUserByAuthenticationInformationWhenOKAfterUpdate() {
        /* Given a new user */

        String login = "alexOK";
        String password1 = "alex-pass";
        String password2 = "NewAlex-pass";

        User u = new User();
        u.setLogin(login);
        u.setPassword(password1);
        resourceService.create(u);

        /* After that the password is updates */
        u.setPassword(password2);
        u = resourceService.updatePassword(u);

        /* When we search him with good login and password */
        u = resourceService.authenticateUser(login, password2);

        /* Then we retrieve the good user */
        assertNotNull(u);
        assertEquals(u.getLogin(), login);

        resourceService.delete(u);
        // userService.delete(u);
    }

    @Test
    public void shouldGetNullWhenBadPassword() {
        /* Given a new user */
        String login = "alexBadPassword";
        String password = "alex-pass";
        String badPassword = "alex-bad-pass";

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        resourceService.create(u);
        // userService.create(u);
		/* When we search him providing a bad password */
        User retrievedUser = resourceService.authenticateUser(login,
                badPassword);

        /* Then the user is not retrieved */
        assertNull(retrievedUser);

        resourceService.delete(u);
    }

    @Test
    public void shouldGetNullWhenBadLogin() {
        String login = "alexBadLogin";
        String badLogin = "alex";
        String password = "alex-password";
        /* Given a new user */

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        resourceService.create(u);

        /* When we search him providing a bad login */
        User retrievedUser = resourceService.authenticateUser(badLogin,
                password);
        /* Then the user is not retrieved */

    }

    @Test
    public void testDirectPermissions() {
        /* Given a user with permissions */
        String login = "permissionLogin";
        String password = "Password";

        // direct permissions
        List permissions = new ArrayList();
        permissions.add("ADMIN");
        permissions.add("USER");

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        u.getPermissions().addAll(permissions);
        resourceService.create(u);

        /* When we retrieved him after a search */
        u = resourceService.findByLogin(login);

        /* We can get the direct permissions */
        assertEquals("Permissions not found", 2, u.getPermissions().size());
        assertTrue("Permissions not found", u.getPermissions().contains("ADMIN"));
        assertTrue("Permissions not found", u.getPermissions().contains("USER"));

        resourceService.delete(u);

    }

    @Test
    public void testGroupsPermissions() {
        /* Given a user with permissions */
        String login = "permissionLogin";
        String password = "Password";

        // direct permissions
        List permissions = new ArrayList();
        permissions.add("ADMIN");
        permissions.add("USER");

        // a group and a subGroup
        Group group = new Group();
        Group subGroup = new Group();
        group.setName("TestGroup");
        subGroup.setName("TestSubGroup");

        // add a permission to each group
        group.getPermissions().add("TESTGROUPPERMISSION");
        subGroup.getPermissions().add("TESTSUBGROUPPERMISSION");

        // make subGroup a permission of group
        group.getGroups().add(subGroup);

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        u.getPermissions().addAll(permissions);
        u.getGroups().add(group);
        resourceService.create(u);

        /* When we retrieved him after a search */
        u = resourceService.findByLogin(login);

        /* We can get the direct permissions */
        assertEquals("Permissions not found", 2, u.getPermissions().size());
        assertTrue("Permissions not found", u.getPermissions().contains("ADMIN"));
        assertTrue("Permissions not found", u.getPermissions().contains("USER"));

        /* now with the permissions from groups */
        List allPermissions = resourceService.getUserPermissions(login);
        assertEquals("Permissions not found", 4, allPermissions.size());
        assertTrue("Permissions not found", allPermissions.contains("ADMIN"));
        assertTrue("Permissions not found", allPermissions.contains("USER"));
        assertTrue("Permissions not found", allPermissions.contains("TESTGROUPPERMISSION"));
        assertTrue("Permissions not found", allPermissions.contains("TESTSUBGROUPPERMISSION"));

        resourceService.delete(u);
    }

    @Test
    public void testDuplicatePermissions() {
        /* Given a user with permissions */
        String login = "permissionLogin";
        String password = "Password";

        // direct permissions
        List permissions = new ArrayList();
        permissions.add("ADMIN");
        permissions.add("USER");

        // a group and a subGroup
        Group group = new Group();
        Group subGroup = new Group();
        group.setName("TestGroup");
        subGroup.setName("TestSubGroup");

        // add a permission to each group
        group.getPermissions().add("TESTGROUPPERMISSION");
        subGroup.getPermissions().add("TESTSUBGROUPPERMISSION");

        // this is the test: USER is already a direct permission of this user
        // getUserPermission should return only one time the permission USER
        group.getPermissions().add("USER");

        // make subGroup a permission of group
        group.getGroups().add(subGroup);

        User u = new User();
        u.setLogin(login);
        u.setPassword(password);
        u.getPermissions().addAll(permissions);
        u.getGroups().add(group);
        resourceService.create(u);

        /* When we retrieved him after a search */
        u = resourceService.findByLogin(login);

        /* We can get the direct permissions */
        assertEquals("Permissions not found", 2, u.getPermissions().size());
        assertTrue("Permissions not found", u.getPermissions().contains("ADMIN"));
        assertTrue("Permissions not found", u.getPermissions().contains("USER"));

        /* now with the permissions from groups */
        List allPermissions = resourceService.getUserPermissions(login);
        assertEquals("Permissions not found", 4, allPermissions.size());
        assertTrue("Permissions not found", allPermissions.contains("ADMIN"));
        // the USER permission should exists only once in the list
        assertTrue("Permissions not found", allPermissions.contains("USER"));
        assertTrue("Permissions not found", allPermissions.contains("TESTGROUPPERMISSION"));
        assertTrue("Permissions not found", allPermissions.contains("TESTSUBGROUPPERMISSION"));

        resourceService.delete(u);
    }

    @Test
    public void testRolesPermissions() {
        // TODO: when roles are implemented, test that getUserPermissions also retrieve
        // the permissions set from roles.
    }

    @Test
    public void testShouldGetUsersFromGroup() {
        /* Given a new group */
        String groupName = "testGroup";
        Group g = new Group();
        g.setName(groupName);
        this.groupService.create(g);

        /* Given a new user */
        String firstName = "first";
        String lastName = "last";
        String password = "pass";
        String login = "testLogin";

        User u = new User();
        u.setFirstName(firstName);
        u.setLastName(lastName);
        u.setPassword(password);
        u.setLogin(login);

        /* Given a link between this user and the group */
        u.getGroups().add(g);
        u = this.resourceService.create(u);

        /* When I get the users of the group */
        List usersFromGroup = this.resourceService.getUsersFromGroup(groupName);

        /* Then the list of users contains our user */
        assertTrue("The list of users should contain our just added user", usersFromGroup.contains(u));

        /* Cleanup */
        this.resourceService.delete(u);
        this.groupService.delete(g);
    }

    @Test
    public void shouldGetUsersWithDirectRole() {
        // Given some new roles
        Role r1 = new Role("role1");
        Role r2 = new Role("role2");
        r1 = this.roleService.create(r1);
        r2 = this.roleService.create(r2);

        // Given some new users
        // u1 with role1
        User u1 = this.createTestRessource();
        u1.getRoles().add(r1);
        // u2 without any role
        User u2 = this.createTestRessource();
        // u3 with role2
        User u3 = this.createTestRessource();
        u3.getRoles().add(r2);
        // u4 with both role1 and role2
        User u4 = this.createTestRessource();
        u4.getRoles().add(r1);
        u4.getRoles().add(r2);

        u1 = this.resourceService.create(u1);
        u2 = this.resourceService.create(u2);
        u3 = this.resourceService.create(u3);
        u4 = this.resourceService.create(u4);

        // When I look for users with roles
        List notExistingRoleUsers = this.resourceService.findAllUsersWithRoles(Arrays.asList("role"));
        List role1Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1"));
        List role2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2"));
        List role1AndRole2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1", "role2"));

        // Then the lists should only contain what I asked for
        assertTrue("A search with an unknown role shouldn't bring anything", notExistingRoleUsers.isEmpty());

        assertEquals("The list of users with role1 should contain 2 elements", 2, role1Users.size());
        assertTrue("The list of users with role1 should contain user1", role1Users.contains(u1));
        assertTrue("The list of users with role1 should contain user4", role1Users.contains(u4));

        assertEquals("The list of users with role2 should contain 2 elements", 2, role2Users.size());
        assertTrue("The list of users with role2 should contain user3", role2Users.contains(u3));
        assertTrue("The list of users with role2 should contain user4", role2Users.contains(u4));

        assertEquals("The list of users with role1 and role2 should contain 3 elements", 3, role1AndRole2Users.size());
        assertTrue("The list of users with role2 should contain user1", role1AndRole2Users.contains(u1));
        assertTrue("The list of users with role2 should contain user3", role1AndRole2Users.contains(u3));
        assertTrue("The list of users with role2 should contain user4", role1AndRole2Users.contains(u4));
    }

    /**
     * Here is a little scheme of the hierarchy that will be set in this test
     * g1 (r1)
     * |_g2 (r2)
     * | |_g4 (r4)
     * |   |_u1 (r1)
     * |   |_u3
     * |_g3 (r3)
     *   |_u2
     *   |_u3
     *   |_u4 (r4)
     */
    @Test
    public void shouldGetUsersWithInheritedRoles() {
        // Given some new roles
        Role r1 = new Role("role1");
        Role r2 = new Role("role2");
        Role r3 = new Role("role3");
        Role r4 = new Role("role4");
        r1 = this.roleService.create(r1);
        r2 = this.roleService.create(r2);
        r3 = this.roleService.create(r3);
        r4 = this.roleService.create(r4);

        // Given some new groups
        Group g1 = this.createTestGroup();
        Group g2 = this.createTestGroup();
        Group g3 = this.createTestGroup();
        Group g4 = this.createTestGroup();

        g1.getRoles().add(r1); // add role1 to g1
        g2.getGroups().add(g1); // add g1 as parent of g2
        g2.getRoles().add(r2); // add role2 to g2
        g3.getGroups().add(g1); // add g1 as parent of g3
        g3.getRoles().add(r3); // add role3 to g3
        g4.getGroups().add(g2); // add g2 as parent of g4
        g4.getRoles().add(r4); // add role4 to g4

        g1 = this.groupService.create(g1);
        g2 = this.groupService.create(g2);
        g3 = this.groupService.create(g3);
        g4 = this.groupService.create(g4);

        // Given some new users
        // u1 with direct role1 and inside group4
        User u1 = this.createTestRessource();
        u1.getRoles().add(r1); // add role1 to u1
        u1.getGroups().add(g4); // add group4 as parent of u1

        // u2 without any role and inside group3
        User u2 = this.createTestRessource();
        u2.getGroups().add(g3);

        // u3 without any role and inside group3 and group4
        User u3 = this.createTestRessource();
        u3.getGroups().add(g3);
        u3.getGroups().add(g4);

        // u4 with role4 and inside group3
        User u4 = this.createTestRessource();
        u4.getRoles().add(r4);
        u4.getGroups().add(g3);

        u1 = this.resourceService.create(u1);
        u2 = this.resourceService.create(u2);
        u3 = this.resourceService.create(u3);
        u4 = this.resourceService.create(u4);

        // When I look for users with roles
        List notExistingRoleUsers = this.resourceService.findAllUsersWithRoles(Arrays.asList("role"));

        List role1Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role1"));
        List role2Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2"));
        List role3Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role3"));
        List role4Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role4"));
        List role2AndRole3Users = this.resourceService.findAllUsersWithRoles(Arrays.asList("role2", "role3"));

        // Then the lists should only contain what I asked for
        assertTrue("A search with an unknown role shouldn't bring anything", notExistingRoleUsers.isEmpty());

        assertEquals("The list of users with role1 should contain 4 elements", 4, role1Users.size());
        assertTrue("The list of users with role1 should contain user1", role1Users.contains(u1));
        assertTrue("The list of users with role1 should contain user2", role1Users.contains(u2));
        assertTrue("The list of users with role1 should contain user3", role1Users.contains(u3));
        assertTrue("The list of users with role1 should contain user4", role1Users.contains(u4));

        assertEquals("The list of users with role2 should contain 2 elements", 2, role2Users.size());
        assertTrue("The list of users with role2 should contain user1", role2Users.contains(u1));
        assertTrue("The list of users with role2 should contain user3", role2Users.contains(u3));

        assertEquals("The list of users with role3 should contain 3 elements", 3, role3Users.size());
        assertTrue("The list of users with role3 should contain user2", role3Users.contains(u2));
        assertTrue("The list of users with role3 should contain user3", role3Users.contains(u3));
        assertTrue("The list of users with role3 should contain user4", role3Users.contains(u4));

        assertEquals("The list of users with role4 should contain 3 elements", 3, role4Users.size());
        assertTrue("The list of users with role4 should contain user1", role4Users.contains(u1));
        assertTrue("The list of users with role4 should contain user3", role4Users.contains(u3));
        assertTrue("The list of users with role4 should contain user4", role4Users.contains(u4));

        assertEquals("The list of users with role2 and role3 should contain 4 elements", 4, role2AndRole3Users.size());
        assertTrue("The list of users with role2 and role3 should contain user1", role2AndRole3Users.contains(u1));
        assertTrue("The list of users with role2 and role3 should contain user2", role2AndRole3Users.contains(u2));
        assertTrue("The list of users with role2 and role3 should contain user3", role2AndRole3Users.contains(u3));
        assertTrue("The list of users with role2 and role3 should contain user4", role2AndRole3Users.contains(u4));
    }

    @Test
    public void shouldAddRoleToUser() {
        // Given a new role
        Role r = new Role("Role");
        r = this.roleService.create(r);

        // Given a new user
        User u = this.createTestRessource();
        u = this.resourceService.create(u);

        // When I associate the user and the role
        this.resourceService.addRoleToUser(u.getLogin(), r.getName());

        // Then I get the user with this role
        User userWithRole = this.resourceService.findById(u.getId());
        assertTrue("The user should contain the role", userWithRole.getRoles().contains(r));
    }

    @Test
    public void shouldRemoveRoleFromUser() {
        // Given a new role
        Role r = new Role("Role");
        r = this.roleService.create(r);

        // Given a new user associated to the previous role
        User u = this.createTestRessource();
        u = this.resourceService.create(u);
        this.resourceService.addRoleToUser(u.getLogin(), r.getName());

        // When I remove the role from the user
        this.resourceService.removeRoleFromUser(u.getLogin(), r.getName());

        // Then I get the user without this role
        User userWithRole = this.resourceService.findById(u.getId());
        assertFalse("The user shouldn't contain the role", userWithRole.getRoles().contains(r));
    }

    @Test
    public void shouldCreationBeNotified() {
        // Given a registered listener
        TestListener listener = new TestListener();
        userService.addListener(listener);
        // Given a user
        User u = new User();
        u.setLogin("user" + new Random().nextInt());

        // When saving it
        u = userService.create(u);

        // Then a creation notification has been received
        assertEquals(UserServiceChange.USER_CREATION.name(), listener.lastType);
        assertArrayEquals(new Object[]{u}, listener.lastArguments);
    } // shouldCreationBeNotified().

    @Test
    public void shouldDeletionBeNotifiedById() {
        // Given a registered listener
        TestListener listener = new TestListener();
        userService.addListener(listener);

        // Given a created user
        User u = new User();
        u.setLogin("user" + new Random().nextInt());
        u = userService.create(u);

        // When removing it by id
        userService.delete(u.getId());

        // Then a deletion notification has been received
        assertEquals(UserServiceChange.USER_DELETION.name(), listener.lastType);
        assertArrayEquals(new Object[]{u}, listener.lastArguments);
    } // shouldDeletionBeNotifiedById().

    @Test
    public void shouldDeletionBeNotifiedByUser() {
        // Given a registered listener
        TestListener listener = new TestListener();
        userService.addListener(listener);

        // Given a created user
        User u = new User();
        u.setLogin("user" + new Random().nextInt());
        u = userService.create(u);

        // When removing it
        userService.delete(u);

        // Then a deletion notification has been received
        assertEquals(UserServiceChange.USER_DELETION.name(), listener.lastType);
        assertArrayEquals(new Object[]{u}, listener.lastArguments);
    } // shouldDeletionBeNotifiedByUser().

    @Test
    public void shouldUserAdditionToGroupBeNotified() {
        // Given a registered listener
        TestListener listener = new TestListener();
        userService.addListener(listener);

        // Given a created user
        User u = new User();
        u.setLogin("user" + new Random().nextInt());
        u = userService.create(u);

        // Given a group
        Group g = new Group();
        g.setName("group" + new Random().nextInt());
        g = groupService.create(g);

        // When adding the user to the group
        userService.addGroupToUser(u.getLogin(), g.getName());

        // Then a deletion notification has been received
        assertEquals(UserServiceChange.USER_ADDED_TO_GROUP.name(), listener.lastType);
        assertArrayEquals(new Object[]{u, g}, listener.lastArguments);
    } // shouldUserAdditionToGroupBeNotified().

    @Test
    public void shouldUserRemovalFromGroupBeNotified() {
        // Given a registered listener
        TestListener listener = new TestListener();
        userService.addListener(listener);

        // Given a group
        Group g = new Group();
        g.setName("group" + new Random().nextInt());
        g = groupService.create(g);

        // Given a created user in this group
        User u = new User();
        u.setLogin("user" + new Random().nextInt());
        u = userService.create(u);
        userService.addGroupToUser(u.getLogin(), g.getName());

        // When adding the user to the group
        userService.removeGroupFromUser(u.getLogin(), g.getName());

        // Then a deletion notification has been received
        assertEquals(UserServiceChange.USER_REMOVED_FROM_GROUP.name(), listener.lastType);
        assertArrayEquals(new Object[]{u, g}, listener.lastArguments);
    } // shouldUserRemovalFromGroupBeNotified().
}
File
UserServiceTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration