package se.gu.fire.data;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import se.gu.fire.core.FireUser;
import se.gu.fire.core.UserRole;
import se.gu.fire.data.inter.IUserManager;
import se.gu.fire.util.FireLogger;
/**
* Persistence manager for FireUser type objects
*/
@Stateless
@LocalBean
public class UserManager extends AbstractDAO<FireUser, Long> implements IUserManager {
public UserManager() {
super(FireUser.class);
FireLogger.logInfo("Created new UserManager");
}
@Override
public boolean isAdmin(FireUser user) {
return user.getRole() == UserRole.ADMIN;
}
@Override
public boolean isAdmin(Long userId) {
FireUser user = read(userId);
if (user == null) {
FireLogger.logInfo("No user found {0}", userId);
return false;
}
return user.getRole() == UserRole.ADMIN;
}
@Override
public boolean isGrader(FireUser user) {
return user.getRole() == UserRole.GRADER;
}
@Override
public boolean isGrader(Long userId) {
FireUser user = read(userId);
if (user == null) {
FireLogger.logInfo("No user found {0}", userId);
return false;
}
return user.getRole() == UserRole.GRADER;
}
@Override
public FireUser findUser(String email) {
String query = "select u from FireUser u where u.email like :value";
List<FireUser> u = findHelper(query, email);
// Should be at most one result
return u.isEmpty() ? null : u.get(0);
}
@Override
public List<FireUser> findUsersByFirstName(String firstName) {
String query = "select u from FireUser u where u.fname like :value";
return findHelper(query, firstName);
}
@Override
public List<FireUser> findUsersByLastName(String lastName) {
String query = "select u from FireUser u where u.lname like :value";
return findHelper(query, lastName);
}
private List<FireUser> findHelper(String query, String value) {
List<FireUser> users = null;
try {
TypedQuery<FireUser> q = getEntityManager().createQuery(query, FireUser.class);
q.setParameter("value", value);
users = q.getResultList();
} catch (PersistenceException ex) {
FireLogger.logSevere("Error in findHelper {0}", ex);
}
return users;
}
}