Example usage for com.fasterxml.jackson.databind JsonNode asText

List of usage examples for com.fasterxml.jackson.databind JsonNode asText

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode asText.

Prototype

public abstract String asText();

Source Link

Usage

From source file:com.baasbox.controllers.Admin.java

public static Result createUser() {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();/*from ww  w.j  av  a  2s.c  o  m*/
    if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("signUp bodyJson: " + bodyJson);

    //check and validate input
    if (!bodyJson.has("username"))
        return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password"))
        return badRequest("The 'password' field is missing");
    if (!bodyJson.has("role"))
        return badRequest("The 'role' field is missing");

    //extract fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    JsonNode userID = bodyJson.get(BaasBoxPrivateFields.ID.toString());

    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);
    String role = (String) bodyJson.findValuesAsText("role").get(0);
    String id = (userID != null && userID.isTextual()) ? userID.asText() : null;

    if (privateAttributes != null && privateAttributes.has("email")) {
        //check if email address is valid
        if (!Util.validateEmail((String) (String) privateAttributes.findValuesAsText("email").get(0)))
            return badRequest("The email address must be valid.");
    }

    //try to signup new user
    try {
        UserService.signUp(username, password, null, role, nonAppUserAttributes, privateAttributes,
                friendsAttributes, appUsersAttributes, false, id);
    } catch (InvalidParameterException e) {
        return badRequest(ExceptionUtils.getMessage(e));
    } catch (InvalidJsonException e) {
        return badRequest("Body is not a valid JSON: " + ExceptionUtils.getMessage(e) + "\nyou sent:\n"
                + bodyJson.toString() + "\nHint: check the fields "
                + UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER + " they must be an object, not a value.");
    } catch (UserAlreadyExistsException e) {
        return badRequest(ExceptionUtils.getMessage(e));
    } catch (EmailAlreadyUsedException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("signUp", e);
        return badRequest(username + ": the email provided is already in use");
    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
        throw new RuntimeException(e);
    }
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method End");
    return created();
}

From source file:com.baasbox.commands.LinksResource.java

private String getLinkId(JsonNode command) throws CommandException {
    JsonNode params = command.get(ScriptCommand.PARAMS);
    JsonNode id = params.get("id");
    if (id == null || !id.isTextual()) {
        throw new CommandParsingException(command, "missing link id");
    }//from ww  w  . jav a  2  s  .  co m
    String idString = id.asText();
    return idString;
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserializeV3(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }//from  w ww  . j a va2  s  .co  m

    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            DOMTreeUtilsV3.buildSubtree(content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.crushpaper.JsonNodeHelper.java

/**
 * Returns the string array value for the key, null if it does not exist, or
 * throws an exception if the value is not an array of strings.
 * //from  w  ww  .  j a  va  2 s. c  om
 * @throws IOException
 */
public String[] getStringArray(String key) throws IOException {
    JsonNode value = node.get(key);
    if (value == null) {
        return null;
    }

    if (!value.isArray()) {
        throw new IOException();
    }

    int size = value.size();
    String[] values = new String[size];
    for (int i = 0; i < size; ++i) {
        JsonNode element = value.get(i);
        if (element == null) {
            throw new IOException();
        }

        if (!element.isTextual()) {
            throw new IOException();
        }

        values[i] = element.asText();
    }

    return values;
}

From source file:com.neovisionaries.security.JsonDigestUpdater.java

private void updateText(JsonNode node) {
    // Text start.
    mark("T");// w  ww  .ja  v  a 2s . co  m

    digest.update(node.asText());

    // Text end.
    mark("t");
}

From source file:com.digitalpebble.storm.crawler.filtering.regex.RegexURLNormalizer.java

/** Populates a List of Rules off of JsonNode. */
private List<Rule> readRules(ArrayNode rulesList) {
    List<Rule> rules = new ArrayList<Rule>();
    for (JsonNode regexNode : rulesList) {
        if (regexNode == null || regexNode.isNull()) {
            LOG.warn("bad config: 'regex' element is null");
            continue;
        }//w ww .  j av  a  2 s  .  c o  m
        JsonNode patternNode = regexNode.get("pattern");
        JsonNode substitutionNode = regexNode.get("substitution");

        String substitutionValue = "";
        if (substitutionNode != null) {
            substitutionValue = substitutionNode.asText();
        }
        if (patternNode != null && StringUtils.isNotBlank(patternNode.asText())) {
            Rule rule = createRule(patternNode.asText(), substitutionValue);
            if (rule != null) {
                rules.add(rule);
            }
        }
    }
    if (rules.size() == 0) {
        rules = EMPTY_RULES;
    }
    return rules;
}

From source file:com.digitalpebble.stormcrawler.filtering.regex.RegexURLNormalizer.java

/** Populates a List of Rules off of JsonNode. */
private List<Rule> readRules(ArrayNode rulesList) {
    List<Rule> rules = new ArrayList<>();
    for (JsonNode regexNode : rulesList) {
        if (regexNode == null || regexNode.isNull()) {
            LOG.warn("bad config: 'regex' element is null");
            continue;
        }/*from   w  ww  .  j a v  a2s . c om*/
        JsonNode patternNode = regexNode.get("pattern");
        JsonNode substitutionNode = regexNode.get("substitution");

        String substitutionValue = "";
        if (substitutionNode != null) {
            substitutionValue = substitutionNode.asText();
        }
        if (patternNode != null && StringUtils.isNotBlank(patternNode.asText())) {
            Rule rule = createRule(patternNode.asText(), substitutionValue);
            if (rule != null) {
                rules.add(rule);
            }
        }
    }
    if (rules.size() == 0) {
        rules = EMPTY_RULES;
    }
    return rules;
}

From source file:com.ikanow.aleph2.security.service.IkanowV1DataGroupRoleProvider.java

public Tuple2<Set<String>, Set<String>> getRolesAndPermissions(String principalName) {

    Set<String> roleNames = new HashSet<String>();
    Set<String> permissions = new HashSet<String>();

    Cursor<JsonNode> result;
    try {/*w w  w . ja  va 2 s. c  om*/

        ObjectId objecId = new ObjectId(principalName);
        result = getCommunityDb().getObjectsBySpec(
                CrudUtils.allOf().when("members._id", objecId).when("isSystemCommunity", false)).get();
        boolean roleAssigned = false;
        for (Iterator<JsonNode> it = result.iterator(); it.hasNext();) {
            if (!roleAssigned) {
                roleNames.add(principalName);
                roleAssigned = true;
            }
            JsonNode community = it.next();
            JsonNode type = community.get("type");
            if (type == null || "data".equalsIgnoreCase(type.asText())) {
                String communityId = community.get("_id").asText();
                if (!SYSTEM_COMMUNITY_ID.equals(communityId)) {
                    //String communityName = community.get("name").asText();
                    String action = determineCommunityAction(community.get("members"), principalName);
                    String communityPermission = PermissionExtractor.createPermission(
                            IkanowV1SecurityService.SECURITY_ASSET_COMMUNITY, Optional.of(action), communityId);
                    permissions.add(communityPermission);
                    Tuple2<Set<String>, Set<String>> sourceAndBucketIds = loadSourcesAndBucketIdsByCommunityId(
                            communityId);
                    // add all sources to permissions
                    for (String sourceId : sourceAndBucketIds._1()) {
                        String sourcePermission = PermissionExtractor.createPermission(
                                IkanowV1SecurityService.SECURITY_ASSET_SOURCE, Optional.of(action), sourceId);
                        permissions.add(sourcePermission);
                    }
                    // add all bucketids to permissions
                    Set<String> bucketIds = sourceAndBucketIds._2();
                    if (!bucketIds.isEmpty()) {
                        Set<String> bucketPathPermissions = loadBucketPermissions(bucketIds, action);
                        permissions.addAll(bucketPathPermissions);
                    }
                    Set<String> sharePermissions = loadSharePermissionsByCommunityId(communityId);
                    permissions.addAll(sharePermissions);
                }
            } // type
        } // it
        logger.debug("Permissions for " + principalName + ":");
        logger.debug(permissions);

    } catch (Exception e) {
        logger.error("Caught Exception", e);
    }
    logger.debug("Roles loaded for " + principalName + ":");
    logger.debug(roleNames);
    return Tuples._2T(roleNames, permissions);
}

From source file:net.solarnetwork.node.weather.nz.metservice.MetserviceWeatherDatumDataSource.java

@Override
public GeneralLocationDatum readCurrentDatum() {
    GeneralAtmosphericDatum result = null;

    String url = getBaseUrl() + '/' + localObs;
    final SimpleDateFormat tsFormat = new SimpleDateFormat(getTimestampDateFormat());
    try {/*from  w w w  . j  a v a2  s .co m*/
        URLConnection conn = getURLConnection(url, HTTP_METHOD_GET);
        JsonNode root = getObjectMapper().readTree(getInputStreamFromURLConnection(conn));
        JsonNode data = root.get(localObsContainerKey);
        if (data == null) {
            log.warn("Local observation container key '{}' not found in {}", localObsContainerKey, url);
            return null;
        }
        Date infoDate = parseDateAttribute("dateTime", data, tsFormat);
        Float temp = parseFloatAttribute("temp", data);

        if (infoDate == null || temp == null) {
            log.debug("Date and/or temperature missing from {}", url);
            return null;
        }
        result = new GeneralAtmosphericDatum();
        result.setCreated(infoDate);
        result.setTemperature(temp);

        result.setHumidity(parseIntegerAttribute("humidity", data));

        Double millibar = parseDoubleAttribute("pressure", data);
        if (millibar != null) {
            int pascals = (int) (millibar.doubleValue() * 100);
            result.setAtmosphericPressure(pascals);
        }

        // get local forecast
        try {
            url = getBaseUrl() + '/' + localForecast;
            conn = getURLConnection(url, HTTP_METHOD_GET);
            root = getObjectMapper().readTree(getInputStreamFromURLConnection(conn));

            JsonNode forecastWord = root.findValue("forecastWord");
            if (forecastWord != null) {
                result.setSkyConditions(forecastWord.asText());
            }
        } catch (IOException e) {
            log.warn("Error reading MetService URL [{}]: {}", url, e.getMessage());
        }

        log.debug("Obtained WeatherDatum: {}", result);

    } catch (IOException e) {
        log.warn("Error reading MetService URL [{}]: {}", url, e.getMessage());
    }
    return result;
}

From source file:ext.sns.auth.AccessTokenResponse.java

/**
 * ?/*ww w. j a  v  a  2  s.  c om*/
 * 
 * @param key ?key
 * @return ?Map
 */
public String getResponseValue(String key) {
    if (resultType == 1) {
        @SuppressWarnings("unchecked")
        Map<String, String> resultMap = (Map<String, String>) resultObject;
        return resultMap.get(key);
    } else if (resultType == 2) {
        JsonNode resultJson = (JsonNode) resultObject;

        if (!resultJson.hasNonNull(key)) {
            return null;
        }

        JsonNode valueNode = resultJson.get(key);
        if (valueNode.isContainerNode()) {
            return valueNode.toString();
        } else {
            return valueNode.asText();
        }

    } else {
        return null;
    }
}