PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/dumbhippo/branches/cluster/server/src/com/dumbhippo/server/impl/AccountSystemBean.java

https://gitlab.com/manoj-makkuboy/magnetism
Java | 191 lines | 151 code | 30 blank | 10 comment | 8 complexity | c972465fa5633d647490beb5861caade MD5 | raw file
  1. package com.dumbhippo.server.impl;
  2. import java.util.Date;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.concurrent.Callable;
  9. import javax.ejb.EJB;
  10. import javax.ejb.Stateless;
  11. import javax.persistence.EntityManager;
  12. import javax.persistence.NoResultException;
  13. import javax.persistence.PersistenceContext;
  14. import javax.persistence.Query;
  15. import org.jboss.annotation.IgnoreDependency;
  16. import org.slf4j.Logger;
  17. import com.dumbhippo.ExceptionUtils;
  18. import com.dumbhippo.GlobalSetup;
  19. import com.dumbhippo.TypeUtils;
  20. import com.dumbhippo.identity20.Guid;
  21. import com.dumbhippo.persistence.Account;
  22. import com.dumbhippo.persistence.Client;
  23. import com.dumbhippo.persistence.EmailResource;
  24. import com.dumbhippo.persistence.Resource;
  25. import com.dumbhippo.persistence.User;
  26. import com.dumbhippo.persistence.ValidationException;
  27. import com.dumbhippo.server.AccountSystem;
  28. import com.dumbhippo.server.Character;
  29. import com.dumbhippo.server.Enabled;
  30. import com.dumbhippo.server.IdentitySpider;
  31. import com.dumbhippo.server.NotFoundException;
  32. import com.dumbhippo.server.Stacker;
  33. import com.dumbhippo.server.TransactionRunner;
  34. import com.dumbhippo.server.UnauthorizedException;
  35. import com.dumbhippo.server.util.EJBUtil;
  36. @Stateless
  37. public class AccountSystemBean implements AccountSystem {
  38. static private final Logger logger = GlobalSetup.getLogger(AccountSystem.class);
  39. @PersistenceContext(unitName = "dumbhippo")
  40. private EntityManager em;
  41. @EJB
  42. private IdentitySpider spider;
  43. @EJB
  44. private TransactionRunner runner;
  45. @EJB
  46. @IgnoreDependency
  47. private Stacker stacker;
  48. public Account createAccountFromResource(Resource res) {
  49. User user = new User();
  50. user.setNickname(res.getDerivedNickname());
  51. Account account = new Account(user);
  52. em.persist(user);
  53. em.persist(account);
  54. // Important to add the account first here so other code
  55. // can just assume all users have accounts. Specifically
  56. // the GroupMember canonicalization code assumes this for example.
  57. spider.addVerifiedOwnershipClaim(user, account);
  58. spider.addVerifiedOwnershipClaim(user, res);
  59. stacker.onUserCreated(user.getGuid());
  60. return account;
  61. }
  62. public Account createAccountFromEmail(String email) throws ValidationException {
  63. Resource res = spider.getEmail(email);
  64. return createAccountFromResource(res);
  65. }
  66. public Client authorizeNewClient(Account acct, String name) {
  67. Client c = new Client(acct, name);
  68. em.persist(c);
  69. acct.authorizeNewClient(c);
  70. return c;
  71. }
  72. public Account checkClientCookie(Guid guid, String authKey) throws NotFoundException, UnauthorizedException {
  73. Account account = lookupAccountByOwnerId(guid);
  74. if (!account.checkClientCookie(authKey))
  75. throw new UnauthorizedException("Invalid authorization cookie");
  76. return account;
  77. }
  78. public Client getExistingClient(Guid userId, long clientId) throws NotFoundException {
  79. Client client = em.find(Client.class, clientId);
  80. if (client == null)
  81. throw new NotFoundException("Client not found");
  82. if (!client.getAccount().getOwner().getGuid().equals(userId))
  83. throw new RuntimeException("Client doesn't match user");
  84. return client;
  85. }
  86. public Account lookupAccountByUser(User user) {
  87. if (!em.contains(user)) {
  88. try {
  89. user = EJBUtil.lookupGuid(em, User.class, user.getGuid());
  90. } catch (NotFoundException e) {
  91. throw new RuntimeException("Failed to look up user", e);
  92. }
  93. }
  94. return user.getAccount();
  95. }
  96. public Account lookupAccountByOwnerId(Guid ownerId) throws NotFoundException {
  97. User user = EJBUtil.lookupGuid(em, User.class, ownerId);
  98. return user.getAccount();
  99. }
  100. public long getNumberOfActiveAccounts() {
  101. try {
  102. Number num = (Number) em.createQuery("SELECT COUNT(a) FROM Account a").getSingleResult();
  103. return num.longValue();
  104. } catch (NoResultException e) {
  105. throw new RuntimeException("Failed to count number of accounts", e);
  106. }
  107. }
  108. public Set<Account> getActiveAccounts() {
  109. Query q = em.createQuery("SELECT a FROM Account a WHERE a.wasSentShareLinkTutorial = TRUE");
  110. Set<Account> accounts = new HashSet<Account>();
  111. List list = q.getResultList();
  112. for (Object o : list) {
  113. accounts.add((Account) o);
  114. }
  115. return accounts;
  116. }
  117. public List<Account> getRecentlyActiveAccounts() {
  118. Query q = em.createQuery("SELECT a FROM Account a WHERE a.lastLoginDate >= :weekAgo");
  119. q.setParameter("weekAgo", new Date(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000)));
  120. return TypeUtils.castList(Account.class, q.getResultList());
  121. }
  122. public User getCharacter(final Character whichOne) {
  123. try {
  124. return runner.runTaskThrowingConstraintViolation(new Callable<User>() {
  125. public User call() {
  126. EmailResource email;
  127. try {
  128. email = spider.getEmail(whichOne.getEmail());
  129. } catch (ValidationException e) {
  130. throw new RuntimeException("Character has invalid email address!");
  131. }
  132. User user = spider.getUser(email);
  133. if (user == null) {
  134. // don't add any special handling in here - it should be OK if
  135. // someone just creates the character accounts manually without running
  136. // this code. We don't want to start doing "if (character) ; else ;" all
  137. // over the place.
  138. logger.info("Creating special user " + whichOne);
  139. Account account = createAccountFromResource(email);
  140. user = account.getOwner();
  141. user.setNickname(whichOne.getDefaultNickname());
  142. }
  143. return user;
  144. }
  145. });
  146. } catch (Exception e) {
  147. ExceptionUtils.throwAsRuntimeException(e);
  148. return null; // not reached
  149. }
  150. }
  151. public Map<String, String> getPrefs(Account account) {
  152. Map<String,String> prefs = new HashMap<String, String>();
  153. // account.isMusicSharingEnabled() could return null, so we should use getMusicSharingEnabled()
  154. // method in identitySpider to get the right default
  155. prefs.put("musicSharingEnabled", Boolean.toString(spider.getMusicSharingEnabled(account.getOwner(),
  156. Enabled.AND_ACCOUNT_IS_ACTIVE)));
  157. // not strictly a "pref" but this is a convenient place to send this to the client
  158. prefs.put("musicSharingPrimed", Boolean.toString(account.isMusicSharingPrimed()));
  159. return prefs;
  160. }
  161. }