package protocol;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import domain.Role;
import domain.User;
public class EditUserQuery extends Query
{
/**
*
*/
private static final long serialVersionUID = -3602183204391786499L;
private Long id;
private String username;
private String password;
private String fullname;
private Long role;
public EditUserQuery() {} // required for Gson
/**
* Checks if the manager send this request,
* Checks if the given id, fullname, password, username and role are valid
* and then update the user in the database
*/
@Override
protected Response internalExecute(HttpServletRequest request, Session databaseSession) {
Response response = null;
User oldUser = null;
HttpSession httpSession = request.getSession();
// if user is not a manager, he can't continue
if( ! ((Boolean) httpSession.getAttribute("manager")) ) {
return new Response(ResponseStatus.FAIL, "No authorization");
}
try {
Role newRoleObject = (Role) databaseSession.createCriteria(Role.class).add(Restrictions.eq("id", this.role)).uniqueResult();
if (null == newRoleObject) {
return new Response(ResponseStatus.FAIL, "User role does not exist, database failure.");
}
oldUser = (User) databaseSession.createCriteria(User.class)
.add(Restrictions.eq("id", id))
.uniqueResult();
if (null == oldUser) {
throw new IllegalArgumentException("The user you are editing was not found.");
}
Transaction transaction = databaseSession.beginTransaction();
oldUser.setUsername(this.username);
oldUser.setPassword(this.password);
oldUser.setFullname(this.fullname);
oldUser.setRole(newRoleObject);
databaseSession.update(oldUser);
transaction.commit();
response = new Response(ResponseStatus.OK);
}
catch (Exception ex) {
// if there was an error, it'll be set here.
response = new Response(ResponseStatus.FAIL, ex.toString());
}
return response;
}
}