Example usage for com.google.gson JsonElement getAsInt

List of usage examples for com.google.gson JsonElement getAsInt

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsInt.

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:com.remediatetheflag.global.actions.auth.management.admin.RemoveChallengeAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement idChallengeEement = json.get(Constants.ACTION_PARAM_ID);
    Integer idChallenge = idChallengeEement.getAsInt();
    Challenge challenge = hpc.getChallengeWithDetails(idChallenge, sessionUser.getManagedOrganizations());
    if (null == challenge) {
        logger.warn("User " + sessionUser.getIdUser() + " not authorized to remove challenge: " + idChallenge);
        MessageGenerator.sendErrorMessage("NotAuthorized", response);
        return;//from  ww w  .ja v a2  s.co  m
    }
    Boolean result = hpc.removeChallenge(challenge);
    if (!result) {
        logger.warn("Could not remove challenge " + idChallenge);
        MessageGenerator.sendErrorMessage("ChallengeRemoveFailed", response);
        return;
    }
    MessageGenerator.sendSuccessMessage(response);
    return;
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.RemoveInvitationCodeAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement orgIdElement = json.get(Constants.ACTION_PARAM_ORG_ID);
    Integer orgId = orgIdElement.getAsInt();
    JsonElement codeElement = json.get(Constants.ACTION_PARAM_ORG_CODE);
    String code = codeElement.getAsString();

    Organization org = hpc.getOrganizationById(orgId);
    if (!isManagingOrg(sessionUser, org)) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;/*  w  w  w  .  j  a  v  a2 s  . co  m*/
    }

    Boolean result = hpc.removeInvitationCode(code, orgId);

    if (result)
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Failed", response);
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.RemoveOrganizationAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement idOrgElement = json.get(Constants.ACTION_PARAM_ORG_ID);
    Integer idOrg = idOrgElement.getAsInt();

    Organization org = hpc.getOrganizationById(idOrg);
    if (!isManagingOrg(sessionUser, org)) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;//from   w  ww.j av a2 s  .com
    }

    Boolean result = hpc.deleteOrganization(idOrg);
    if (!result) {
        logger.warn("Could not remove organization " + idOrg);
        MessageGenerator.sendErrorMessage("OrganizationRemoveFailed", response);
        return;
    }
    MessageGenerator.sendSuccessMessage(response);
    return;
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.RemoveTeamAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);

    JsonElement teamIdJson = json.get(Constants.ACTION_PARAM_TEAM_ID);
    Integer teamId = teamIdJson.getAsInt();
    Team team = hpc.getTeam(teamId, sessionUser.getManagedOrganizations());

    List<User> users = hpc.getUsersForTeamName(team.getName(), sessionUser.getManagedOrganizations());
    if (null == users || users.isEmpty()) {
        hpc.deleteTeam(team);//from   w  w  w. j  ava  2  s .c  o m
        MessageGenerator.sendSuccessMessage(response);
    } else {
        MessageGenerator.sendErrorMessage("TeamNotEmpty", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.RemoveTeamManagerAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement jsonTeamId = json.get(Constants.ACTION_PARAM_TEAM_ID);
    Integer teamId = jsonTeamId.getAsInt();
    JsonElement jsonUser = json.get(Constants.ACTION_PARAM_USERNAME);
    String username = jsonUser.getAsString();

    Team team = hpc.getTeam(teamId, sessionUser.getManagedOrganizations());
    if (null == team) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;/*w w  w  . ja  v a  2  s  . c  o  m*/
    }
    User user = hpc.getUserFromUsername(username, sessionUser.getManagedOrganizations());
    if (null != user) {
        hpc.removeFromTeamManager(team.getIdTeam(), user);
        List<Team> teams = hpc.getTeamsManagedBy(user);
        if (teams.isEmpty() && user.getRole().equals(Constants.ROLE_TEAM_MANAGER)) {
            user.setRole(Constants.ROLE_USER);
            hpc.updateUserInfo(user);
        }
        MessageGenerator.sendSuccessMessage(response);
    } else {
        MessageGenerator.sendErrorMessage("NotFound", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.UpdateOrganizationAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);

    JsonElement idOrgElement = json.get(Constants.ACTION_PARAM_ID);

    JsonElement nameElement = json.get(Constants.ACTION_PARAM_NAME);
    JsonElement contactEmailElement = json.get(Constants.ACTION_PARAM_EMAIL);
    JsonElement maxUsersElement = json.get(Constants.ACTION_PARAM_MAX_USERS);

    String name = nameElement.getAsString();
    String contactEmail = contactEmailElement.getAsString();
    Integer maxUsers = maxUsersElement.getAsInt();

    Organization o = new Organization();

    Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    o.setDateJoined(c.getTime());/*from  www.j  a  v a 2s .  co m*/
    o.setName(name);
    o.setEmail(contactEmail);
    o.setMaxUsers(maxUsers);
    o.setStatus(OrganizationStatus.ACTIVE);

    Boolean result = hpc.updateOrganization(idOrgElement.getAsInt(), o);
    if (result) {
        MessageGenerator.sendSuccessMessage(response);
    } else {
        MessageGenerator.sendErrorMessage("Failed", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.admin.UpdateUserAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JsonObject json = (JsonObject) request.getAttribute("json");

    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement idUser = json.get(Constants.ACTION_PARAM_ID);
    JsonElement usernameElement = json.get(Constants.ACTION_PARAM_USERNAME);
    JsonElement firstNameElement = json.get(Constants.ACTION_PARAM_FIRST_NAME);
    JsonElement lastNameElement = json.get(Constants.ACTION_PARAM_LAST_NAME);
    JsonElement emailElement = json.get(Constants.ACTION_PARAM_EMAIL);
    JsonElement countryElement = json.get(Constants.ACTION_PARAM_COUNTRY);
    JsonElement orgElement = json.get(Constants.ACTION_PARAM_ORG_ID);

    JsonElement roleElement = json.get(Constants.ACTION_PARAM_ROLE_ID);
    JsonElement concurrentExerciseLimitElement = json.get(Constants.ACTION_PARAM_CONCURRENT_EXERCISE_LIMIT);
    JsonElement creditsElement = json.get(Constants.ACTION_PARAM_CREDITS);

    String username = usernameElement.getAsString();
    String firstName = firstNameElement.getAsString();
    String lastName = lastNameElement.getAsString();
    String email = emailElement.getAsString();
    String country = countryElement.getAsString();
    Integer orgId = orgElement.getAsInt();
    Integer credits = creditsElement.getAsInt();

    Integer roleId = roleElement.getAsInt();
    Integer concurrentExercisesLimit = concurrentExerciseLimitElement.getAsInt();
    Boolean emailVerified = true;
    Boolean forcePasswordChange = false;

    Integer usrRole = -1;//from   w ww .ja  v a2  s .  c o  m
    switch (roleId) {
    case -1:
        usrRole = Constants.ROLE_RTF_ADMIN;
        break;
    case 0:
        usrRole = Constants.ROLE_ADMIN;
        break;
    case 1:
        usrRole = Constants.ROLE_REVIEWER;
        break;
    case 3:
        usrRole = Constants.ROLE_TEAM_MANAGER;
        break;
    case 4:
        usrRole = Constants.ROLE_STATS;
        break;
    case 7:
        usrRole = Constants.ROLE_USER;
        break;

    default: {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    }
    if (usrRole.intValue() < sessionUser.getRole().intValue()) {
        MessageGenerator.sendErrorMessage("NotAuthorized", response);
        return;
    }
    Organization o = hpc.getOrganizationById(orgId);
    if (null == o) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    boolean isManager = false;
    for (Organization organization : sessionUser.getManagedOrganizations()) {
        if (o.getId().equals(organization.getId())) {
            isManager = true;
            break;
        }
    }
    if (!isManager) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    @SuppressWarnings("serial")
    List<User> organizationUsers = hpc.getManagementAllUsers(new HashSet<Organization>() {
        {
            add(o);
        }
    });
    if (organizationUsers.size() >= o.getMaxUsers()) {
        MessageGenerator.sendErrorMessage("MaxUserLimit", response);
        return;
    }
    User dbUser = hpc.getUserFromUserId(idUser.getAsInt());
    if (!dbUser.getUsername().equals(username)) {
        User existingUser = hpc.getUserFromUsername(username);
        if (existingUser != null) {
            MessageGenerator.sendErrorMessage("UserExists", response);
            return;
        }
    }
    Country c = hpc.getCountryFromCode(country);
    if (null == c) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    dbUser.setEmail(email);
    dbUser.setLastName(lastName);
    dbUser.setUsername(username);
    dbUser.setFirstName(firstName);
    dbUser.setRole(usrRole);
    dbUser.setStatus(UserStatus.ACTIVE);
    dbUser.setCountry(c);
    dbUser.setEmailVerified(emailVerified);
    dbUser.setForceChangePassword(forcePasswordChange);
    dbUser.setInstanceLimit(concurrentExercisesLimit);
    dbUser.setCredits(credits);
    if (null != dbUser.getTeam()) {
        if (!dbUser.getTeam().getOrganization().getId().equals(o.getId())) {
            dbUser.setTeam(null);
        }
    }
    dbUser.setDefaultOrganization(o);
    dbUser.setPersonalDataUpdateDateTime(new Date());
    Boolean alreadyManaging = false;
    if (dbUser.getRole().intValue() < 7) {
        for (Organization uManagedOrg : dbUser.getManagedOrganizations()) {
            if (uManagedOrg.getId().equals(o.getId())) {
                alreadyManaging = true;
                break;
            }
        }
        if (!alreadyManaging)
            dbUser.getManagedOrganizations().add(o);
    } else {
        dbUser.setManagedOrganizations(null);
    }
    Boolean result = hpc.updateUserInfo(dbUser);
    if (result) {
        MessageGenerator.sendSuccessMessage(response);
    } else {
        logger.error("Update failed at DB-end for email: " + email);
        MessageGenerator.sendErrorMessage("UpdateFailed", response);
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.monitor.GetChallengeDetailsAction.java

License:Apache License

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement jsonElement = json.get(Constants.ACTION_PARAM_ID);
    Integer idChallenge = jsonElement.getAsInt();

    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);
    Challenge challenge = hpc.getChallengeWithDetails(idChallenge, sessionUser.getManagedOrganizations());

    boolean granted = true;
    if (sessionUser.getRole().equals(Constants.ROLE_TEAM_MANAGER)) {
        List<User> users = hpc.getUsersInTeamManagedBy(sessionUser);
        granted = isTeamManagerGranted(users, challenge);
    }/*from   ww  w  .j a  v  a2 s . c  o m*/
    if (!granted) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    MessageGenerator.sendChallengeDetailsMessage(challenge, response);

}

From source file:com.remediatetheflag.global.actions.auth.management.reviewer.AddTeamAction.java

License:Apache License

@SuppressWarnings("serial")
@Override/*from   ww  w. j av a2s  . co  m*/
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement newTeamName = json.get(Constants.ACTION_PARAM_TEAM_NAME);
    String teamName = newTeamName.getAsString();

    JsonElement newTeamOrganization = json.get(Constants.ACTION_PARAM_ORG_NAME);
    Integer teamOrg = newTeamOrganization.getAsInt();

    //check if user can manage specified org
    Organization org = hpc.getOrganizationById(teamOrg);
    boolean isManager = false;
    for (Organization mOrg : sessionUser.getManagedOrganizations()) {
        if (org.getId().equals(mOrg.getId())) {
            isManager = true;
            break;
        }
    }
    if (null == org || !isManager) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    //check if team already exists for specified org
    Team t = hpc.getTeamFromName(teamName, org);
    if (null != t) {
        MessageGenerator.sendErrorMessage("TeamExists", response);
        return;
    }

    Team team = new Team();
    team.setManagers(new HashSet<User>() {
        {
            add(sessionUser);
        }
    });
    team.setName(teamName);
    team.setCreatedByUser(sessionUser.getIdUser());
    team.setOrganization(org);
    if (null != hpc.addTeam(team))
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Error", response);

}

From source file:com.remediatetheflag.global.actions.auth.management.reviewer.AddUserAction.java

License:Apache License

@SuppressWarnings({ "unchecked", "serial", "rawtypes" })
@Override/*from  w  w w.  j a v a2 s  . c  o  m*/
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JsonObject json = (JsonObject) request.getAttribute("json");

    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement usernameElement = json.get(Constants.ACTION_PARAM_USERNAME);
    JsonElement firstNameElement = json.get(Constants.ACTION_PARAM_FIRST_NAME);
    JsonElement lastNameElement = json.get(Constants.ACTION_PARAM_LAST_NAME);
    JsonElement emailElement = json.get(Constants.ACTION_PARAM_EMAIL);
    JsonElement countryElement = json.get(Constants.ACTION_PARAM_COUNTRY);
    JsonElement passwordElement = json.get(Constants.ACTION_PARAM_PASSWORD);
    JsonElement orgElement = json.get(Constants.ACTION_PARAM_ORG_ID);

    JsonElement roleElement = json.get(Constants.ACTION_PARAM_ROLE_ID);
    JsonElement concurrentExerciseLimitElement = json.get(Constants.ACTION_PARAM_CONCURRENT_EXERCISE_LIMIT);
    JsonElement creditsElement = json.get(Constants.ACTION_PARAM_CREDITS);
    JsonElement passwordChangeElement = json.get(Constants.ACTION_PARAM_FORCE_PASSWORD_CHANGE);

    String username = usernameElement.getAsString();
    String firstName = firstNameElement.getAsString();
    String lastName = lastNameElement.getAsString();
    String email = emailElement.getAsString();
    String country = countryElement.getAsString();
    String password = passwordElement.getAsString();
    Integer orgId = orgElement.getAsInt();
    Integer credits = creditsElement.getAsInt();

    Integer roleId = roleElement.getAsInt();
    Integer concurrentExercisesLimit = concurrentExerciseLimitElement.getAsInt();
    Boolean emailVerified = true;//TODO
    Boolean forcePasswordChange = passwordChangeElement.getAsBoolean();

    Integer usrRole = -2;
    switch (roleId) {
    case -1:
        usrRole = Constants.ROLE_RTF_ADMIN;
        break;
    case 0:
        usrRole = Constants.ROLE_ADMIN;
        break;
    case 1:
        usrRole = Constants.ROLE_REVIEWER;
        break;
    case 3:
        usrRole = Constants.ROLE_TEAM_MANAGER;
        break;
    case 4:
        usrRole = Constants.ROLE_STATS;
        break;
    case 7:
        usrRole = Constants.ROLE_USER;
        break;

    default: {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    }
    if (usrRole.intValue() < sessionUser.getRole().intValue()) {
        MessageGenerator.sendErrorMessage("NotAuthorized", response);
        return;
    }
    Organization o = hpc.getOrganizationById(orgId);
    if (null == o) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    boolean isManager = false;
    for (Organization organization : sessionUser.getManagedOrganizations()) {
        if (o.getId().equals(organization.getId())) {
            isManager = true;
            break;
        }
    }
    if (!isManager) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    List<User> organizationUsers = hpc.getManagementAllUsers(new HashSet<Organization>() {
        {
            add(o);
        }
    });
    if (organizationUsers.size() >= o.getMaxUsers()) {
        MessageGenerator.sendErrorMessage("MaxUserLimit", response);
        return;
    }
    if (!PasswordComplexityUtil.isPasswordComplex(password)) {
        MessageGenerator.sendErrorMessage("WeakPassword", response);
        return;
    }
    User existingUser = hpc.getUserFromUsername(username);
    if (existingUser != null) {
        MessageGenerator.sendErrorMessage("UserExists", response);
        return;
    }
    Country c = hpc.getCountryFromCode(country);
    if (null == c) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    User user = new User();
    user.setEmail(email);
    user.setLastName(lastName);
    user.setUsername(username);
    user.setFirstName(firstName);
    user.setRole(usrRole);
    String salt = RandomGenerator.getNextSalt();
    String pwd = DigestUtils.sha512Hex(password.concat(salt));
    user.setSalt(salt);
    user.setPassword(pwd);
    user.setStatus(UserStatus.ACTIVE);
    user.setCountry(c);
    user.setScore(0);
    user.setExercisesRun(0);
    user.setEmailVerified(emailVerified);
    user.setForceChangePassword(forcePasswordChange);
    user.setInstanceLimit(concurrentExercisesLimit);
    user.setJoinedDateTime(new Date());
    user.setTeam(null);
    user.setCredits(credits);
    user.setCreatedByUser(sessionUser.getIdUser());
    user.setDefaultOrganization(o);
    if (user.getRole().intValue() < Constants.ROLE_USER) {
        user.setManagedOrganizations(new HashSet() {
            {
                add(o);
            }
        });
    } else {
        user.setManagedOrganizations(null);
    }
    Integer id = hpc.addUser(user);
    if (null != id && id > 0) {
        NotificationsHelper helper = new NotificationsHelper();
        helper.addNewUserAdded(user);
        helper.addWelcomeToRTFNotification(user);
        MessageGenerator.sendSuccessMessage(response);
    } else {
        logger.error("Signup failed at DB-end for email: " + email);
        MessageGenerator.sendErrorMessage("SignupFailed", response);
    }
}