Example usage for com.fasterxml.jackson.databind.node ObjectNode size

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode size

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode size.

Prototype

public int size() 

Source Link

Usage

From source file:com.redhat.lightblue.query.ArrayAddExpression.java

/**
 * Parses an array update expression using the given json object
 *///from ww  w .ja v a 2  s .  c om
public static ArrayAddExpression fromJson(ObjectNode node) {
    if (node.size() == 1) {
        UpdateOperator op = UpdateOperator._append;
        JsonNode arg = node.get(UpdateOperator._append.toString());
        if (arg == null) {
            arg = node.get(UpdateOperator._insert.toString());
            op = UpdateOperator._insert;
        }
        if (arg instanceof ObjectNode) {
            ObjectNode objArg = (ObjectNode) arg;
            if (objArg.size() == 1) {
                Map.Entry<String, JsonNode> item = objArg.fields().next();
                Path field = new Path(item.getKey());
                JsonNode valueNode = item.getValue();
                List<RValueExpression> rvalues = new ArrayList<>();
                if (valueNode instanceof ArrayNode) {
                    for (Iterator<JsonNode> itr = ((ArrayNode) valueNode).elements(); itr.hasNext();) {
                        rvalues.add(RValueExpression.fromJson(itr.next()));
                    }
                } else {
                    rvalues.add(RValueExpression.fromJson(valueNode));
                }
                return new ArrayAddExpression(field, op, rvalues);
            }
        }
    }
    throw Error.get(QueryConstants.ERR_INVALID_ARRAY_UPDATE_EXPRESSION, node.toString());
}

From source file:com.redhat.smonkey.Utils.java

private static boolean objectToString(StringBuilder bld, ObjectNode node, int depth, boolean newLine) {
    if (newLine) {
        indent(bld, depth);// w  w  w  .j  a va 2  s  .  co  m
        newLine = false;
    }
    if (node.size() > 0) {
        bld.append("{\n");
        newLine = true;
    }
    boolean first = true;
    for (Iterator<Map.Entry<String, JsonNode>> itr = node.fields(); itr.hasNext();) {
        if (first) {
            first = false;
        } else {
            if (newLine) {
                indent(bld, depth);
                newLine = false;
            }
            bld.append(',');
            bld.append('\n');
            newLine = true;
        }
        Map.Entry<String, JsonNode> entry = itr.next();
        indent(bld, depth);
        bld.append('\"');
        bld.append(entry.getKey());
        bld.append('\"');
        bld.append(':');
        newLine = toString(bld, entry.getValue(), depth + 1, false);
        if (newLine) {
            indent(bld, depth);
            newLine = false;
        }
    }
    if (node.size() > 0) {
        bld.append('\n');
        newLine = true;
    }
    if (newLine) {
        indent(bld, depth);
        newLine = false;
    }
    bld.append('}');
    return false;
}

From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashConfigUtils.java

public static String validateLogstashInput(LogstashHarvesterConfigBean globals, String sourceKey, String config,
        StringBuffer errorMessage, boolean isAdmin) {

    _allowedInputs.addAll(Arrays.asList(globals.non_admin_inputs().toLowerCase().split("\\s*,\\s*")));
    _allowedFilters.addAll(Arrays.asList(globals.non_admin_filters().toLowerCase().split("\\s*,\\s*")));
    _allowedOutputs.addAll(Arrays.asList(globals.non_admin_outputs().toLowerCase().split("\\s*,\\s*")));

    // Configuration validation, phase 1

    errorMessage.append("Validation error:");
    ObjectNode jsonifiedConfig = parseLogstashConfig(config, errorMessage);
    if (null == jsonifiedConfig) {
        return null;
    }/*  w w  w  . j  a v a2 s.  c  o m*/
    errorMessage.setLength(0);

    // Configuration validation, phase 2 - very basic checks on the structure of the object

    Object input = jsonifiedConfig.get("input");
    if ((null == input) || !(input instanceof ObjectNode)) { // Does input exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (0)");
        return null;
    } //TESTED (3_1d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        ObjectNode inputDbo = (ObjectNode) input;
        if (1 != inputDbo.size()) {
            errorMessage.append(
                    "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (1)");
            return null;
        } //TESTED
        if (!isAdmin) {
            for (String key : (Iterable<String>) () -> inputDbo.fieldNames()) {
                if (!_allowedInputs.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed input type " + key
                            + ", allowed options: " + _allowedInputs.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_1abc)
    }
    Object filter = jsonifiedConfig.get("filter");
    if ((null == filter) || !(filter instanceof ObjectNode)) { // Does filter exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (2)");
        return null;
    } //TESTED (3_2d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        if (!isAdmin) {
            ObjectNode filterDbo = (ObjectNode) filter;
            for (String key : (Iterable<String>) () -> filterDbo.fieldNames()) {
                if (!_allowedFilters.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed filter type " + key
                            + ", allowed options: " + _allowedFilters.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_2abc)
    }

    //TODO: same for output

    // Configuration validation, phase 3

    Matcher m = null;
    m = _validationRegexInputReplace.matcher(config);
    if (!m.find()) {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (3)");
        return null;
    } //TESTED (see above)
    else { // If admin check on allowed types
        String inputType = m.group(2).toLowerCase();

        // If it's a file-based plugin then replace sincedb_path (check that it's not used during the JSON-ification):
        if (inputType.equalsIgnoreCase("file")) {
            config = _validationRegexInputReplace.matcher(config)
                    .replaceFirst("$1\n      sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n");
        } else if (inputType.equalsIgnoreCase("s3")) {
            config = _validationRegexInputReplace.matcher(config).replaceFirst(
                    "$1\n      sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n      temporary_directory => \"_XXX_LSTEMPDIR_XXX_\"");
        }

    } //TESTED

    m = _validationRegexNoSourceKey.matcher(config);
    // (this won't help malicious changes to source key, but will let people know they're not supposed to)
    if (m.find()) {
        errorMessage.append(
                "Not allowed to reference sourceKey - this is automatically appended by the logstash harvester");
        return null;
    } //TESTED      

    // OK now need to append the sourceKey at each stage of the pipeline to really really ensure that nobody sets sourceKey to be different 

    m = _validationRegexAppendFields.matcher(config);
    StringBuffer newConfig = new StringBuffer();
    if (m.find()) {
        m.appendReplacement(newConfig, "add_field => [  \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] \n\n"
                + m.group() + " \n if [@metadata][sourceKey] == \"" + sourceKey + "\" { \n\n ");
    } else {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (4)");
        return null;
    }
    m.appendTail(newConfig);
    config = newConfig.toString();
    config = config.replaceAll("}[^}]*$", ""); // (remove the last })
    config += "\n\n mutate { update => [ \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] } \n}\n}\n"; // double check the sourceKey hasn't been overwritten and close the if from above
    //TESTED (syntactically correct and does overwrite sourceKey everywhere - success_2_2)

    return config;
}

From source file:com.redhat.lightblue.util.JsonUtils.java

private static boolean objectToString(StringBuilder bld, ObjectNode node, int depth, boolean newLine) {
    if (newLine) {
        indent(bld, depth);/*from  w  w w  .  j  a  va  2s  . c o  m*/
        newLine = false;
    }
    bld.append('{');
    if (node.size() > 0) {
        bld.append("\n");
        newLine = true;
    }
    boolean first = true;
    for (Iterator<Map.Entry<String, JsonNode>> itr = node.fields(); itr.hasNext();) {
        if (first) {
            first = false;
        } else {
            if (newLine) {
                indent(bld, depth);
            }
            bld.append(',');
            bld.append('\n');
        }
        Map.Entry<String, JsonNode> entry = itr.next();
        indent(bld, depth);
        bld.append('\"');
        bld.append(entry.getKey());
        bld.append('\"');
        bld.append(':');
        newLine = toString(bld, entry.getValue(), depth + 1, false);
        if (newLine) {
            indent(bld, depth);
            newLine = false;
        }
    }
    if (node.size() > 0) {
        bld.append('\n');
        newLine = true;
    }
    if (newLine) {
        indent(bld, depth);
    }
    bld.append('}');
    return false;
}

From source file:com.almende.eve.protocol.jsonrpc.formats.Params.java

/**
 * Instantiates a new params./* w w  w. ja v  a  2  s .c o  m*/
 *
 * @param node
 *            the node
 */
public Params(final ObjectNode node) {
    super(JOM.getInstance().getNodeFactory(),
            new LinkedHashMap<String, JsonNode>(node != null ? node.size() : 2));
    if (node != null) {
        this.setAll(node);
    }
}

From source file:org.openremote.server.catalog.NodeDescriptor.java

public Node initialize(Node node) {

    List<Slot> slots = new ArrayList<>();
    addSlots(slots);//from  w ww. j  ava2s  .  com
    node.setSlots(slots.toArray(new Slot[slots.size()]));

    node.getEditorSettings().setTypeLabel(getTypeLabel());
    node.getEditorSettings().setNodeColor(getColor());

    List<String> editorComponents = new ArrayList<>();
    addEditorComponents(editorComponents);
    node.getEditorSettings().setComponents(editorComponents.toArray(new String[editorComponents.size()]));

    Object initialProperties = getInitialProperties();
    try {
        if (initialProperties != null) {
            node.setProperties(JSON.writeValueAsString(initialProperties));
        } else {
            ObjectNode properties = JSON.createObjectNode();
            configureInitialProperties(properties);
            if (properties.size() > 0) {
                node.setProperties(JSON.writeValueAsString(properties));
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Error writing initial properties of: " + getType(), ex);
    }

    List<String> persistentPaths = new ArrayList<>();
    addPersistentPropertyPaths(persistentPaths);
    if (persistentPaths.size() > 0) {
        node.setPersistentPropertyPaths(persistentPaths.toArray(new String[persistentPaths.size()]));
    }

    return node;
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitTraceInputHandler.java

protected ObjectName metaObjectName(final JsonNode node) {
    try {/*from   w ww . j  a v a2  s .com*/
        final String metric = node.get("Metric").textValue();
        final ObjectNode tags = (ObjectNode) node.get("Tags");
        if (tags != null && tags.size() > 0) {
            Map<String, String> t = new HashMap<String, String>(tags.size());
            for (Iterator<String> n = tags.fieldNames(); n.hasNext();) {
                final String key = n.next();
                final String value = tags.get(key).asText();
                t.put(key, value);
            }
            return toHostObjectName(JMXHelper.objectName(metric, t));
            //            return JMXHelper.objectName(metric, t);
        } else {
            return JMXHelper.objectName(toHostObjectName(JMXHelper.objectName(metric + ":*")).toString());
            //            return JMXHelper.objectName(metric + ":type=static");
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.heliosapm.tsdblite.handlers.json.SplitTraceInputHandler.java

protected String metaObject(final JsonNode node) {
    try {/*w  w w  .ja va2 s . co m*/
        final String metric = node.get("Metric").textValue();
        final ObjectNode tags = (ObjectNode) node.get("Tags");
        if (tags != null && tags.size() > 0) {
            Map<String, String> t = new HashMap<String, String>(tags.size());
            for (Iterator<String> n = tags.fieldNames(); n.hasNext();) {
                final String key = n.next();
                final String value = tags.get(key).asText();
                t.put(key, value);
            }
            return metric + ":" + t;
            //            return JMXHelper.objectName(metric, t);
        } else {
            return metric + ":*";
            //            return JMXHelper.objectName(toHostObjectName(JMXHelper.objectName(metric + ":*")).toString());            
            //            return JMXHelper.objectName(metric + ":type=static");
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.google.api.server.spi.EndpointsServletTest.java

@Test
public void echo() throws IOException {
    req.setRequestURI("/_ah/api/test/v2/echo");
    req.setMethod("POST");
    req.setParameter("x", "1");

    servlet.service(req, resp);/* w  w  w.j  a  va  2  s .c  o  m*/

    assertThat(resp.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
    ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper();
    ObjectNode actual = mapper.readValue(resp.getContentAsString(), ObjectNode.class);
    assertThat(actual.size()).isEqualTo(1);
    assertThat(actual.get("x").asInt()).isEqualTo(1);
}

From source file:com.github.fge.jsonschema.matchers.ProcessingMessageAssert.java

public ProcessingMessageAssert hasContents(final ObjectNode node) {
    /*/*from  w  ww.  j  a  va 2  s .  c  o m*/
     * No need to check if the map is empty
     */
    if (node.size() == 0)
        return this;

    /*
     * Grab the two nodes as maps
     */
    final Map<String, JsonNode> expectedMap = JacksonUtils.asMap(msg);
    final Map<String, JsonNode> actualMap = JacksonUtils.asMap(node);

    /*
     * Check that this message's map contains all keys of the wanted data
     */
    assertTrue(expectedMap.keySet().containsAll(actualMap.keySet()));

    /*
     * OK? Let's check contents with Map.equals().
     */
    expectedMap.keySet().retainAll(actualMap.keySet());
    assertEquals(actualMap, expectedMap, "different map contents");
    return this;
}