Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.dagitab.opensocial.service.impl;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- import javax.jws.WebService;
- import javax.persistence.NoResultException;
- import javax.persistence.PersistenceException;
- import javax.persistence.Query;
- import javax.persistence.TemporalType;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.dao.DataIntegrityViolationException;
- import org.springframework.orm.jpa.JpaSystemException;
- import org.springframework.security.providers.encoding.PasswordEncoder;
- import org.springframework.security.userdetails.UsernameNotFoundException;
- import org.springframework.stereotype.Service;
- import com.dagitab.opensocial.dao.GenericDao;
- import com.dagitab.opensocial.dao.RoleDao;
- import com.dagitab.opensocial.dao.UserDao;
- import com.dagitab.opensocial.model.Permission;
- import com.dagitab.opensocial.model.Role;
- import com.dagitab.opensocial.model.User;
- import com.dagitab.opensocial.service.UserExistsException;
- import com.dagitab.opensocial.service.UserManager;
- import com.dagitab.opensocial.service.UserService;
- /**
- * Implementation of UserManager interface.
- *
- * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
- */
- @Service("userManager")
- @WebService(serviceName = "UserService", endpointInterface = "com.dagitab.opensocial.service.UserService")
- public class UserManagerImpl extends GenericManagerImpl<User, Long> implements UserManager, UserService {
- private PasswordEncoder passwordEncoder;
- private UserDao userDao;
- private RoleDao roalDao;
- private GenericDao<Permission, String> permissionDao;
- @Autowired
- public void setPasswordEncoder(final PasswordEncoder passwordEncoder) {
- this.passwordEncoder = passwordEncoder;
- }
- @Autowired
- public void setUserDao(final UserDao userDao) {
- this.dao = userDao;
- this.userDao = userDao;
- }
- @Autowired
- public void setRoalDao(final RoleDao roalDao) {
- this.roalDao = roalDao;
- }
- @Autowired
- public void setPermissionDao(
- @Qualifier("permissionDao") final
- GenericDao<Permission, String> permissionDao) {
- this.permissionDao = permissionDao;
- }
- /**
- * {@inheritDoc}
- */
- public User getUser(final String userId) {
- return userDao.get(new Long(userId));
- }
- /**
- * {@inheritDoc}
- */
- public List<User> getUsers() {
- return userDao.getAllDistinct();
- }
- /**
- * {@inheritDoc}
- */
- public User saveUser(final User user) throws UserExistsException {
- if (user.getVersion() == null) {
- // if new user, lowercase userId
- user.setUsername(user.getUsername().toLowerCase());
- }
- // Get and prepare password management-related artifacts
- boolean passwordChanged = false;
- if (passwordEncoder != null) {
- // Check whether we have to encrypt (or re-encrypt) the password
- if (user.getVersion() == null) {
- // New user, always encrypt
- passwordChanged = true;
- } else {
- // Existing user, check password in DB
- final String currentPassword = userDao.getUserPassword(user.getUsername());
- if (currentPassword == null) {
- passwordChanged = true;
- } else {
- if (!currentPassword.equals(user.getPassword())) {
- passwordChanged = true;
- }
- }
- }
- // If password was changed (or new user), encrypt it
- if (passwordChanged) {
- user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
- }
- } else {
- log.warn("PasswordEncoder not set, skipping password encryption...");
- }
- user.setUpdateDate(new java.util.Date());
- user.setAccessDate(new java.util.Date());
- user.setUserId(user.getUsername());
- try {
- return userDao.saveUser(user);
- } catch (final DataIntegrityViolationException e) {
- //e.printStackTrace();
- log.warn(e.getMessage());
- throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
- } catch (final JpaSystemException e) { // needed for JPA
- //e.printStackTrace();
- log.warn(e.getMessage());
- throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
- }
- }
- /**
- * {@inheritDoc}
- */
- public void removeUser(final String userId) {
- log.debug("removing user: " + userId);
- userDao.remove(new Long(userId));
- }
- /**
- * {@inheritDoc}
- *
- * @param username the login name of the human
- * @return User the populated user object
- * @throws UsernameNotFoundException thrown when username not found
- */
- public User getUserByUsername(final String username) throws UsernameNotFoundException {
- return (User) userDao.loadUserByUsername(username);
- }
- // Register users, update extended user profile data, etc.
- public void registerUser(final User user) {
- if (user == null) {
- throw new IllegalArgumentException("Cannot register null user");
- }
- try {
- saveUser(user);
- }
- catch (final UserExistsException e) {
- throw new IllegalArgumentException("User already exist", e);
- }
- }
- public void removeUser(final User user) {
- if (user == null) {
- throw new IllegalArgumentException("Cannot remove null user");
- }
- if (user.isNew()) {
- throw new IllegalArgumentException("Cannot remove unpersisted user");
- }
- removeUser(user.getId() + "");
- }
- public long getUserCount() {
- final Query query = getNamedQuery("User.count");
- final Long count = (Long)query.getSingleResult();
- return count;
- }
- public User getUserByUserId(final String UserId) {
- return getUserByUserId(UserId, null);
- }
- public User getUserByUserId(final String UserId, final Boolean enabled) {
- if (UserId == null) {
- throw new IllegalArgumentException("Cannot get user with null UserId");
- }
- Query query = null;
- if (enabled == null) {
- query = getNamedQuery("User.findByUserId");
- query.setParameter("userId", UserId);
- } else {
- query = getNamedQuery("User.findByUserId&Enabled");
- query.setParameter("userId", UserId);
- query.setParameter("enabled", enabled);
- }
- User user = null;
- try {
- user = (User)query.getSingleResult();
- } catch(final NoResultException ex) {
- user = null;
- }
- return user;
- }
- public User getUserByActivationCode(final String activationCode) {
- if (activationCode == null) {
- throw new IllegalArgumentException("Cannot get user with null activationCode");
- }
- final Query query = getNamedQuery("User.findByActivationCode");
- query.setParameter("activationCode", activationCode);
- User user = null;
- try {
- user = (User)query.getSingleResult();
- } catch(final NoResultException ex) {
- user = null;
- }
- return user;
- }
- // Query by enabled status, creation date and with offset/length paging
- public List<User> getUsers(final Boolean enabled, final Date startDate, Date endDate, final int offset, final int length) {
- if (endDate == null) {
- endDate = new Date();
- }
- final List<User> users = new ArrayList<User>();
- Query query = null;
- if (enabled != null) {
- if (startDate != null) {
- query = getNamedQuery("User.findByEnabled&StartDate&EndDateOrderByCreationDateDESC");
- query.setParameter("enabled", enabled);
- query.setParameter("startDate", startDate, TemporalType.DATE);
- query.setParameter("endDate", endDate, TemporalType.DATE);
- } else {
- query = getNamedQuery("User.findByEnabled&EndDateOrderByCreationDateDESC");
- query.setParameter("enabled", enabled);
- query.setParameter("endDate", endDate, TemporalType.DATE);
- }
- } else {
- if (startDate != null) {
- query = getNamedQuery("User.findByStartDate&EndDateOrderByCreationDateDESC");
- query.setParameter("startDate", startDate, TemporalType.DATE);
- query.setParameter("endDate", endDate, TemporalType.DATE);
- } else {
- query = getNamedQuery("User.findByEndDateOrderByCreationDateDESC");
- query.setParameter("endDate", endDate, TemporalType.DATE);
- }
- }
- if (offset != 0) {
- query.setFirstResult(offset);
- }
- if (length != -1) {
- query.setMaxResults(length);
- }
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- users.add((User)obj);
- }
- }
- return users;
- }
- public List<User> getUsersStartingWith(final String startsWith, final Boolean enabled, final int offset, final int length) {
- final List<User> users = new ArrayList<User>();
- Query query = null;
- if (enabled != null) {
- if (startsWith != null) {
- query = getNamedQuery(
- "User.findByUserIdOrEmailAddressPattern&Enabled");
- query.setParameter("enabled", enabled);
- query.setParameter("pattern", startsWith + '%');
- } else {
- query = getNamedQuery("User.findByEnabled");
- query.setParameter("enabled", enabled);
- }
- } else {
- if (startsWith != null) {
- query = getNamedQuery(
- "User.findByUserIdOrEmailAddressPattern");
- query.setParameter("pattern", startsWith + '%');
- } else {
- query = getNamedQuery("User.getAll");
- }
- }
- if (offset != 0) {
- query.setFirstResult(offset);
- }
- if (length != -1) {
- query.setMaxResults(length);
- }
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- users.add((User)obj);
- }
- }
- return users;
- }
- public List<User> getUsersByLetter(final char letter, final int offset, final int length) {
- final List<User> users = new ArrayList<User>();
- final Query query = getNamedQuery("User.findByUserIdPatternOrderByUserId");
- if (offset != 0) {
- query.setFirstResult(offset);
- }
- if (length != -1) {
- query.setMaxResults(length);
- }
- query.setParameter("pattern", letter + "%");
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- users.add((User)obj);
- }
- }
- return users;
- }
- public Map<String, Long> getUserIdLetterMap() {
- final String lc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- final Map<String, Long> results = new TreeMap<String, Long>();
- final Query query = getNamedQuery("User.countWithUserIdPattern");
- for (int i = 0; i < lc.length(); i++) {
- final char currentChar = lc.charAt(i);
- query.setParameter("pattern", currentChar + "%");
- final List row = query.getResultList();
- final Long count = (Long) row.get(0);
- results.put(String.valueOf(currentChar), count);
- }
- return results;
- }
- // Grant and revoke roles because roles imply permissions
- // "is user in role" is provided by the container
- // role is granted to user but not save to database
- public void grantRole(final String roleName, final User user) {
- if (roleName == null) {
- throw new IllegalArgumentException("Cannot grant role with null roleName");
- }
- if (user == null) {
- throw new IllegalArgumentException("Cannot grant role with null user");
- }
- Role role = null;
- try {
- role = getOrCreateRole(roleName);
- final Set<Role> userRoles = user.getRoles();
- userRoles.add(role);
- user.setRoles(userRoles);
- } catch (final Throwable t) {
- throw new IllegalArgumentException(t);
- }
- }
- private Role getOrCreateRole(final String roleName) throws PersistenceException {
- Role role = null;
- try {
- final Query query = getNamedQuery("Role.findByRoleName");
- query.setParameter("name", roleName);
- role = (Role)query.getSingleResult();
- } catch(final NoResultException nre) {
- // create the role in database
- final Role newRole = new Role();
- newRole.setName(roleName);
- roalDao.save(newRole);
- }
- // If role is null, try again (since it _should_ now exist in the DB).
- if (role == null) {
- final Query query = getNamedQuery("Role.findByRoleName");
- query.setParameter("name", roleName);
- role = (Role)query.getSingleResult();
- }
- return role;
- }
- // role is revoked to user but not save to database
- public void revokeRole(final String roleName, final User user) {
- if (roleName == null) {
- throw new IllegalArgumentException("Cannot revoke role with null roleName");
- }
- if (user == null) {
- throw new IllegalArgumentException("Cannot revoke role with null user");
- }
- final Query query = getNamedQuery("Role.findByRoleName");
- query.setParameter("name", roleName);
- try {
- final Role role = (Role)query.getSingleResult();
- final Set<Role> userRoles = user.getRoles();
- userRoles.remove(role);
- user.setRoles(userRoles);
- } catch(final NoResultException ex) {
- // no op
- }
- }
- // and to display the roles and permissions associated with each user
- public List<String> getRoles(final String userId) {
- if (userId == null) {
- throw new IllegalArgumentException("Cannot get roles for null UserId");
- }
- final List<String> roleStrings = new ArrayList<String>();
- final Query query = getNamedQuery("Role.findByUserId");
- query.setParameter("userId", userId);
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- roleStrings.add(((Role)obj).getName());
- }
- }
- return roleStrings;
- }
- // Grant and revoke SF object permissions
- public void grantPermission(final String objectId, final String objectType,
- final User user, final List<String> actions) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "grant");
- if (objectType == null) {
- throw new IllegalArgumentException("Cannot grant Permission with null objectType");
- }
- // first, see if user already has a permission for the specified object
- final Permission existingPerm = getPermission(objectId, user, null);
- log.debug("existingPerm != null: " + (existingPerm != null));
- // permission already exists, so add any actions specified in perm argument
- if (existingPerm != null) {
- existingPerm.addActions(actions);
- permissionDao.save(existingPerm);
- } else {
- // it's a new permission, so store it
- final Permission perm = new Permission(objectId, objectType,
- user, actions);
- }
- }
- public void grantPermissionPending(final String objectId, final String objectType,
- final User user, final List<String> actions) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "grant");
- if (objectType == null) {
- throw new IllegalArgumentException("Cannot grant Permission with null objectType");
- }
- // first, see if user already has a permission for the specified object
- final Permission existingPerm = getPermission(objectId, user, null);
- // permission already exists, so complain
- if (existingPerm != null) {
- throw new IllegalArgumentException("Cannot make existing permission into pending");
- } else {
- // it's a new permission, so store it
- final Permission perm = new Permission(objectId, objectType,
- user, actions);
- perm.setPending(true);
- }
- }
- public void revokePermission(final String objectId, final User user, final List<String> actions) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "revoke");
- // first, see if user already has a permission for the specified object
- final Permission oldPerm = getPermission(objectId, user, null);
- if (oldPerm == null) {
- throw new IllegalArgumentException("Permission not found");
- } else {
- // remove actions specified in perm agument
- oldPerm.removeActions(actions);
- if (oldPerm.isEmpty()) {
- // no actions left in permission so remove it
- user.getPermissions().remove(oldPerm);
- permissionDao.remove(oldPerm.getId());
- } else {
- // otherwise save it
- }
- }
- }
- /**
- * Confirm a permission that is currently in pending state.
- * If user already has a permission record for the specified object, then
- * actions specified in argument perm will be added to that record.
- */
- public void confirmPermission(final String objectId, final User user) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "confirm");
- // first, see if user already has a permission for the specified object
- final Permission existingPerm = getPermission(objectId, user, null);
- if (existingPerm == null) {
- throw new IllegalArgumentException("permission not found");
- } else {
- existingPerm.setPending(false);
- }
- }
- /**
- * Decline a permission that is currently in pending state.
- * Causes permission record to be deleted.
- */
- public void declinePermission(final String objectId, final User user) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "confirm");
- // first, see if user already has a permission for the specified object
- final Permission existingPerm = getPermission(objectId, user, null);
- if (existingPerm == null) {
- throw new IllegalArgumentException("permission not found");
- } else {
- user.getPermissions().remove(existingPerm);
- permissionDao.remove(existingPerm.getId());
- }
- }
- /**
- * Retrieve Permission by objectId, userId and pending.
- * return null when the result is not found
- * @param objectId
- * @param user
- * @param pending
- */
- public Permission getPermission(final String objectId, final User user, final Boolean pending) {
- permissionObjectIdAndUserShouldNotBeNull(objectId, user, "find");
- Query query = null;
- if (pending == null) {
- query = getNamedQuery("Permission.findByUserId&ObjectId");
- query.setParameter("objectId", objectId);
- query.setParameter("userId", user.getId());
- } else {
- query = getNamedQuery("Permission.findByUserId&ObjectId&Pending");
- query.setParameter("objectId", objectId);
- query.setParameter("userId", user.getId());
- query.setParameter("pending", pending);
- }
- Permission perm = null;
- try {
- perm = (Permission)query.getSingleResult();
- } catch (final NoResultException ignored) {
- // ignored
- }
- return perm;
- }
- private void permissionObjectIdAndUserShouldNotBeNull(final String objectId, final User user, final String action) {
- if (objectId == null) {
- throw new IllegalArgumentException("Cannot " + action + " Permission with null objectId");
- }
- if (user == null) {
- throw new IllegalArgumentException("Cannot " + action + " Permission with null user");
- }
- }
- public List<Permission> getPermissions(final User user) {
- if (user == null) {
- throw new IllegalArgumentException("Cannot get Permissions for null user");
- }
- final List<Permission> permissions = new ArrayList<Permission>();
- final Query query = getNamedQuery("Permission.findByUserId");
- query.setParameter("userId", user.getId());
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- permissions.add((Permission)obj);
- }
- }
- return permissions;
- }
- /**
- * Get all pending permissions associated with an object .
- */
- public List<Permission> getPermissionsPending(final User user) {
- if (user == null) {
- throw new IllegalArgumentException("Cannot get pending Permissions for null user");
- }
- final List<Permission> permissions = new ArrayList<Permission>();
- final Query query = getNamedQuery("Permission.findByUserId&Pending");
- query.setParameter("userId", user.getId());
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- permissions.add((Permission)obj);
- }
- }
- return permissions;
- }
- public List<Permission> getPermissions(final String objectId) {
- if (objectId == null) {
- throw new IllegalArgumentException("Cannot get Permissions for null objectId");
- }
- final List<Permission> permissions = new ArrayList<Permission>();
- final Query query = getNamedQuery("Permission.findByObjectId");
- query.setParameter("objectId", objectId);
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- permissions.add((Permission)obj);
- }
- }
- return permissions;
- }
- /**
- * Get all of user's pending permissions.
- */
- public List<Permission> getPermissionsPending(final String objectId) {
- if (objectId == null) {
- throw new IllegalArgumentException("Cannot get pending Permissions for null objectId");
- }
- final List<Permission> permissions = new ArrayList<Permission>();
- final Query query = getNamedQuery("Permission.findByObjectId&Pending");
- query.setParameter("objectId", objectId);
- final List results = query.getResultList();
- if (results != null) {
- for (final Object obj : results) {
- permissions.add((Permission)obj);
- }
- }
- return permissions;
- }
- //----- private methods -----
- public boolean hasRole(final String roleName, final String UserId) {
- if (UserId == null) {
- throw new IllegalArgumentException("Cannot get role for null UserId");
- }
- if (roleName == null) {
- throw new IllegalArgumentException("Cannot get role for null roleName");
- }
- final Query query = getNamedQuery("Role.findByUserIdAndRoleName");
- query.setParameter("userId", UserId);
- query.setParameter("name", roleName);
- final List results = query.getResultList();
- return results == null ? false : !results.isEmpty();
- }
- public User getUserByEmailAddress(String emailAddress) {
- if (emailAddress == null) {
- throw new IllegalArgumentException("Cannot get user with null email");
- }
- final Query query = getNamedQuery("User.findByEmail");
- query.setParameter("emailAddress", emailAddress);
- User user = null;
- try {
- user = (User)query.getSingleResult();
- } catch(final NoResultException ex) {
- user = null;
- }
- return user;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement