1 package ejava.examples.asyncmarket.ejb;
2
3 import java.util.List;
4
5 import javax.annotation.PostConstruct;
6 import javax.ejb.Stateless;
7 import javax.ejb.TransactionAttribute;
8 import javax.ejb.TransactionAttributeType;
9 import javax.inject.Inject;
10
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 import ejava.examples.asyncmarket.bo.Person;
15 import ejava.examples.asyncmarket.dao.PersonDAO;
16
17 @Stateless
18 @TransactionAttribute(TransactionAttributeType.REQUIRED)
19 public class UserMgmtEJB implements UserMgmtRemote, UserMgmtLocal {
20 private static final Logger logger = LoggerFactory.getLogger(UserMgmtEJB.class);
21
22 @Inject
23 private PersonDAO userDAO;
24 @Inject
25 private DtoMapper dtoMapper;
26
27 @PostConstruct
28 public void init() {
29 logger.info("*** UserMgmtEJB init() ***");
30 }
31
32 public long createUser(String userId, String name) {
33 try {
34 Person user = new Person();
35 user.setName(name);
36 user.setUserId(userId);
37 return userDAO.createPerson(user).getId();
38 }
39 catch (Exception ex) {
40 logger.error("error creating user", ex);
41 throw new InternalErrorException("error creating user:%s", ex);
42 }
43 }
44
45 public List<Person> getUsers(int index, int count) {
46 try {
47 return dtoMapper.toDTOPeople(userDAO.getPeople(index, count));
48 }
49 catch (Exception ex) {
50 logger.error("error getting users", ex);
51 throw new InternalErrorException("error getting users: %s", ex);
52 }
53 }
54
55 public Person getUser(long id) throws ResourceNotFoundException {
56 Person user = userDAO.getPerson(id);
57 if (user==null) {
58 throw new ResourceNotFoundException("userId[%d] not found", id);
59 }
60
61 try {
62 return dtoMapper.toDTO(user);
63 }
64 catch (Exception ex) {
65 logger.error("error getting user", ex);
66 throw new InternalErrorException("error getting user: %s", ex);
67 }
68 }
69
70 public Person getUserByUserId(String userId) throws ResourceNotFoundException {
71 Person user = userDAO.getPersonByUserId(userId);
72 if (user==null) {
73 throw new ResourceNotFoundException("userId[%s] not found", userId);
74 }
75 logger.debug("getUserByUserId({})={}", userId, user);
76
77 try {
78 return dtoMapper.toDTO(user);
79 }
80 catch (Exception ex) {
81 logger.error("error getting user by userId", ex);
82 throw new InternalErrorException("error getting user by userId: %s", ex);
83 }
84 }
85
86 public void removeUser(String userId) throws ResourceNotFoundException {
87 Person user = userDAO.getPersonByUserId(userId);
88 if (user==null) {
89 throw new ResourceNotFoundException("userId[%s] not found", userId);
90 }
91
92 try {
93 userDAO.removePerson(user);
94 }
95 catch (Exception ex) {
96 logger.error("error getting user by userId", ex);
97 throw new InternalErrorException("error getting user by userId: %s", ex);
98 }
99 }
100 }