Example usage for com.google.gson JsonElement getAsBoolean

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

Introduction

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

Prototype

public boolean getAsBoolean() 

Source Link

Document

convenience method to get this element as a boolean value.

Usage

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

/**
 * Add a single value of a known type.//from  w w  w.j a v a 2  s  .  c o m
 */
static void value(StringBuilder sb, String type, JsonElement value) {
    switch (type) {
    case "UINT8":
    case "UINT16":
    case "UINT32":
    case "UINT64":
    case "INT8":
    case "INT16":
    case "INT32":
    case "INT64":
    case "FLOAT32":
    case "FLOAT64":
        numberLiteral(sb, value.getAsJsonPrimitive(), type);
        break;
    case "RSTRING":
        stringLiteral(sb, value.getAsString());
        break;
    case "USTRING":
        stringLiteral(sb, value.getAsString());
        sb.append("u");
        break;

    case "BOOLEAN":
        sb.append(value.getAsBoolean());
        break;

    default:
    case JParamTypes.TYPE_ENUM:
    case JParamTypes.TYPE_SPLTYPE:
    case JParamTypes.TYPE_ATTRIBUTE:
    case JParamTypes.TYPE_SPL_EXPRESSION:
        sb.append(value.getAsString());
        break;
    }
}

From source file:com.ibm.streamsx.topology.internal.gson.GsonUtilities.java

License:Open Source License

public static boolean jboolean(JsonObject object, String property) {
    if (object.has(property)) {
        JsonElement je = object.get(property);
        if (je.isJsonNull())
            return false;
        return je.getAsBoolean();
    }/*from www  .j  a  va2s . c om*/
    return false;
}

From source file:com.jcwhatever.nucleus.storage.JsonDataNode.java

License:MIT License

@Override
@Nullable//from   w  w  w . ja v a2 s . c o  m
protected Object getBooleanObject(String keyPath) {
    JsonElement element = getJsonElement(keyPath);
    if (element == null || element.isJsonObject())
        return null;

    return element.getAsBoolean();
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java

License:Open Source License

private static boolean isDeleted(JsonObject item) {

    JsonElement deletedToken = item.get(MobileServiceSystemColumns.Deleted);

    boolean isDeleted = deletedToken != null && deletedToken.getAsBoolean();

    return isDeleted;
}

From source file:com.orchestra.portale.externalauth.FacebookUtils.java

public static Boolean ifTokenValid(String access_token) throws FacebookException {

    Boolean is_valid = false;//from  w  ww .  jav a2s.  c  o  m

    String fb_token_url = "https://graph.facebook.com/debug_token?" + "input_token=" + access_token
            + "&access_token=" + FACEBOOK_APP_TOKEN;

    try {

        BufferedReader ck_token_in = NetworkUtils.doConnection(fb_token_url);
        String ck_token = ck_token_in.readLine();

        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(ck_token);
        JsonObject j_object = (JsonObject) element;
        JsonObject data = (JsonObject) j_object.get("data");
        JsonElement validity = data.get("is_valid");
        is_valid = validity.getAsBoolean();

    } catch (MalformedURLException ex) {
        throw new FacebookException();
    } catch (IOException ioex) {
        throw new FacebookException();
    }

    return is_valid;
}

From source file:com.paysafe.common.impl.BooleanAdapter.java

License:Open Source License

/**
 * Some api transactions will return 0 or 1 instead of the expected true or false.
 *
 * @param el the el/*from w  ww. j  a  va2  s  .  c  o  m*/
 * @param typeOfT the type of t
 * @param context the context
 * @return Boolean
 * @throws JsonParseException the json parse exception
 */
@Override
public Boolean deserialize(JsonElement el, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (((Class<?>) typeOfT).equals(Boolean.class)) {
        return el.getAsBoolean();
    } else if (((Class<?>) typeOfT).isInstance(Integer.class)) {
        final int elAsInt = el.getAsInt();
        if (elAsInt < 0 || elAsInt > 1) {
            throw new JsonParseException("Boolean out of range: " + elAsInt);
        }
        return elAsInt == 1;
    } else {
        throw new JsonParseException("Unexpected type: " + typeOfT);
    }
}

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

License:Apache License

@SuppressWarnings({ "unchecked", "serial", "rawtypes" })
@Override/*from ww  w .  jav  a 2 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);
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.AddExerciseInRegionAction.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 idExerciseElement = json.get(Constants.ACTION_PARAM_EXERCISE_ID);

    JsonElement taskDefinitionNameElement = json.get(Constants.ACTION_PARAM_TASK_DEFINITION_NAME);
    JsonElement containerNameElement = json.get(Constants.ACTION_PARAM_CONTAINER_NAME);
    JsonElement repositoryImageUrlElement = json.get(Constants.ACTION_PARAM_REPO_URL);
    JsonElement softMemoryLimitElement = json.get(Constants.ACTION_PARAM_SOFT_MEMORY);
    JsonElement regionElement = json.get(Constants.ACTION_PARAM_REGION);
    JsonElement hardMemoryLimitElement = json.get(Constants.ACTION_PARAM_HARD_MEMORY);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);

    String taskDefinitionName = taskDefinitionNameElement.getAsString();
    String containerName = containerNameElement.getAsString();

    String repositoryImageUrl = repositoryImageUrlElement.getAsString();
    String region = regionElement.getAsString();
    Integer softMemoryLimit = softMemoryLimitElement.getAsInt();
    Integer hardMemoryLimit = hardMemoryLimitElement.getAsInt();

    Boolean active = statusElement.getAsBoolean();
    Integer idExercise = idExerciseElement.getAsInt();

    AvailableExercise exercise = hpc.getAvailableExercise(idExercise);
    if (null == exercise) {
        MessageGenerator.sendErrorMessage("ExerciseNotFound", response);
        logger.error("Exercise " + idExercise + " not found for user " + sessionUser.getIdUser());
        return;//from  w  w w .j  a v a 2 s .com
    }

    Regions awsRegion = null;
    try {
        awsRegion = Regions.valueOf(region);
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("RegionNotFound", response);
        logger.error("Region " + region + " not found for user " + sessionUser.getIdUser());
        return;
    }

    RTFECSTaskDefinition ecsTask = new RTFECSTaskDefinition();

    ecsTask.setRegion(awsRegion);
    ecsTask.setContainerName(containerName);
    ecsTask.setTaskDefinitionName(taskDefinitionName);
    ecsTask.setHardMemoryLimit(hardMemoryLimit);
    ecsTask.setSoftMemoryLimit(softMemoryLimit);
    ecsTask.setRepositoryImageUrl(repositoryImageUrl);
    ecsTask.setUpdateDate(new Date());

    AWSHelper awsHelper = new AWSHelper();
    String arn = awsHelper.createECSTaskDefinition(ecsTask, sessionUser);

    if (null != arn) {
        ecsTask.setTaskDefinitionArn(arn);
        String nameWithRevision = arn.split("/")[(arn.split("/").length) - 1];
        if (null != nameWithRevision && !nameWithRevision.equals(""))
            ecsTask.setTaskDefinitionName(nameWithRevision);
        RTFECSTaskDefinitionForExerciseInRegion ecsTaskForExercise = new RTFECSTaskDefinitionForExerciseInRegion();
        ecsTaskForExercise.setExercise(exercise);
        ecsTaskForExercise.setRegion(awsRegion);
        ecsTaskForExercise.setTaskDefinition(ecsTask);
        ecsTaskForExercise.setActive(active);
        Integer id = hpc.addECSTaskDefinitionForExerciseInRegion(ecsTaskForExercise);
        if (null == id) {
            MessageGenerator.sendErrorMessage("Error", response);
            logger.error("New ECSTaskDefinitionForExerciseInRegion could not be saved for user "
                    + sessionUser.getIdUser());
            return;
        }
        MessageGenerator.sendSuccessMessage(response);
        return;
    }
    MessageGenerator.sendErrorMessage("Error", response);
    logger.error(
            "New ECSTaskDefinitionForExerciseInRegion could not be saved for user " + sessionUser.getIdUser());
}

From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.AddSatelliteGatewayAction.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 nameElement = json.get(Constants.ACTION_PARAM_NAME);
    JsonElement regionElement = json.get(Constants.ACTION_PARAM_REGION);
    JsonElement fqdnElement = json.get(Constants.ACTION_PARAM_FQDN);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);

    String name = nameElement.getAsString();
    String region = regionElement.getAsString();
    String fqdn = fqdnElement.getAsString();
    Boolean status = statusElement.getAsBoolean();

    Regions awsRegion = null;//from   ww w .  ja  v a  2  s .  co  m
    try {
        awsRegion = Regions.valueOf(region);
    } catch (Exception e) {
        MessageGenerator.sendErrorMessage("RegionNotFound", response);
        logger.error("Region " + region + " not found for user " + sessionUser.getIdUser());
        return;
    }

    RTFGateway g = new RTFGateway();
    g.setName(name);
    g.setFqdn(fqdn);
    g.setRegion(awsRegion);
    g.setActive(status);

    Integer id = hpc.addGateway(g);
    if (null != id)
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Failed", response);
}

From source file:com.remediatetheflag.global.actions.auth.management.rtfadmin.UpdateSatelliteGatewayAction.java

License:Apache License

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

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);

    JsonElement idElement = json.get(Constants.ACTION_PARAM_ID);
    JsonElement nameElement = json.get(Constants.ACTION_PARAM_NAME);
    JsonElement fqdnElement = json.get(Constants.ACTION_PARAM_FQDN);
    JsonElement statusElement = json.get(Constants.ACTION_PARAM_STATUS);

    Integer id = idElement.getAsInt();
    String name = nameElement.getAsString();
    String fqdn = fqdnElement.getAsString();
    Boolean status = statusElement.getAsBoolean();

    RTFGateway g = new RTFGateway();
    g.setName(name);/*w  ww.  jav a  2  s  .co  m*/
    g.setFqdn(fqdn);
    g.setActive(status);

    if (hpc.updateGateway(id, g))
        MessageGenerator.sendSuccessMessage(response);
    else
        MessageGenerator.sendErrorMessage("Failed", response);
}