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:org.qcert.runtime.BinaryOperators.java

License:Apache License

public static JsonElement or(JsonElement e1, JsonElement e2) {
    return new JsonPrimitive(e1.getAsBoolean() || e2.getAsBoolean());
}

From source file:org.qcert.runtime.DataComparator.java

License:Apache License

/** Note: this comparator
 * imposes orderings that are inconsistent with equals.
 *//*  ww w .j  ava  2s  .c o m*/
@Override
public int compare(JsonElement o1, JsonElement o2) {
    // short-circuit in this case
    if (o1 == o2) {
        return 0;
    }

    DType typ1 = getType(o1);
    DType typ2 = getType(o2);

    // For lazily parsed numbers, check type of other operand and try and coerce
    if (typ1 == DType.DT_LAZYNUM) {
        switch (typ2) {
        case DT_LONG:
            return Long.compare(o1.getAsLong(), o2.getAsLong());
        case DT_DOUBLE:
            return Double.compare(o1.getAsDouble(), o2.getAsDouble());
        case DT_LAZYNUM:
            // Tricky here... there is no way to know what to coerce to,
            // underlying gson code relies on string equality, hence so do we
            typ1 = DType.DT_STRING;
            typ2 = DType.DT_STRING;
        }
    } else if (typ2 == DType.DT_LAZYNUM) {
        switch (typ1) {
        case DT_LONG:
            return Long.compare(o1.getAsLong(), o2.getAsLong());
        case DT_DOUBLE:
            return Double.compare(o1.getAsDouble(), o2.getAsDouble());
        }
    }

    final int typCompare = typ1.compareTo(typ2);
    if (typCompare != 0) {
        return typCompare;
    }

    switch (typ1) {
    case DT_JNULL:
    case DT_NULL:
        return 0;
    case DT_BOOL:
        return Boolean.compare(o1.getAsBoolean(), o2.getAsBoolean());
    case DT_STRING:
        String str1 = o1.getAsString();
        String str2 = o2.getAsString();
        // TODO
        // WARNING 
        // HACK
        // special hack for dates.
        // what could go wrong??? :-D
        // of course, this breaks the transitivity of compareTo
        // sigh...
        // a real solution to this is a bit challenging
        // since we need type information
        // or a wrapper around date times.
        try {
            final ZonedDateTime date1 = ZonedDateTime.parse(str1);
            final ZonedDateTime date2 = ZonedDateTime.parse(str2);
            // if they are both parseable as dates, we will compare them as dates
            return date1.toInstant().compareTo(date2.toInstant());
        } catch (DateTimeException e) {
            // If they are not both parseable as dates, just compare them as strings
            return str1.compareTo(str2);
        }
    case DT_LONG:
        return Long.compare(o1.getAsLong(), o2.getAsLong());
    case DT_DOUBLE:
        return Double.compare(o1.getAsDouble(), o2.getAsDouble());
    case DT_COLL:
        return compare(o1.getAsJsonArray(), o2.getAsJsonArray());
    case DT_REC:
        return compare(o1.getAsJsonObject(), o2.getAsJsonObject());
    default:
        // We should never get here.
        // but if we do, we can use toString to give
        // a deterministic order
        return o1.toString().compareTo(o2.toString());
    }
}

From source file:org.qcert.runtime.RuntimeUtils.java

License:Apache License

public static boolean asBoolean(JsonElement e) {
    return e.getAsBoolean();
}

From source file:org.qcert.runtime.UnaryOperators.java

License:Apache License

public static JsonElement neg(JsonElement e) {
    return new JsonPrimitive(!e.getAsBoolean());
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

License:Apache License

private boolean checkCookiesForToken(HttpServletRequest request, HttpSession session) {
    boolean cookieFound = false;

    // If there is no oauth credential, and the user has a dashboard cookie, add cookie value as
    // oauth session attribute.
    if (session.getAttribute(OAUTH_TOKEN) == null) {
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {

            // Loop through cookies to find dashboard cookie
            for (Cookie c : cookies) {
                if (c.getName().equals(DASHBOARD_COOKIE)) {

                    // DE883. We need to decrypt the cookie value to authenticate the token.
                    String decryptedCookie = null;
                    try {
                        String s = URLDecoder.decode(c.getValue(), "UTF-8");
                        decryptedCookie = propDecryptor.decrypt(s);
                    } catch (GeneralSecurityException e) {
                        LOG.error(e.getMessage());
                    } catch (IOException e) {
                        LOG.error(e.getMessage());
                    } catch (NumberFormatException e) {
                        LOG.info("Failed to decrypt cookie with value: " + c.getValue());
                        return false;
                    }/*from   w  w w  . ja va  2s . c o m*/

                    JsonObject json = restClient.sessionCheck(decryptedCookie);

                    // If user is not authenticated, expire the cookie, else set OAUTH_TOKEN to
                    // cookie value and continue
                    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
                    if ((authElement != null) && (!authElement.getAsBoolean())) {
                        c.setMaxAge(0);
                        LOG.info(LOG_MESSAGE_AUTH_EXPIRING_COOKIE, new Object[] { request.getRemoteAddr() });
                    } else {
                        cookieFound = true;
                        session.setAttribute(OAUTH_TOKEN, decryptedCookie);
                        LOG.info(LOG_MESSAGE_AUTH_USING_COOKIE, new Object[] { request.getRemoteAddr() });
                    }

                }
            }
        }
    }

    return cookieFound;
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

License:Apache License

private SLIPrincipal completeSpringAuthentication(String token) {

    // Get authentication information
    JsonObject json = restClient.sessionCheck(token);

    LOG.debug(json.toString());/*from   w w w  .  j a va 2s  .c  o m*/

    // If the user is authenticated, create an SLI principal, and authenticate
    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
    if ((authElement != null) && (authElement.getAsBoolean())) {

        // Setup principal
        SLIPrincipal principal = new SLIPrincipal();
        principal.setId(token);

        // Extract user name from authentication payload
        String username = "";
        JsonElement nameElement = json.get(Constants.ATTR_AUTH_FULL_NAME);
        if (nameElement != null) {
            username = nameElement.getAsString();
            if (username != null && username.contains("@")) {
                username = username.substring(0, username.indexOf("@"));
                if (username.contains(".")) {
                    String first = username.substring(0, username.indexOf('.'));
                    String second = username.substring(username.indexOf('.') + 1);
                    username = first.substring(0, 1).toUpperCase()
                            + (first.length() > 1 ? first.substring(1) : "")
                            + (second.substring(0, 1).toUpperCase()
                                    + (second.length() > 1 ? second.substring(1) : ""));
                }
            }
        } else {
            LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_NAME);
        }

        // Set principal name
        principal.setName(username);

        // Extract user roles from authentication payload
        LinkedList<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
        JsonArray grantedAuthorities = json.getAsJsonArray(Constants.ATTR_AUTH_ROLES);
        if (grantedAuthorities != null) {

            // Add authorities to user principal
            Iterator<JsonElement> authIterator = grantedAuthorities.iterator();
            while (authIterator.hasNext()) {
                JsonElement nextElement = authIterator.next();
                authList.add(new GrantedAuthorityImpl(nextElement.getAsString()));
            }
        } else {
            LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_ROLES);
        }
        if (json.get(Constants.ATTR_USER_TYPE).getAsString().equals(Constants.ROLE_TEACHER)) {
            authList.add(new GrantedAuthorityImpl(Constants.ROLE_EDUCATOR));
        }

        if (json.get(Constants.ATTR_ADMIN_USER).getAsBoolean()) {
            authList.add(new GrantedAuthorityImpl(Constants.ROLE_IT_ADMINISTRATOR));
        }

        SecurityContextHolder.getContext()
                .setAuthentication(new PreAuthenticatedAuthenticationToken(principal, token, authList));

        return principal;
    } else {
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION_INVALID_AUTHENTICATED);
    }

    return null;
}

From source file:org.sobotics.guttenberg.finders.RelatedAnswersFinder.java

License:Open Source License

public List<Post> fetchRelatedAnswers() {
    //The question_ids of all the new answers
    StringBuilder idString = new StringBuilder();
    int n = 0;/* w  ww .j a  va 2 s .c  o m*/
    for (Integer id : targedIds) {
        idString.append(n++ == 0 ? id : ";" + id);
    }

    LOGGER.debug("Related IDs: " + idString);

    if (idString.length() < 2)
        return new ArrayList<>();

    Properties prop = new Properties();

    try {
        prop = FileUtils.getPropertiesFromFile(FilePathUtils.loginPropertiesFile);
    } catch (IOException e) {
        LOGGER.error("Could not load login.properties", e);
    }

    LOGGER.debug("Fetching the linked/related questions...");

    try {
        JsonObject relatedQuestions = ApiService.defaultService.getRelatedQuestionsByIds(idString.toString());
        LOGGER.debug("Related done");
        JsonObject linkedQuestions = ApiService.defaultService.getLinkedQuestionsByIds(idString.toString());
        LOGGER.debug("linked done");

        StringBuilder relatedIds = new StringBuilder();

        for (JsonElement question : relatedQuestions.get("items").getAsJsonArray()) {
            int id = question.getAsJsonObject().get("question_id").getAsInt();
            LOGGER.trace("Add: " + id);
            relatedIds.append(id).append(";");
        }

        for (JsonElement question : linkedQuestions.get("items").getAsJsonArray()) {
            int id = question.getAsJsonObject().get("question_id").getAsInt();
            LOGGER.trace("Add: " + id);
            relatedIds.append(id).append(";");
        }

        if (relatedIds.length() > 0) {
            relatedIds = new StringBuilder(relatedIds.substring(0, relatedIds.length() - 1));

            List<JsonObject> relatedFinal = new ArrayList<>();

            int i = 1;

            while (i <= 2) {
                LOGGER.debug("Fetch page " + i);
                JsonObject relatedAnswers = ApiService.defaultService
                        .getAnswersToQuestionsByIdString(relatedIds.toString(), i);
                LOGGER.trace("Related answers:\n" + relatedAnswers);

                for (JsonElement answer : relatedAnswers.get("items").getAsJsonArray()) {
                    JsonObject answerObject = answer.getAsJsonObject();
                    relatedFinal.add(answerObject);
                }

                JsonElement hasMoreElement = relatedAnswers.get("has_more");

                if (hasMoreElement != null && !hasMoreElement.getAsBoolean())
                    break;

                i++;
            }

            List<Post> relatedPosts = new ArrayList<>();
            for (JsonElement item : relatedFinal) {
                Post post = PostUtils.getPost(item.getAsJsonObject());
                relatedPosts.add(post);
            }

            LOGGER.debug("Collected " + relatedFinal.size() + " answers");

            return relatedPosts;
        } else {
            LOGGER.warn("No ids found!");
        }

    } catch (IOException e) {
        LOGGER.error("Error in RelatedAnswersFinder", e);
        return new ArrayList<>();
    }

    return new ArrayList<>();
}

From source file:org.sonar.plugins.csharp.sarif.SarifParser01And04.java

License:Open Source License

private static boolean isSuppressed(JsonObject issue) {
    JsonElement isSuppressedInSource = issue.get("isSuppressedInSource");
    if (isSuppressedInSource != null) {
        return isSuppressedInSource.getAsBoolean();
    }//  w w  w .  j  a  v a 2s  .  c o m

    JsonElement properties = issue.get("properties");
    if (properties != null && properties.isJsonObject()) {
        isSuppressedInSource = properties.getAsJsonObject().get("isSuppressedInSource");
        if (isSuppressedInSource != null) {
            return isSuppressedInSource.getAsBoolean();
        }
    }

    return false;
}

From source file:org.sonar.plugins.csharp.sarif.SarifParser10.java

License:Open Source License

private static boolean isSuppressed(JsonObject resultObj) {
    JsonElement isSuppressedInSource = resultObj.get("isSuppressedInSource");
    if (isSuppressedInSource != null) {
        return isSuppressedInSource.getAsBoolean();
    }/*from  w  ww .  j ava2s.c o  m*/

    JsonElement properties = resultObj.get("properties");
    if (properties != null && properties.isJsonObject()) {
        isSuppressedInSource = properties.getAsJsonObject().get("isSuppressedInSource");
        if (isSuppressedInSource != null) {
            return isSuppressedInSource.getAsBoolean();
        }
    }

    return false;
}

From source file:org.springframework.ide.vscode.commons.languageserver.util.Settings.java

License:Open Source License

public Boolean getBoolean(String... names) {
    try {/*from  w  ww.  j a v a2  s .co  m*/
        JsonElement val = getRawProperty(names);
        if (val != null) {
            return val.getAsBoolean();
        }
    } catch (Exception e) {
        log.error("", e);
    }
    return null;
}