12,83 → 12,90 |
/** |
* |
* Service that do some business logic before access DAO layer. |
* |
* |
*/ |
public class UserServiceImpl implements UserService { |
|
private UserDAO userDAO; |
|
public UserServiceImpl(UserDAO userDAO) { |
private final UserDAO userDAO; |
|
public UserServiceImpl(final UserDAO userDAO) { |
this.userDAO = userDAO; |
} |
|
|
@Override |
public User findByUsername(String username) { |
if(username == null) throw new IllegalArgumentException("Username cannot be null"); |
|
public User findByUsername(final String username) { |
if (username == null) { |
throw new IllegalArgumentException("Username cannot be null"); |
} |
|
return userDAO.findByUsername(username); |
} |
|
public User load(int id) { |
if(id < 1) return null; |
|
@Override |
public User load(final int id) { |
if (id < 1) { |
return null; |
} |
|
return userDAO.load(id); |
} |
|
@Override |
public void save(User u) { |
public void save(final User u) { |
|
if(u.getUsername() == null || u.getUsername().isEmpty()) |
if (u.getUsername() == null || u.getUsername().isEmpty()) { |
throw new IllegalStateException("Username cannot be null"); |
|
if(u.getId() > 0) { |
} |
|
if (u.getId() > 0) { |
userDAO.update(u); |
|
} else { |
|
} |
else { |
userDAO.insert(u); |
|
|
// Send email to any new user with password |
sendWelcomeMail(u); |
} |
|
|
} |
|
private void sendWelcomeMail(User u) { |
|
Letter welcome = new TextLetter("welcome.txt"); |
private void sendWelcomeMail(final User u) { |
|
final Letter welcome = new TextLetter("welcome.txt"); |
welcome.setAttribute("username", u.getUsername()); |
welcome.setAttribute("password", u.getPassword()); |
|
|
try { |
|
String subject = welcome.getSubject(u.getLocale()); |
String body = welcome.getText(u.getLocale()); |
|
|
final String subject = welcome.getSubject(u.getLocale()); |
final String body = welcome.getText(u.getLocale()); |
|
SimpleEmail.sendLater(u.getUsername(), u.getEmail(), subject, body); |
|
} catch(Exception e) { |
|
|
} |
catch (final Exception e) { |
|
System.err.println("Error sending email to: " + u.getEmail()); |
|
|
e.printStackTrace(); |
} |
|
|
} |
|
|
@Override |
public User login(User user) throws LoginException { |
|
User userFinded = userDAO.findByUsername(user.getUsername()); |
|
if(userFinded == null) { |
public User login(final User user) throws LoginException { |
|
final User userFinded = userDAO.findByUsername(user.getUsername()); |
|
if (userFinded == null) { |
throw new LoginException(Type.USERNAME_NOTFOUND); |
} |
|
|
if (!userFinded.getPassword().equals(user.getPassword())) { |
throw new LoginException(Type.WRONG_PASSWORD); |
} |
|
|
return userFinded; |
} |
} |