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.jaredjstewart.SampleSecurityManager.java

private Map<String, Role> readRoles(final JsonNode jsonNode) {
    if (jsonNode.get("roles") == null) {
        return Collections.EMPTY_MAP;
    }/*w  w w . java  2  s  . co  m*/
    Map<String, Role> roleMap = new HashMap<>();
    for (JsonNode rolesNode : jsonNode.get("roles")) {
        Role role = new Role();
        role.name = rolesNode.get("name").asText();
        String regionNames = null;
        String keys = null;

        JsonNode regionsNode = rolesNode.get("regions");
        if (regionsNode != null) {
            if (regionsNode.isArray()) {
                regionNames = StreamSupport.stream(regionsNode.spliterator(), false).map(JsonNode::asText)
                        .collect(Collectors.joining(","));
            } else {
                regionNames = regionsNode.asText();
            }
        }

        for (JsonNode operationsAllowedNode : rolesNode.get("operationsAllowed")) {
            String[] parts = operationsAllowedNode.asText().split(":");
            String resourcePart = (parts.length > 0) ? parts[0] : null;
            String operationPart = (parts.length > 1) ? parts[1] : null;

            if (parts.length > 2) {
                regionNames = parts[2];
            }
            if (parts.length > 3) {
                keys = parts[3];
            }

            String regionPart = (regionNames != null) ? regionNames : "*";
            String keyPart = (keys != null) ? keys : "*";

            role.permissions.add(new ResourcePermission(resourcePart, operationPart, regionPart, keyPart));
        }

        roleMap.put(role.name, role);

        if (rolesNode.has("serverGroup")) {
            role.serverGroup = rolesNode.get("serverGroup").asText();
        }
    }

    return roleMap;
}

From source file:com.spankingrpgs.scarletmoon.loader.EventLoader.java

/**
 * Parses the passed JSON into an Event, and loads it into the specified state.
 *
 * @param eventData  The JSON representing the Event
 * @param state  The state to load the event into
 */// www.  j  a v  a 2  s  .  c  om
private void loadEvent(String eventData, GameState state) {
    try {
        List<JsonNode> eventList = parser.readValue(eventData, new TypeReference<List<JsonNode>>() {
        });
        for (JsonNode eventJson : eventList) {
            verifyFields(eventJson);
            String name = eventJson.get("name").asText();
            JsonNode eventBody = eventJson.get("text");
            String newLine = parser == JSON_PARSER ? TextParser.NEW_LINE_MARKER : "\n";
            Event event = eventFactory.build(
                    eventBody == null ? EventDescription.EMPTY_BODY
                            : TextParser.parse(eventBody.asText().trim().replace("''", "'"), newLine),
                    hydrateCommands(eventJson.get("do")),
                    hydrateAutomatedChoices(eventJson.get("automatic choices")),
                    hydrateChoices(eventJson.get("choices")),
                    loadMusic ? hydrateMusic(eventJson.get("music")) : null);
            state.addEvent(name, event);
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, e.getMessage());
        throw new IllegalArgumentException(e);
    }
}

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

private String getAuthorOverride(JsonNode command) throws CommandParsingException {
    JsonNode node = command.get(ScriptCommand.PARAMS).get(AUTHOR);
    if (node != null && !node.isTextual()) {
        throw new CommandParsingException(command, "author must be a string");

    } else if (node != null) {
        return node.asText();
    }/*from  w w w . ja va2 s  . c om*/
    return null;
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public PhysicalLink testBuildLink(JsonNode arg) throws Exception {
    if (arg == null)
        return null;

    PhysicalLink physicalLink = mock(PhysicalLink.class);
    JsonNode jsonNode = mock(JsonNode.class);
    JsonNode jsonNode1 = mock(JsonNode.class);

    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildLink", new Class[] { JsonNode.class });
    method.setAccessible(true);//from  w  ww  .  j  ava  2 s  .  c  om

    when(jsonNode.get(any(String.class))).thenReturn(jsonNode1).thenReturn(jsonNode1);
    when(jsonNode1.asText()).thenReturn(new String("test"));
    when(jsonNode1.asLong()).thenReturn((long) 1);

    physicalLink = (PhysicalLink) method.invoke(phyConfigLoader, jsonNode);
    Assert.assertTrue(physicalLink != null);
    Assert.assertTrue(physicalLink != mock(PhysicalLink.class));

    return physicalLink;
}

From source file:com.pros.jsontransform.ObjectTransformer.java

public JsonNode transformValueNode(final JsonNode sourceNode, final JsonNode transformNode)
        throws ObjectTransformerException {
    JsonNode resultNode = sourceNode;//from   w  w w.j a  v  a2 s . c  om

    // use $value to determine transformed value
    JsonNode valuePath = transformNode.get(VALUE);
    if (valuePath != null) {
        String valuePathAsString = valuePath.asText();
        if (!valuePathAsString.equalsIgnoreCase(PATH_DOT)) {
            // $value contains a path to a source node
            resultNode = updateSourceFromPath(sourceNode, valuePath);
            restoreSourceFromPath(sourceNode, valuePath);
        }
    }

    return resultNode;
}

From source file:org.apache.solr.kelvin.testcases.SimpleCondition.java

public List<ConditionFailureTestEvent> verifyConditions(ITestCase testCase, Properties queryParams,
        Map<String, Object> decodedResponses, Object testSpecificArgument) {
    List<ConditionFailureTestEvent> ret = new ArrayList<ConditionFailureTestEvent>();
    ArrayNode results = new ArrayNode(null);
    if (decodedResponses.containsKey(XmlDoclistExtractorResponseAnalyzer.DOC_LIST)) {
        results = (ArrayNode) decodedResponses.get(XmlDoclistExtractorResponseAnalyzer.DOC_LIST);
    }/*from w ww  .ja  v  a 2  s  .com*/
    int lengthToCheck = getLengthToCheck(results);
    for (int i = 0; i < lengthToCheck; i++) {
        if (results.size() <= i) {
            ret.add(new MissingResultTestEvent(testCase, queryParams, "result set too short", i));
        } else {
            JsonNode row = results.get(i);
            boolean allFields = true;
            for (String field : this.fields) {
                if (!hasField(row, field)) {
                    ret.add(new MissingFieldTestEvent(testCase, queryParams,
                            "missing field from result - " + field, i));
                    allFields = false;
                }
            }
            if (allFields) {
                String allText = "";
                for (String field : fields) {
                    JsonNode fieldValue = getField(row, field);
                    if (fieldValue.isArray()) {
                        for (int j = 0; j < fieldValue.size(); j++) {
                            allText = allText + " " + fieldValue.get(j);
                        }
                        //checkAllWords(testCase, queryParams, ret, i,
                        //      allText);

                    } else {
                        String stringFieldValue = fieldValue.asText();
                        allText = allText + " " + stringFieldValue;
                    }
                }
                checkAllWords(testCase, queryParams, ret, i, allText);
            }
        }
    }
    return ret;
}

From source file:org.createnet.raptor.models.data.types.NumberRecord.java

@Override
public Number parseValue(Object value) {
    try {// w  w  w .  j  ava  2 s.  co m

        if (value instanceof Number) {
            return (Number) value;
        }

        if (value instanceof JsonNode) {

            JsonNode node = (JsonNode) value;

            if (node.isNumber()) {

                if (node.isInt() || node.isShort()) {
                    return (Number) node.asInt();
                }

                if (node.isDouble() || node.isFloat()) {
                    return (Number) node.asDouble();
                }

                if (node.isLong()) {
                    return (Number) node.asLong();
                }
            }

            if (node.isTextual()) {
                value = node.asText();
            }

        }

        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition pos = new ParsePosition(0);
        Number numVal = formatter.parse((String) value, pos);

        return numVal;
    } catch (Exception e) {
        throw new RaptorComponent.ParserException(e);
    }
}

From source file:com.redhat.lightblue.metadata.parser.JSONMetadataParser.java

@Override
public Object getValueProperty(JsonNode object, String name) {
    Error.push(name);/*from  w  w w  .  jav  a  2s.c  o  m*/
    try {
        JsonNode x = object.get(name);
        if (x != null) {
            if (x.isValueNode()) {
                if (x.isNumber()) {
                    return x.numberValue();
                } else if (x.isBoolean()) {
                    return x.booleanValue();
                } else {
                    return x.asText();
                }
            } else {
                throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, name);
            }
        } else {
            return null;
        }
    } catch (Error e) {
        // rethrow lightblue error
        throw e;
    } catch (Exception e) {
        // throw new Error (preserves current error context)
        LOGGER.error(e.getMessage(), e);
        throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, e.getMessage());
    } finally {
        Error.pop();
    }
}

From source file:com.spotify.helios.testing.TemporaryJobBuilder.java

private TemporaryJobBuilder imageFromInfoJson(final String json, final String source) {
    try {//from   ww  w. j  a  v a 2  s  . c  o m
        final JsonNode info = Json.readTree(json);
        final JsonNode imageNode = info.get("image");
        if (imageNode == null) {
            fail("Missing image field in image info: " + source);
        }
        if (imageNode.getNodeType() != STRING) {
            fail("Bad image field in image info: " + source);
        }
        final String image = imageNode.asText();
        return image(image);
    } catch (IOException e) {
        throw new AssertionError("Failed to parse image info: " + source, e);
    }
}