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

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

Introduction

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

Prototype

public String textValue() 

Source Link

Usage

From source file:de.fhg.fokus.odp.registry.ckan.ODRClientImpl.java

/**
 * ACHTUNG!!!<br/>/*from   www.  j a  va 2  s .  co m*/
 * Die Methode sollte nur mit bedacht genutzt werden, da Abfragen an eine CKAN-Instanz mit sehr
 * vielen Datenstzen sehr, sehr laaaaange dauern.
 */
@Override
@Deprecated
public List<Tag> getTagCounts() {
    List<Tag> tags = new ArrayList<Tag>();

    log.trace("REST > calling search api 'tag_counts' with nothing");
    long start = System.currentTimeMillis();
    JsonNode result = search.getTagCounts();
    log.debug("/api/2/tag_counts: {}ms", System.currentTimeMillis() - start);
    log.trace("REST < returns: {}", result);

    if (result != null && result.isArray()) {
        log.info("number of tags: {}", result.size());
        for (JsonNode node : result) {
            if (node.isArray()) {

                TagBean tag = new TagBean();
                TagImpl impl = new TagImpl(tag);
                for (JsonNode elem : node) {
                    if (elem.isTextual()) {
                        tag.setName(elem.textValue());
                    } else if (elem.isInt()) {
                        impl.setCount(elem.longValue());
                    }
                }
                tags.add(impl);
            }
        }
    }
    return tags;
}

From source file:org.apache.parquet.cli.json.AvroJson.java

private static boolean matches(JsonNode datum, Schema schema) {
    switch (schema.getType()) {
    case RECORD://from  w w w  . j  av  a  2 s  .co  m
        if (datum.isObject()) {
            // check that each field is present or has a default
            boolean missingField = false;
            for (Schema.Field field : schema.getFields()) {
                if (!datum.has(field.name()) && field.defaultValue() == null) {
                    missingField = true;
                    break;
                }
            }
            if (!missingField) {
                return true;
            }
        }
        break;
    case UNION:
        if (resolveUnion(datum, schema.getTypes()) != null) {
            return true;
        }
        break;
    case MAP:
        if (datum.isObject()) {
            return true;
        }
        break;
    case ARRAY:
        if (datum.isArray()) {
            return true;
        }
        break;
    case BOOLEAN:
        if (datum.isBoolean()) {
            return true;
        }
        break;
    case FLOAT:
        if (datum.isFloat() || datum.isInt()) {
            return true;
        }
        break;
    case DOUBLE:
        if (datum.isDouble() || datum.isFloat() || datum.isLong() || datum.isInt()) {
            return true;
        }
        break;
    case INT:
        if (datum.isInt()) {
            return true;
        }
        break;
    case LONG:
        if (datum.isLong() || datum.isInt()) {
            return true;
        }
        break;
    case STRING:
        if (datum.isTextual()) {
            return true;
        }
        break;
    case ENUM:
        if (datum.isTextual() && schema.hasEnumSymbol(datum.textValue())) {
            return true;
        }
        break;
    case BYTES:
    case FIXED:
        if (datum.isBinary()) {
            return true;
        }
        break;
    case NULL:
        if (datum == null || datum.isNull()) {
            return true;
        }
        break;
    default: // UNION or unknown
        throw new IllegalArgumentException("Unsupported schema: " + schema);
    }
    return false;
}

From source file:com.unboundid.scim2.server.utils.SchemaChecker.java

/**
 * Internal method to check a SCIM resource.
 *
 * @param prefix The issue prefix.//  w  ww. ja va 2 s. c om
 * @param objectNode The partial resource.
 * @param results The schema check results.
 * @param currentObjectNode The current resource.
 * @param isReplace Whether this is a replace.
 * @throws ScimException If an error occurs.
 */
private void checkResource(final String prefix, final ObjectNode objectNode, final Results results,
        final ObjectNode currentObjectNode, final boolean isReplace) throws ScimException {
    // Iterate through the schemas
    JsonNode schemas = objectNode.get(SchemaUtils.SCHEMAS_ATTRIBUTE_DEFINITION.getName());
    if (schemas != null && schemas.isArray()) {
        boolean coreFound = false;
        for (JsonNode schema : schemas) {
            if (!schema.isTextual()) {
                // Go to the next one if the schema URI is not valid. We will report
                // this issue later when we check the values for the schemas
                // attribute.
                continue;
            }

            // Get the extension namespace object node.
            JsonNode extensionNode = objectNode.remove(schema.textValue());
            if (extensionNode == null) {
                // Extension listed in schemas but no namespace in resource. Treat it
                // as an empty namesapce to check for required attributes.
                extensionNode = JsonUtils.getJsonNodeFactory().objectNode();
            }
            if (!extensionNode.isObject()) {
                // Go to the next one if the extension namespace is not valid
                results.syntaxIssues.add(prefix + "Extended attributes namespace " + schema.textValue()
                        + " must be a JSON object");
                continue;
            }

            // Find the schema definition.
            Map.Entry<SchemaResource, Boolean> extensionDefinition = null;
            if (schema.textValue().equals(resourceType.getCoreSchema().getId())) {
                // Skip the core schema.
                coreFound = true;
                continue;
            } else {
                for (Map.Entry<SchemaResource, Boolean> schemaExtension : resourceType.getSchemaExtensions()
                        .entrySet()) {
                    if (schema.textValue().equals(schemaExtension.getKey().getId())) {
                        extensionDefinition = schemaExtension;
                        break;
                    }
                }
            }

            if (extensionDefinition == null) {
                // Bail if we can't find the schema definition. We will report this
                // issue later when we check the values for the schemas attribute.
                continue;
            }

            checkObjectNode(prefix, Path.root(schema.textValue()), extensionDefinition.getKey().getAttributes(),
                    (ObjectNode) extensionNode, results, currentObjectNode, isReplace, false, isReplace);
        }

        if (!coreFound) {
            // Make sure core schemas was included.
            results.syntaxIssues.add(prefix + "Value for attribute schemas must " + " contain schema URI "
                    + resourceType.getCoreSchema().getId()
                    + " because it is the core schema for this resource type");
        }

        // Make sure all required extension schemas were included.
        for (Map.Entry<SchemaResource, Boolean> schemaExtension : resourceType.getSchemaExtensions()
                .entrySet()) {
            if (schemaExtension.getValue()) {
                boolean found = false;
                for (JsonNode schema : schemas) {
                    if (schema.textValue().equals(schemaExtension.getKey().getId())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    results.syntaxIssues.add(prefix + "Value for attribute schemas "
                            + "must contain schema URI " + schemaExtension.getKey().getId()
                            + " because it is a required schema extension for this " + "resource type");
                }
            }
        }
    }

    // All defined schema extensions should be removed.
    // Remove any additional extended attribute namespaces not included in
    // the schemas attribute.
    Iterator<Map.Entry<String, JsonNode>> i = objectNode.fields();
    while (i.hasNext()) {
        String fieldName = i.next().getKey();
        if (SchemaUtils.isUrn(fieldName)) {
            results.syntaxIssues.add(prefix + "Extended attributes namespace " + fieldName
                    + " must be included in the schemas attribute");
            i.remove();
        }
    }

    // Check common and core schema
    checkObjectNode(prefix, Path.root(), commonAndCoreAttributes, objectNode, results, currentObjectNode,
            isReplace, false, isReplace);
}

From source file:io.swagger.parser.util.SwaggerDeserializer.java

public List<String> tagStrings(ArrayNode nodes, String location, ParseResult result) {
    if (nodes == null)
        return null;

    List<String> output = new ArrayList<String>();

    for (JsonNode node : nodes) {
        if (node.getNodeType().equals(JsonNodeType.STRING)) {
            output.add(node.textValue());
        }//from   w  w  w  . j a  va  2  s.co m
    }
    return output;
}

From source file:com.addthis.codec.jackson.CodecBeanDeserializer.java

private void handleDefaultsAndRequiredAndNull(DeserializationContext ctxt, ObjectNode fieldValues)
        throws JsonMappingException {
    Iterator<SettableBeanProperty> propertyIterator = getDelegatee().properties();
    while (propertyIterator.hasNext()) {
        SettableBeanProperty prop = propertyIterator.next();
        String propertyName = prop.getName();
        JsonNode fieldValue = fieldValues.path(propertyName);
        if (fieldValue.isMissingNode() || fieldValue.isNull()) {
            if (fieldDefaults.hasNonNull(propertyName)) {
                fieldValue = fieldDefaults.get(propertyName).deepCopy();
                fieldValues.set(propertyName, fieldValue);
            } else if (prop.isRequired()) {
                throw MissingPropertyException.from(ctxt.getParser(), prop.getType().getRawClass(),
                        propertyName, getKnownPropertyNames());
            } else if (fieldValue.isNull()
                    && (prop.getType().isPrimitive() || (prop.getValueDeserializer().getNullValue() == null))) {
                // don't overwrite possible hard-coded defaults/ values with nulls unless they are fancy
                fieldValues.remove(propertyName);
            }/* ww w.  j  ava  2s .co m*/
        }
        if (fieldValue.isTextual()) {
            try {
                // sometimes we erroneously get strings that would parse into valid numbers and maybe other edge
                // cases (eg. when using system property overrides in typesafe-config). So we'll go ahead and guard
                // with this regex to make sure we only get reasonable candidates.
                Time time = prop.getAnnotation(Time.class);
                if ((time != null) && NUMBER_UNIT.matcher(fieldValue.textValue()).matches()) {
                    Duration dropWizardDuration = Duration.parse(fieldValue.asText());
                    long asLong = time.value().convert(dropWizardDuration.getQuantity(),
                            dropWizardDuration.getUnit());
                    fieldValues.put(propertyName, asLong);
                } else if ((prop.getAnnotation(Bytes.class) != null)
                        && NUMBER_UNIT.matcher(fieldValue.textValue()).matches()) {
                    Size dropWizardSize = Size.parse(fieldValue.asText());
                    long asLong = dropWizardSize.toBytes();
                    fieldValues.put(propertyName, asLong);
                }
            } catch (Throwable cause) {
                throw JsonMappingException.wrapWithPath(cause, prop.getType().getRawClass(), propertyName);
            }
        }
    }
}

From source file:io.swagger.parser.util.SwaggerDeserializer.java

public Parameter parameter(ObjectNode obj, String location, ParseResult result) {
    if (obj == null) {
        return null;
    }//  w  ww.  j  a va  2 s  .co  m

    Parameter output = null;
    JsonNode ref = obj.get("$ref");
    if (ref != null) {
        if (ref.getNodeType().equals(JsonNodeType.STRING)) {
            return refParameter((TextNode) ref, location, result);
        } else {
            result.invalidType(location, "$ref", "string", obj);
            return null;
        }
    }

    String l = null;
    JsonNode ln = obj.get("name");
    if (ln != null) {
        l = ln.asText();
    } else {
        l = "['unknown']";
    }
    location += ".[" + l + "]";

    String value = getString("in", obj, true, location, result);
    if (value != null) {
        String type = getString("type", obj, false, location, result);
        String format = getString("format", obj, false, location, result);
        AbstractSerializableParameter<?> sp = null;
        if ("query".equals(value)) {
            sp = new QueryParameter();
        } else if ("header".equals(value)) {
            sp = new HeaderParameter();
        } else if ("path".equals(value)) {
            sp = new PathParameter();
        } else if ("formData".equals(value)) {
            sp = new FormParameter();
        }

        if (sp != null) {
            // type is mandatory when sp != null
            getString("type", obj, true, location, result);
            Map<PropertyBuilder.PropertyId, Object> map = new HashMap<PropertyBuilder.PropertyId, Object>();

            map.put(TYPE, type);
            map.put(FORMAT, format);
            String defaultValue = getString("default", obj, false, location, result);
            map.put(DEFAULT, defaultValue);
            sp.setDefault(defaultValue);

            Double dbl = getDouble("maximum", obj, false, location, result);
            if (dbl != null) {
                map.put(MAXIMUM, dbl);
                sp.setMaximum(dbl);
            }

            Boolean bl = getBoolean("exclusiveMaximum", obj, false, location, result);
            if (bl != null) {
                map.put(EXCLUSIVE_MAXIMUM, bl);
                sp.setExclusiveMaximum(bl);
            }

            dbl = getDouble("minimum", obj, false, location, result);
            if (dbl != null) {
                map.put(MINIMUM, dbl);
                sp.setMinimum(dbl);
            }

            bl = getBoolean("exclusiveMinimum", obj, false, location, result);
            if (bl != null) {
                map.put(EXCLUSIVE_MINIMUM, bl);
                sp.setExclusiveMinimum(bl);
            }

            map.put(MAX_LENGTH, getInteger("maxLength", obj, false, location, result));
            map.put(MIN_LENGTH, getInteger("minLength", obj, false, location, result));

            String pat = getString("pattern", obj, false, location, result);
            map.put(PATTERN, pat);
            sp.setPattern(pat);

            Integer iv = getInteger("maxItems", obj, false, location, result);
            map.put(MAX_ITEMS, iv);
            sp.setMaxItems(iv);

            iv = getInteger("minItems", obj, false, location, result);
            map.put(MIN_ITEMS, iv);
            sp.setMinItems(iv);

            map.put(UNIQUE_ITEMS, getBoolean("uniqueItems", obj, false, location, result));

            ArrayNode an = getArray("enum", obj, false, location, result);
            if (an != null) {
                List<String> _enum = new ArrayList<String>();
                for (JsonNode n : an) {
                    _enum.add(n.textValue());
                }
                sp.setEnum(_enum);
                map.put(ENUM, _enum);
            }

            Property prop = PropertyBuilder.build(type, format, map);

            if (prop != null) {
                sp.setProperty(prop);
                ObjectNode items = getObject("items", obj, false, location, result);
                if (items != null) {
                    Property inner = schema(null, items, location, result);
                    sp.setItems(inner);
                }
            }

            Set<String> keys = getKeys(obj);
            for (String key : keys) {
                if (key.startsWith("x-")) {
                    sp.setVendorExtension(key, extension(obj.get(key)));
                } else if (!PARAMETER_KEYS.contains(key)) {
                    result.extra(location, key, obj.get(key));
                }
            }

            String collectionFormat = getString("collectionFormat", obj, false, location, result);
            sp.setCollectionFormat(collectionFormat);

            output = sp;
        } else if ("body".equals(value)) {
            output = Json.mapper().convertValue(obj, Parameter.class);
        }
        if (output != null) {
            value = getString("name", obj, true, location, result);
            output.setName(value);

            value = getString("description", obj, false, location, result);
            output.setDescription(value);

            Boolean required = getBoolean("required", obj, false, location, result);
            if (required != null) {
                output.setRequired(required);
            }
        }
    }

    return output;
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGenerator.java

@VisibleForTesting
protected String getSchemaType(URI type, SchemaTree schema) throws CodeGenerationException {
    String schemaType;//from  w  ww .  j a v  a 2  s . c  o  m
    JsonNode schemaTypeNode = schema.getNode().get("type");
    if (schemaTypeNode == null) {
        // check whether it is a oneOf/anyOf/allOf
        Set<String> aggregationTypes = new HashSet<>();
        if (schema.getNode().hasNonNull("allOf")) {
            aggregationTypes.add("allOf");
        }
        if (schema.getNode().hasNonNull("anyOf")) {
            aggregationTypes.add("anyOf");
        }
        if (schema.getNode().hasNonNull("oneOf")) {
            aggregationTypes.add("oneOf");
        }

        if (aggregationTypes.size() > 1) {
            throw new CodeGenerationException(type,
                    "Cannot combine multiple aggregation types, found " + aggregationTypes);
        } else if (aggregationTypes.size() == 1) {
            schemaType = aggregationTypes.iterator().next();
        } else {
            // XXX: is assuming "object" ok here, or should this be fatal?
            logger.warn("{}: Missing type keyword, assuming 'object'", type);
            schemaType = "object";
        }
    } else {
        schemaType = schemaTypeNode.textValue();
    }
    return schemaType;
}

From source file:com.mapr.data.sputnik.log.Log4JLogger.java

public void printAll(String name, JsonNode node) {
    if (!node.isValueNode()) {
        Iterator<String> fieldNames = node.fieldNames();
        System.out.print("{ ");
        while (fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode fieldValue = node.get(fieldName);
            if (fieldValue.isArray()) {
                System.out.print(fieldName + " [ ");
                List<String> a = new ArrayList<>(1);
                Iterator<JsonNode> itr = fieldValue.iterator();
                while (itr.hasNext()) {
                    JsonNode n = itr.next();
                    printAll(fieldName, n);
                    System.out.print(", ");
                }//from   ww w . j  ava2s  .co  m
                System.out.print(" ] ");
            } else {
                printAll(fieldName, fieldValue);
                System.out.print(", ");
            }
        }
        System.out.print(" } ");
    } else {
        Iterator<Entry<String, JsonNode>> itParams = node.fields();
        while (itParams.hasNext()) {
            Entry<String, JsonNode> elt = itParams.next();
            System.out.println(elt.getKey());
        }
        if (node.isInt()) {
            System.out.print(name + " : " + node.intValue());
        } else if (node.isDouble()) {
            System.out.print(name + " : " + node.doubleValue());
        } else if (node.isTextual()) {
            System.out.print(name + " : " + node.textValue());
        } else if (node.isLong()) {
            System.out.print(name + " : " + node.longValue());
        } else
            System.out.print(name + " : " + node.textValue());

    }

}

From source file:com.discover.cls.processors.cls.JSONToAttributes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/* w w w.jav a2 s . c om*/
    if (flowFile == null) {
        return;
    }

    final String flattenJsonSeparator = context.getProperty(FLATTEN_JSON_SEPARATOR).getValue();
    final boolean flattenJson = context.getProperty(FLATTEN_JSON).asBoolean();
    final boolean flattenJsonArrays = context.getProperty(FLATTEN_JSON_ARRAYS).asBoolean();
    final String attributeNameFromProperty = context.getProperty(JSON_ATTRIBUTE_NAME)
            .evaluateAttributeExpressions().getValue();
    final String attributeContent = flowFile.getAttribute(attributeNameFromProperty);
    final byte[] content = getContent(session, flowFile, attributeNameFromProperty, attributeContent);
    final boolean toOverride = context.getProperty(OVERRIDE_ATTRIBUTES).asBoolean();
    final boolean preserveType = context.getProperty(PRESERVE_TYPE).asBoolean();

    if (attributeNameFromProperty != null && !"".equals(attributeNameFromProperty)
            && attributeContent == null) {
        getLogger().error(JSON_ATTRIBUTE_NAME.getDisplayName() + " is defined, but the attribute '"
                + attributeNameFromProperty + "' does not exist.");
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    if (content == null || Arrays.equals(content, new byte[0])) {
        // No content. push through.
        getLogger().debug("No content is defined. Passing flow file to 'no content' relationship.");
        session.transfer(flowFile, REL_NO_CONTENT);
        return;
    }

    try {
        final JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        final Map<String, String> attributes = new LinkedHashMap<>();

        if (flattenJson) {
            addKeys("", jsonNode, flattenJsonSeparator, preserveType, flattenJsonArrays, attributes);
        } else {
            final Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                if (toOverride || flowFile.getAttribute(entry.getKey()) == null) {
                    JsonNode value = entry.getValue();
                    switch (value.getNodeType()) {
                    case ARRAY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BINARY:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case BOOLEAN:
                        attributes.put(entry.getKey(), Boolean.toString(value.asBoolean()));
                        break;
                    case MISSING:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NULL:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case NUMBER:
                        attributes.put(entry.getKey(), Long.toString(value.asLong()));
                        break;
                    case OBJECT:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case POJO:
                        attributes.put(entry.getKey(), value.toString());
                        break;
                    case STRING:
                        attributes.put(entry.getKey(), preserveType ? value.toString() : value.textValue());
                        break;
                    }
                }
            }
        }

        flowFile = session.putAllAttributes(flowFile, attributes);
        session.getProvenanceReporter().modifyAttributes(flowFile);
        session.transfer(flowFile, REL_SUCCESS);
    } catch (IOException e) {
        getLogger().error("Failed parsing JSON.", new Object[] { e });
        session.transfer(flowFile, REL_FAILURE);
    }
}