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.google.api.server.spi.response.ServletResponseResultWriterTest.java

@Test
public void testEnumAsString() throws Exception {
    TestEnum value = TestEnum.TEST1;/*from  w  w  w. ja  v  a 2s .c  om*/
    JsonNode output = ObjectMapperUtil.createStandardObjectMapper().readValue(writeToResponse(value),
            JsonNode.class);
    assertEquals("TEST1", output.asText());
}

From source file:com.facebook.api.FacebookPostActivitySerializer.java

private void addObjectImage(Activity activity, JsonNode value) {
    Image image = new Image();
    image.setUrl(value.asText());
    activity.getObject().setImage(image);
}

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

@Override
protected JSONProperty doDeserializeV4(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
    final JSONProperty property = new JSONProperty();

    try {//from  w w w  .ja  v a2 s . c  o m
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

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

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

                content.setAttribute(ODataConstants.ATTR_M_TYPE,
                        tree.get(v4AnnotationPrefix + 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) {
            DOMTreeUtilsV4.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.reprezen.swagedit.validation.ErrorProcessor.java

protected String rewriteEnumError(JsonNode error) {
    final JsonNode value = error.get("value");
    final JsonNode enums = error.get("enum");
    final String enumString = Joiner.on(", ").join(enums);

    return String.format(Messages.error_notInEnum, value.asText(), enumString);
}

From source file:net.jawr.web.resource.bundle.factory.util.JsonPropertiesSource.java

/**
 * Generates the properties from a JSON node
 * /*w  ww.j  a  v a2  s  .  c om*/
 * @param node
 *            the JSON node
 * @param props
 *            the properties to populate
 */
private void generateProperties(JsonNode node, String parentPrefix, Properties props) {

    Iterator<Entry<String, JsonNode>> fields = node.fields();
    while (fields.hasNext()) {
        Entry<String, JsonNode> entry = fields.next();
        String fieldName = entry.getKey();
        JsonNode jsonNode = entry.getValue();
        String nodePrefix = parentPrefix == null ? fieldName : parentPrefix + FIELD_NAME_SEPARATOR + fieldName;
        if (jsonNode.isTextual() || jsonNode.isBoolean()) {
            props.put(nodePrefix, jsonNode.asText());
        } else if (jsonNode.isNumber()) {
            props.put(nodePrefix, Integer.toString(jsonNode.asInt()));
        } else if (jsonNode.isArray()) {
            String arrayValue = convertToString(jsonNode);
            props.put(nodePrefix, arrayValue);
        }
        generateProperties(jsonNode, nodePrefix, props);
    }
}

From source file:com.medvision360.medrecord.pv.PVReader.java

public SortedMap<String, String> toMap(InputStream is) throws IOException, ParseException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readValue(is, JsonNode.class);

    Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
    SortedMap<String, String> pv = new TreeMap<>(new ExactPathComparator());
    while (fields.hasNext()) {
        Map.Entry<String, JsonNode> field = fields.next();
        String key = field.getKey();
        JsonNode node = field.getValue();
        JsonNodeType nodeType = node.getNodeType();
        String value;/*from w ww  . j  ava2  s . co m*/
        switch (nodeType) {
        case NULL:
            value = null;
            break;
        case BOOLEAN:
        case NUMBER:
        case STRING:
            value = node.asText();
            break;
        case ARRAY:
        case BINARY:
        case OBJECT:
        case MISSING:
        case POJO:
        default:
            throw new ParseException(
                    String.format("Path %s value is of type %s, need a primitive", key, nodeType));
        }
        pv.put(key, value);
    }

    return pv;
}

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

/**
 * Returns the sourceIds and the bucket IDs associated with the community.
 * @param communityId/*  ww  w . j av a 2 s  .  c  o m*/
 * @return
 * @throws ExecutionException 
 * @throws InterruptedException 
 */
protected Tuple2<Set<String>, Set<String>> loadSourcesAndBucketIdsByCommunityId(String communityId)
        throws InterruptedException, ExecutionException {
    Set<String> sourceIds = new HashSet<String>();
    Set<String> bucketIds = new HashSet<String>();
    ObjectId objecId = new ObjectId(communityId);
    Cursor<JsonNode> cursor = getSourceDb().getObjectsBySpec(CrudUtils.anyOf().when("communityIds", objecId))
            .get();

    for (Iterator<JsonNode> it = cursor.iterator(); it.hasNext();) {
        JsonNode source = it.next();
        String sourceId = source.get("_id").asText();
        sourceIds.add(sourceId);
        JsonNode extracType = source.get("extractType");
        if (extracType != null && "V2DataBucket".equalsIgnoreCase(extracType.asText())) {
            JsonNode bucketId = source.get("key");
            if (bucketId != null) {
                // TODO HACK , according to Alex, buckets have a semicolon as last id character to facilitate some string conversion 
                bucketIds.add(bucketId.asText() + ";");
            }
        }
        // bucket id
    }

    return new Tuple2<Set<String>, Set<String>>(sourceIds, bucketIds);
}

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

private JsonNode sendMessage(JsonNode command, JsonCallback callback) throws CommandException {
    JsonNode params = command.get(ScriptCommand.PARAMS);
    if (params == null || !params.isObject()) {
        throw new CommandParsingException(command, "missing parameters");
    }//from w ww  .  ja va2 s.  c  om

    JsonNode body = params.get("body");
    if (body == null || !body.isObject()) {
        throw new CommandParsingException(command, "missing body object parameter");
    }
    JsonNode messageNode = body.get("message");
    if (messageNode == null || !messageNode.isTextual()) {
        throw new CommandParsingException(command, "missing message text parameter");
    }
    String message = messageNode.asText();

    List<String> users = new ArrayList<>();
    JsonNode usersNode = params.get("to");
    if (usersNode == null || !usersNode.isArray()) {
        throw new CommandParsingException(command, "missing required to parameter");
    }
    ArrayNode usrAry = (ArrayNode) usersNode;
    usrAry.forEach(j -> {
        if (j == null || !j.isTextual())
            return;
        users.add(j.asText());
    });

    JsonNode profilesNode = params.get("profiles");
    List<Integer> profiles;
    if (profilesNode == null) {
        profiles = Collections.singletonList(1);
    } else if (profilesNode.isArray()) {
        ArrayNode pAry = (ArrayNode) profilesNode;
        profiles = new ArrayList<>();
        pAry.forEach((j) -> {
            if (j == null || !j.isIntegralNumber())
                return;
            profiles.add(j.asInt());
        });
    } else {
        throw new CommandParsingException(command, "wrong profiles parameter");
    }

    boolean[] errors = new boolean[users.size()];
    PushService ps = new PushService();

    try {
        ps.send(message, users, profiles, body, errors);
        Json.ObjectMapperExt mapper = Json.mapper();
        boolean someOk = false;
        boolean someFail = false;
        for (boolean error : errors) {
            if (error)
                someFail = true;
            else
                someOk = true;
        }
        if (someFail && someOk) {
            return IntNode.valueOf(1);
        } else if (someFail) {
            return IntNode.valueOf(2);
        } else {
            return IntNode.valueOf(0);
        }
    } catch (Exception e) {
        throw new CommandExecutionException(command, ExceptionUtils.getMessage(e), e);
    }
}

From source file:org.ihtsdo.otf.refset.security.RefsetIdentityService.java

protected UserDetails authenticate(String userName, String token) {

    LOGGER.debug("Authenticating user {} ", userName);

    User user = getGuestUser();/*from   w  w  w .ja  v  a2 s  . c om*/

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("username", userName);
    params.add("password", token);
    params.add("queryName", "getUserByNameAuth");

    try {

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(token)) {

            throw new AccessDeniedException("User is unauthorized. Please check user name and password");
        }
        Assert.notNull(rt, "Rest template can not be empty");

        LOGGER.debug("Calling authentication service with URL {}, User {} and Parameters {} ", otfServiceUrl,
                userName);

        JsonNode obj = rt.postForObject(otfServiceUrl, params, JsonNode.class);

        LOGGER.debug("authentication service call successfully returned with {} ", obj);

        //populate user with other user details
        populateUser(user, obj);

        //now check if user has access to Refset app.
        params = new LinkedMultiValueMap<String, String>();
        params.add("username", userName);
        params.add("queryName", "getUserApps");

        LOGGER.debug("Calling autorization service with URL {}, User {} and Parameters {} ", otfServiceUrl,
                userName);

        JsonNode appJson = rt.postForObject(otfServiceUrl, params, JsonNode.class);

        LOGGER.debug("autorization service call successfully returned with {} ", appJson);

        JsonNode apps = appJson.get("apps");
        Collection<RefsetRole> roles = new ArrayList<RefsetRole>();

        for (JsonNode object : apps) {

            if (object != null && object.asText().equals(APP_NAME)) {

                RefsetRole role = new RefsetRole();
                role.setAuthority(ROLE_USER);
                roles.add(role);
                break;
            }
        }
        user.setAuthorities(roles);

        if (isUserHasRole(user)) {

            String info = userName + ":" + token;
            Token key = service.allocateToken(info);
            user.setToken(key.getKey());
        }

    } catch (Exception e) {

        LOGGER.error("Error during authentication for user:password - {} ", userName + ":" + token, e);

        throw new AccessDeniedException("User is unauthorized. Please check user name and password");
    }

    return user;

}