Advertisement
Guest User

Untitled

a guest
Jun 11th, 2017
495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.84 KB | None | 0 0
  1. package com.dagitab.opensocial.service.impl;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Date;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.TreeMap;
  9.  
  10. import javax.jws.WebService;
  11. import javax.persistence.NoResultException;
  12. import javax.persistence.PersistenceException;
  13. import javax.persistence.Query;
  14. import javax.persistence.TemporalType;
  15.  
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.beans.factory.annotation.Qualifier;
  18. import org.springframework.dao.DataIntegrityViolationException;
  19. import org.springframework.orm.jpa.JpaSystemException;
  20. import org.springframework.security.providers.encoding.PasswordEncoder;
  21. import org.springframework.security.userdetails.UsernameNotFoundException;
  22. import org.springframework.stereotype.Service;
  23.  
  24. import com.dagitab.opensocial.dao.GenericDao;
  25. import com.dagitab.opensocial.dao.RoleDao;
  26. import com.dagitab.opensocial.dao.UserDao;
  27. import com.dagitab.opensocial.model.Permission;
  28. import com.dagitab.opensocial.model.Role;
  29. import com.dagitab.opensocial.model.User;
  30. import com.dagitab.opensocial.service.UserExistsException;
  31. import com.dagitab.opensocial.service.UserManager;
  32. import com.dagitab.opensocial.service.UserService;
  33.  
  34.  
  35. /**
  36. * Implementation of UserManager interface.
  37. *
  38. * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
  39. */
  40. @Service("userManager")
  41. @WebService(serviceName = "UserService", endpointInterface = "com.dagitab.opensocial.service.UserService")
  42. public class UserManagerImpl extends GenericManagerImpl<User, Long> implements UserManager, UserService {
  43. private PasswordEncoder passwordEncoder;
  44. private UserDao userDao;
  45. private RoleDao roalDao;
  46. private GenericDao<Permission, String> permissionDao;
  47.  
  48. @Autowired
  49. public void setPasswordEncoder(final PasswordEncoder passwordEncoder) {
  50. this.passwordEncoder = passwordEncoder;
  51. }
  52.  
  53. @Autowired
  54. public void setUserDao(final UserDao userDao) {
  55. this.dao = userDao;
  56. this.userDao = userDao;
  57. }
  58.  
  59. @Autowired
  60. public void setRoalDao(final RoleDao roalDao) {
  61. this.roalDao = roalDao;
  62. }
  63.  
  64. @Autowired
  65. public void setPermissionDao(
  66. @Qualifier("permissionDao") final
  67. GenericDao<Permission, String> permissionDao) {
  68. this.permissionDao = permissionDao;
  69. }
  70.  
  71.  
  72.  
  73. /**
  74. * {@inheritDoc}
  75. */
  76. public User getUser(final String userId) {
  77. return userDao.get(new Long(userId));
  78. }
  79.  
  80. /**
  81. * {@inheritDoc}
  82. */
  83. public List<User> getUsers() {
  84. return userDao.getAllDistinct();
  85. }
  86.  
  87. /**
  88. * {@inheritDoc}
  89. */
  90. public User saveUser(final User user) throws UserExistsException {
  91.  
  92. if (user.getVersion() == null) {
  93. // if new user, lowercase userId
  94. user.setUsername(user.getUsername().toLowerCase());
  95. }
  96.  
  97. // Get and prepare password management-related artifacts
  98. boolean passwordChanged = false;
  99. if (passwordEncoder != null) {
  100. // Check whether we have to encrypt (or re-encrypt) the password
  101. if (user.getVersion() == null) {
  102. // New user, always encrypt
  103. passwordChanged = true;
  104. } else {
  105. // Existing user, check password in DB
  106. final String currentPassword = userDao.getUserPassword(user.getUsername());
  107. if (currentPassword == null) {
  108. passwordChanged = true;
  109. } else {
  110. if (!currentPassword.equals(user.getPassword())) {
  111. passwordChanged = true;
  112. }
  113. }
  114. }
  115.  
  116. // If password was changed (or new user), encrypt it
  117. if (passwordChanged) {
  118. user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
  119. }
  120. } else {
  121. log.warn("PasswordEncoder not set, skipping password encryption...");
  122. }
  123.  
  124. user.setUpdateDate(new java.util.Date());
  125. user.setAccessDate(new java.util.Date());
  126. user.setUserId(user.getUsername());
  127.  
  128. try {
  129. return userDao.saveUser(user);
  130. } catch (final DataIntegrityViolationException e) {
  131. //e.printStackTrace();
  132. log.warn(e.getMessage());
  133. throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
  134. } catch (final JpaSystemException e) { // needed for JPA
  135. //e.printStackTrace();
  136. log.warn(e.getMessage());
  137. throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
  138. }
  139. }
  140.  
  141. /**
  142. * {@inheritDoc}
  143. */
  144. public void removeUser(final String userId) {
  145. log.debug("removing user: " + userId);
  146. userDao.remove(new Long(userId));
  147. }
  148.  
  149. /**
  150. * {@inheritDoc}
  151. *
  152. * @param username the login name of the human
  153. * @return User the populated user object
  154. * @throws UsernameNotFoundException thrown when username not found
  155. */
  156. public User getUserByUsername(final String username) throws UsernameNotFoundException {
  157. return (User) userDao.loadUserByUsername(username);
  158. }
  159.  
  160. // Register users, update extended user profile data, etc.
  161. public void registerUser(final User user) {
  162. if (user == null) {
  163. throw new IllegalArgumentException("Cannot register null user");
  164. }
  165. try {
  166. saveUser(user);
  167. }
  168. catch (final UserExistsException e) {
  169. throw new IllegalArgumentException("User already exist", e);
  170. }
  171. }
  172.  
  173. public void removeUser(final User user) {
  174. if (user == null) {
  175. throw new IllegalArgumentException("Cannot remove null user");
  176. }
  177. if (user.isNew()) {
  178. throw new IllegalArgumentException("Cannot remove unpersisted user");
  179. }
  180. removeUser(user.getId() + "");
  181. }
  182.  
  183. public long getUserCount() {
  184. final Query query = getNamedQuery("User.count");
  185. final Long count = (Long)query.getSingleResult();
  186. return count;
  187. }
  188.  
  189. public User getUserByUserId(final String UserId) {
  190. return getUserByUserId(UserId, null);
  191. }
  192.  
  193. public User getUserByUserId(final String UserId, final Boolean enabled) {
  194. if (UserId == null) {
  195. throw new IllegalArgumentException("Cannot get user with null UserId");
  196. }
  197.  
  198. Query query = null;
  199. if (enabled == null) {
  200. query = getNamedQuery("User.findByUserId");
  201. query.setParameter("userId", UserId);
  202. } else {
  203. query = getNamedQuery("User.findByUserId&Enabled");
  204. query.setParameter("userId", UserId);
  205. query.setParameter("enabled", enabled);
  206. }
  207. User user = null;
  208. try {
  209. user = (User)query.getSingleResult();
  210. } catch(final NoResultException ex) {
  211. user = null;
  212. }
  213. return user;
  214. }
  215.  
  216. public User getUserByActivationCode(final String activationCode) {
  217. if (activationCode == null) {
  218. throw new IllegalArgumentException("Cannot get user with null activationCode");
  219. }
  220. final Query query = getNamedQuery("User.findByActivationCode");
  221. query.setParameter("activationCode", activationCode);
  222. User user = null;
  223. try {
  224. user = (User)query.getSingleResult();
  225. } catch(final NoResultException ex) {
  226. user = null;
  227. }
  228. return user;
  229. }
  230.  
  231. // Query by enabled status, creation date and with offset/length paging
  232. public List<User> getUsers(final Boolean enabled, final Date startDate, Date endDate, final int offset, final int length) {
  233. if (endDate == null) {
  234. endDate = new Date();
  235. }
  236.  
  237. final List<User> users = new ArrayList<User>();
  238. Query query = null;
  239. if (enabled != null) {
  240. if (startDate != null) {
  241. query = getNamedQuery("User.findByEnabled&StartDate&EndDateOrderByCreationDateDESC");
  242. query.setParameter("enabled", enabled);
  243. query.setParameter("startDate", startDate, TemporalType.DATE);
  244. query.setParameter("endDate", endDate, TemporalType.DATE);
  245. } else {
  246. query = getNamedQuery("User.findByEnabled&EndDateOrderByCreationDateDESC");
  247. query.setParameter("enabled", enabled);
  248. query.setParameter("endDate", endDate, TemporalType.DATE);
  249. }
  250. } else {
  251. if (startDate != null) {
  252. query = getNamedQuery("User.findByStartDate&EndDateOrderByCreationDateDESC");
  253. query.setParameter("startDate", startDate, TemporalType.DATE);
  254. query.setParameter("endDate", endDate, TemporalType.DATE);
  255. } else {
  256. query = getNamedQuery("User.findByEndDateOrderByCreationDateDESC");
  257. query.setParameter("endDate", endDate, TemporalType.DATE);
  258. }
  259. }
  260. if (offset != 0) {
  261. query.setFirstResult(offset);
  262. }
  263. if (length != -1) {
  264. query.setMaxResults(length);
  265. }
  266. final List results = query.getResultList();
  267. if (results != null) {
  268. for (final Object obj : results) {
  269. users.add((User)obj);
  270. }
  271. }
  272. return users;
  273. }
  274.  
  275. public List<User> getUsersStartingWith(final String startsWith, final Boolean enabled, final int offset, final int length) {
  276. final List<User> users = new ArrayList<User>();
  277. Query query = null;
  278. if (enabled != null) {
  279. if (startsWith != null) {
  280. query = getNamedQuery(
  281. "User.findByUserIdOrEmailAddressPattern&Enabled");
  282. query.setParameter("enabled", enabled);
  283. query.setParameter("pattern", startsWith + '%');
  284. } else {
  285. query = getNamedQuery("User.findByEnabled");
  286. query.setParameter("enabled", enabled);
  287. }
  288. } else {
  289. if (startsWith != null) {
  290. query = getNamedQuery(
  291. "User.findByUserIdOrEmailAddressPattern");
  292. query.setParameter("pattern", startsWith + '%');
  293. } else {
  294. query = getNamedQuery("User.getAll");
  295. }
  296. }
  297.  
  298. if (offset != 0) {
  299. query.setFirstResult(offset);
  300. }
  301. if (length != -1) {
  302. query.setMaxResults(length);
  303. }
  304. final List results = query.getResultList();
  305. if (results != null) {
  306. for (final Object obj : results) {
  307. users.add((User)obj);
  308. }
  309. }
  310. return users;
  311. }
  312.  
  313. public List<User> getUsersByLetter(final char letter, final int offset, final int length) {
  314. final List<User> users = new ArrayList<User>();
  315. final Query query = getNamedQuery("User.findByUserIdPatternOrderByUserId");
  316. if (offset != 0) {
  317. query.setFirstResult(offset);
  318. }
  319. if (length != -1) {
  320. query.setMaxResults(length);
  321. }
  322. query.setParameter("pattern", letter + "%");
  323. final List results = query.getResultList();
  324. if (results != null) {
  325. for (final Object obj : results) {
  326. users.add((User)obj);
  327. }
  328. }
  329. return users;
  330. }
  331.  
  332. public Map<String, Long> getUserIdLetterMap() {
  333. final String lc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  334. final Map<String, Long> results = new TreeMap<String, Long>();
  335. final Query query = getNamedQuery("User.countWithUserIdPattern");
  336. for (int i = 0; i < lc.length(); i++) {
  337. final char currentChar = lc.charAt(i);
  338. query.setParameter("pattern", currentChar + "%");
  339. final List row = query.getResultList();
  340. final Long count = (Long) row.get(0);
  341. results.put(String.valueOf(currentChar), count);
  342. }
  343. return results;
  344. }
  345.  
  346. // Grant and revoke roles because roles imply permissions
  347. // "is user in role" is provided by the container
  348. // role is granted to user but not save to database
  349. public void grantRole(final String roleName, final User user) {
  350. if (roleName == null) {
  351. throw new IllegalArgumentException("Cannot grant role with null roleName");
  352. }
  353. if (user == null) {
  354. throw new IllegalArgumentException("Cannot grant role with null user");
  355. }
  356.  
  357. Role role = null;
  358. try {
  359. role = getOrCreateRole(roleName);
  360. final Set<Role> userRoles = user.getRoles();
  361. userRoles.add(role);
  362. user.setRoles(userRoles);
  363. } catch (final Throwable t) {
  364. throw new IllegalArgumentException(t);
  365. }
  366. }
  367.  
  368. private Role getOrCreateRole(final String roleName) throws PersistenceException {
  369. Role role = null;
  370. try {
  371. final Query query = getNamedQuery("Role.findByRoleName");
  372. query.setParameter("name", roleName);
  373. role = (Role)query.getSingleResult();
  374. } catch(final NoResultException nre) {
  375. // create the role in database
  376. final Role newRole = new Role();
  377. newRole.setName(roleName);
  378. roalDao.save(newRole);
  379. }
  380.  
  381. // If role is null, try again (since it _should_ now exist in the DB).
  382. if (role == null) {
  383. final Query query = getNamedQuery("Role.findByRoleName");
  384. query.setParameter("name", roleName);
  385. role = (Role)query.getSingleResult();
  386. }
  387.  
  388. return role;
  389. }
  390.  
  391. // role is revoked to user but not save to database
  392. public void revokeRole(final String roleName, final User user) {
  393. if (roleName == null) {
  394. throw new IllegalArgumentException("Cannot revoke role with null roleName");
  395. }
  396. if (user == null) {
  397. throw new IllegalArgumentException("Cannot revoke role with null user");
  398. }
  399.  
  400. final Query query = getNamedQuery("Role.findByRoleName");
  401. query.setParameter("name", roleName);
  402.  
  403. try {
  404. final Role role = (Role)query.getSingleResult();
  405. final Set<Role> userRoles = user.getRoles();
  406. userRoles.remove(role);
  407. user.setRoles(userRoles);
  408. } catch(final NoResultException ex) {
  409. // no op
  410. }
  411. }
  412.  
  413. // and to display the roles and permissions associated with each user
  414. public List<String> getRoles(final String userId) {
  415. if (userId == null) {
  416. throw new IllegalArgumentException("Cannot get roles for null UserId");
  417. }
  418.  
  419. final List<String> roleStrings = new ArrayList<String>();
  420. final Query query = getNamedQuery("Role.findByUserId");
  421. query.setParameter("userId", userId);
  422.  
  423. final List results = query.getResultList();
  424. if (results != null) {
  425. for (final Object obj : results) {
  426. roleStrings.add(((Role)obj).getName());
  427. }
  428. }
  429. return roleStrings;
  430. }
  431.  
  432. // Grant and revoke SF object permissions
  433. public void grantPermission(final String objectId, final String objectType,
  434. final User user, final List<String> actions) {
  435. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "grant");
  436. if (objectType == null) {
  437. throw new IllegalArgumentException("Cannot grant Permission with null objectType");
  438. }
  439.  
  440. // first, see if user already has a permission for the specified object
  441. final Permission existingPerm = getPermission(objectId, user, null);
  442. log.debug("existingPerm != null: " + (existingPerm != null));
  443. // permission already exists, so add any actions specified in perm argument
  444. if (existingPerm != null) {
  445. existingPerm.addActions(actions);
  446. permissionDao.save(existingPerm);
  447. } else {
  448. // it's a new permission, so store it
  449. final Permission perm = new Permission(objectId, objectType,
  450. user, actions);
  451. }
  452. }
  453.  
  454. public void grantPermissionPending(final String objectId, final String objectType,
  455. final User user, final List<String> actions) {
  456. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "grant");
  457. if (objectType == null) {
  458. throw new IllegalArgumentException("Cannot grant Permission with null objectType");
  459. }
  460.  
  461. // first, see if user already has a permission for the specified object
  462. final Permission existingPerm = getPermission(objectId, user, null);
  463.  
  464. // permission already exists, so complain
  465. if (existingPerm != null) {
  466. throw new IllegalArgumentException("Cannot make existing permission into pending");
  467. } else {
  468. // it's a new permission, so store it
  469. final Permission perm = new Permission(objectId, objectType,
  470. user, actions);
  471. perm.setPending(true);
  472. }
  473. }
  474.  
  475. public void revokePermission(final String objectId, final User user, final List<String> actions) {
  476. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "revoke");
  477.  
  478. // first, see if user already has a permission for the specified object
  479. final Permission oldPerm = getPermission(objectId, user, null);
  480.  
  481. if (oldPerm == null) {
  482. throw new IllegalArgumentException("Permission not found");
  483. } else {
  484. // remove actions specified in perm agument
  485. oldPerm.removeActions(actions);
  486. if (oldPerm.isEmpty()) {
  487. // no actions left in permission so remove it
  488. user.getPermissions().remove(oldPerm);
  489. permissionDao.remove(oldPerm.getId());
  490. } else {
  491. // otherwise save it
  492. }
  493. }
  494. }
  495.  
  496.  
  497. /**
  498. * Confirm a permission that is currently in pending state.
  499. * If user already has a permission record for the specified object, then
  500. * actions specified in argument perm will be added to that record.
  501. */
  502. public void confirmPermission(final String objectId, final User user) {
  503. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "confirm");
  504.  
  505. // first, see if user already has a permission for the specified object
  506. final Permission existingPerm = getPermission(objectId, user, null);
  507.  
  508. if (existingPerm == null) {
  509. throw new IllegalArgumentException("permission not found");
  510. } else {
  511. existingPerm.setPending(false);
  512. }
  513. }
  514.  
  515. /**
  516. * Decline a permission that is currently in pending state.
  517. * Causes permission record to be deleted.
  518. */
  519. public void declinePermission(final String objectId, final User user) {
  520. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "confirm");
  521.  
  522. // first, see if user already has a permission for the specified object
  523. final Permission existingPerm = getPermission(objectId, user, null);
  524.  
  525. if (existingPerm == null) {
  526. throw new IllegalArgumentException("permission not found");
  527. } else {
  528. user.getPermissions().remove(existingPerm);
  529. permissionDao.remove(existingPerm.getId());
  530. }
  531. }
  532.  
  533. /**
  534. * Retrieve Permission by objectId, userId and pending.
  535. * return null when the result is not found
  536. * @param objectId
  537. * @param user
  538. * @param pending
  539. */
  540. public Permission getPermission(final String objectId, final User user, final Boolean pending) {
  541. permissionObjectIdAndUserShouldNotBeNull(objectId, user, "find");
  542.  
  543. Query query = null;
  544. if (pending == null) {
  545. query = getNamedQuery("Permission.findByUserId&ObjectId");
  546. query.setParameter("objectId", objectId);
  547. query.setParameter("userId", user.getId());
  548. } else {
  549. query = getNamedQuery("Permission.findByUserId&ObjectId&Pending");
  550. query.setParameter("objectId", objectId);
  551. query.setParameter("userId", user.getId());
  552. query.setParameter("pending", pending);
  553. }
  554. Permission perm = null;
  555. try {
  556. perm = (Permission)query.getSingleResult();
  557. } catch (final NoResultException ignored) {
  558. // ignored
  559. }
  560. return perm;
  561. }
  562.  
  563. private void permissionObjectIdAndUserShouldNotBeNull(final String objectId, final User user, final String action) {
  564. if (objectId == null) {
  565. throw new IllegalArgumentException("Cannot " + action + " Permission with null objectId");
  566. }
  567. if (user == null) {
  568. throw new IllegalArgumentException("Cannot " + action + " Permission with null user");
  569. }
  570. }
  571.  
  572. public List<Permission> getPermissions(final User user) {
  573. if (user == null) {
  574. throw new IllegalArgumentException("Cannot get Permissions for null user");
  575. }
  576.  
  577. final List<Permission> permissions = new ArrayList<Permission>();
  578. final Query query = getNamedQuery("Permission.findByUserId");
  579. query.setParameter("userId", user.getId());
  580. final List results = query.getResultList();
  581. if (results != null) {
  582. for (final Object obj : results) {
  583. permissions.add((Permission)obj);
  584. }
  585. }
  586. return permissions;
  587. }
  588.  
  589. /**
  590. * Get all pending permissions associated with an object .
  591. */
  592. public List<Permission> getPermissionsPending(final User user) {
  593. if (user == null) {
  594. throw new IllegalArgumentException("Cannot get pending Permissions for null user");
  595. }
  596.  
  597. final List<Permission> permissions = new ArrayList<Permission>();
  598. final Query query = getNamedQuery("Permission.findByUserId&Pending");
  599. query.setParameter("userId", user.getId());
  600. final List results = query.getResultList();
  601. if (results != null) {
  602. for (final Object obj : results) {
  603. permissions.add((Permission)obj);
  604. }
  605. }
  606. return permissions;
  607. }
  608.  
  609. public List<Permission> getPermissions(final String objectId) {
  610. if (objectId == null) {
  611. throw new IllegalArgumentException("Cannot get Permissions for null objectId");
  612. }
  613.  
  614. final List<Permission> permissions = new ArrayList<Permission>();
  615. final Query query = getNamedQuery("Permission.findByObjectId");
  616. query.setParameter("objectId", objectId);
  617. final List results = query.getResultList();
  618. if (results != null) {
  619. for (final Object obj : results) {
  620. permissions.add((Permission)obj);
  621. }
  622. }
  623. return permissions;
  624. }
  625.  
  626. /**
  627. * Get all of user's pending permissions.
  628. */
  629. public List<Permission> getPermissionsPending(final String objectId) {
  630. if (objectId == null) {
  631. throw new IllegalArgumentException("Cannot get pending Permissions for null objectId");
  632. }
  633.  
  634. final List<Permission> permissions = new ArrayList<Permission>();
  635. final Query query = getNamedQuery("Permission.findByObjectId&Pending");
  636. query.setParameter("objectId", objectId);
  637. final List results = query.getResultList();
  638. if (results != null) {
  639. for (final Object obj : results) {
  640. permissions.add((Permission)obj);
  641. }
  642. }
  643. return permissions;
  644. }
  645.  
  646. //----- private methods -----
  647.  
  648. public boolean hasRole(final String roleName, final String UserId) {
  649. if (UserId == null) {
  650. throw new IllegalArgumentException("Cannot get role for null UserId");
  651. }
  652. if (roleName == null) {
  653. throw new IllegalArgumentException("Cannot get role for null roleName");
  654. }
  655.  
  656. final Query query = getNamedQuery("Role.findByUserIdAndRoleName");
  657. query.setParameter("userId", UserId);
  658. query.setParameter("name", roleName);
  659.  
  660. final List results = query.getResultList();
  661. return results == null ? false : !results.isEmpty();
  662. }
  663.  
  664. public User getUserByEmailAddress(String emailAddress) {
  665. if (emailAddress == null) {
  666. throw new IllegalArgumentException("Cannot get user with null email");
  667. }
  668. final Query query = getNamedQuery("User.findByEmail");
  669. query.setParameter("emailAddress", emailAddress);
  670. User user = null;
  671. try {
  672. user = (User)query.getSingleResult();
  673. } catch(final NoResultException ex) {
  674. user = null;
  675. }
  676. return user;
  677. }
  678.  
  679. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement