Java Code Examples for com.fasterxml.jackson.databind.JsonNode#isTextual()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isTextual() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BqDdlOperatorFactory.java    From digdag with Apache License 2.0 6 votes vote down vote up
private Table table(String defaultProjectId, Optional<DatasetReference> defaultDataset, JsonNode node)
{
    if (node.isTextual()) {
        return new Table()
                .setTableReference(Bq.tableReference(defaultProjectId, defaultDataset, node.asText()));
    }
    else {
        TableConfig config;
        try {
            config = objectMapper.readValue(node.traverse(), TableConfig.class);
        }
        catch (IOException e) {
            throw new ConfigException("Invalid table reference or configuration: " + node, e);
        }
        return table(defaultProjectId, defaultDataset, config);
    }
}
 
Example 2
Source File: JsonStringOrNodeExpander.java    From samantha with MIT License 6 votes vote down vote up
public List<ObjectNode> expand(List<ObjectNode> initialResult,
                               RequestContext requestContext) {
    List<ObjectNode> expanded = new ArrayList<>();
    for (ObjectNode entity : initialResult) {
        JsonNode json = entity.get(jsonAttr);
        if (json.isTextual()) {
            json = Json.parse(json.asText());
        }
        if (json.isArray()) {
            for (JsonNode one : json) {
                ObjectNode newEntity = entity.deepCopy();
                IOUtilities.parseEntityFromJsonNode(one, newEntity);
                expanded.add(newEntity);
            }
        } else {
            IOUtilities.parseEntityFromJsonNode(json, entity);
            expanded.add(entity);
        }
    }
    return expanded;
}
 
Example 3
Source File: PlusOperator.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isTextual() || v2.isTextual()) {
    // if one operand is string: do string concatenation
    return new TextNode(NodeUtils.toString(v1, false) +
                        NodeUtils.toString(v2, false));

  } else if (v1.isArray() && v2.isArray())
    // if both are arrays: array concatenation
    return concatenateArrays(v1, v2);

  else if (v1.isObject() && v2.isObject())
    // if both are objects: object union
    return unionObjects(v1, v2);

  // {} + null => {} (also arrays)
  else if ((v1.isObject() || v1.isArray()) && v2.isNull())
    return v1;

  // null + {} => {} (also arrays)
  else if (v1.isNull() && (v2.isObject() || v2.isArray()))
    return v2;

  else
    // do numeric operation
    return super.perform(v1, v2);
}
 
Example 4
Source File: LightConfResult.java    From lightconf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 将json结果集转化为TaotaoResult对象
 *
 * @param jsonData
 *            json数据
 * @param clazz
 *            TaotaoResult中的object类型
 * @return
 */
public static LightConfResult formatToPojo(String jsonData, Class<?> clazz) {
    try {
        if (clazz == null) {
            return MAPPER.readValue(jsonData, LightConfResult.class);
        }
        JsonNode jsonNode = MAPPER.readTree(jsonData);
        JsonNode data = jsonNode.get("data");
        Object obj = null;
        if (clazz != null) {
            if (data.isObject()) {
                obj = MAPPER.readValue(data.traverse(), clazz);
            } else if (data.isTextual()) {
                obj = MAPPER.readValue(data.asText(), clazz);
            }
        }
        return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
    } catch (Exception e) {
        return null;
    }
}
 
Example 5
Source File: CustomTypeAnnotator.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
private JsonObject getValue(String key, JsonNode value){
  if(value.isTextual()){
    return annotationLookUp.get(key, value.asText());
  }
  else if(value.isBoolean()){
    return annotationLookUp.get(key, value.asBoolean());
  }
  else if(value.isDouble()){
    return annotationLookUp.get(key, value.asDouble());
  }
  else if(value.isIntegralNumber() || value.isInt()){
    return annotationLookUp.get(key, value.asInt());
  }
  else{
    return null;
  }
}
 
Example 6
Source File: ConfigEvalEngine.java    From digdag with Apache License 2.0 6 votes vote down vote up
private ArrayNode evalArrayRecursive(ObjectNode local, ArrayNode array)
    throws TemplateException
{
    ArrayNode built = array.arrayNode();
    for (JsonNode value : array) {
        JsonNode evaluated;
        if (value.isObject()) {
            evaluated = evalObjectRecursive((ObjectNode) value);
        }
        else if (value.isArray()) {
            evaluated = evalArrayRecursive(local, (ArrayNode) value);
        }
        else if (value.isTextual()) {
            // eval using template engine
            String code = value.textValue();
            evaluated = evalValue(local, code);
        }
        else {
            evaluated = value;
        }
        built.add(evaluated);
    }
    return built;
}
 
Example 7
Source File: BaseParser.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
protected static String processLocation(String parentPath, JsonNode locationNode) throws CWLException {
    String location = null;
    if (locationNode != null && locationNode.isTextual()) {
        location = locationNode.asText();
        if (location.startsWith(IOUtil.HTTP_PREFIX) ||
                location.startsWith(IOUtil.HTTPS_PREFIX) ||
                location.startsWith(IOUtil.FTP_PREFIX)) {
            throw new CWLException(ResourceLoader.getMessage("cwl.parser.remote.file.location.unsupported"),
                    33);
        } else {
            Path locationPath = Paths.get(location.replaceFirst(IOUtil.FILE_PREFIX, ""));
            if (!locationPath.isAbsolute()) {
                locationPath = Paths.get(parentPath, location);
                location = locationPath.toString();
            }
        }
    }
    return location;
}
 
Example 8
Source File: ExtractJsonPathsBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
private void resolve(JsonNode datum, Record record, String fieldName) { 
  if (datum == null) {
    return;
  }
  
  if (flatten) {
    flatten(datum, record.get(fieldName));
    return;
  }

  if (datum.isObject()) {
    record.put(fieldName, datum);
  } else if (datum.isArray()) {
    record.put(fieldName, datum);  
  } else if (datum.isTextual()) {
    record.put(fieldName, datum.asText());
  } else if (datum.isBoolean()) {
    record.put(fieldName, datum.asBoolean());
  } else if (datum.isInt()) {
    record.put(fieldName, datum.asInt());
  } else if (datum.isLong()) {
    record.put(fieldName, datum.asLong());
  } else if (datum.isShort()) {
    record.put(fieldName, datum.shortValue());
  } else if (datum.isDouble()) {
    record.put(fieldName, datum.asDouble());
  } else if (datum.isFloat()) {
    record.put(fieldName, datum.floatValue());
  } else if (datum.isBigInteger()) {
    record.put(fieldName, datum.bigIntegerValue());
  } else if (datum.isBigDecimal()) {
    record.put(fieldName, datum.decimalValue());
  } else if (datum.isNull()) {
    ; // ignore
  } else {
    record.put(fieldName, datum.toString());
  }
}
 
Example 9
Source File: BpmnJsonConverterUtil.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static JsonNode validateIfNodeIsTextual(JsonNode node) {
  if (node != null && node.isNull() == false && node.isTextual() && StringUtils.isNotEmpty(node.asText())) {
    try {
      node = validateIfNodeIsTextual(objectMapper.readTree(node.asText()));
    } catch(Exception e) {
      logger.error("Error converting textual node", e);
    }
  }
  return node;
}
 
Example 10
Source File: SchemaGenerationContextImpl.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Collect the specified value(s) from the given definition's {@link SchemaKeyword#TAG_TYPE} attribute.
 *
 * @param definition type definition to extract specified {@link SchemaKeyword#TAG_TYPE} values from
 * @return extracted {@link SchemaKeyword#TAG_TYPE} – values (may be empty)
 */
private Set<String> collectAllowedSchemaTypes(ObjectNode definition) {
    JsonNode declaredTypes = definition.get(this.getKeyword(SchemaKeyword.TAG_TYPE));
    final Set<String> allowedSchemaTypes;
    if (declaredTypes == null) {
        allowedSchemaTypes = Collections.emptySet();
    } else if (declaredTypes.isTextual()) {
        allowedSchemaTypes = Collections.singleton(declaredTypes.textValue());
    } else {
        allowedSchemaTypes = StreamSupport.stream(declaredTypes.spliterator(), false)
                .map(JsonNode::textValue)
                .collect(Collectors.toSet());
    }
    return allowedSchemaTypes;
}
 
Example 11
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private boolean matchTextualCase(final JsonNode node, final EdmPrimitiveTypeKind primKind) {
  return node.isTextual() &&
      (primKind == EdmPrimitiveTypeKind.String
          || primKind == EdmPrimitiveTypeKind.Binary
          || primKind == EdmPrimitiveTypeKind.Date
          || primKind == EdmPrimitiveTypeKind.DateTimeOffset
          || primKind == EdmPrimitiveTypeKind.Duration
          || primKind == EdmPrimitiveTypeKind.Guid
          || primKind == EdmPrimitiveTypeKind.TimeOfDay);
}
 
Example 12
Source File: Id.java    From digdag with Apache License 2.0 5 votes vote down vote up
@JsonCreator
@Deprecated
static Id fromJson(JsonNode node)
        throws JsonMappingException
{
    if (node.isTextual() || node.isNumber()) {
        return of(node.asText());
    }
    else {
        throw new JsonMappingException("Invalid ID. Expected string but got " + node);
    }
}
 
Example 13
Source File: CmmnJsonConverterUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static JsonNode validateIfNodeIsTextual(JsonNode node) {
    if (node != null && !node.isNull() && node.isTextual() && StringUtils.isNotEmpty(node.asText())) {
        try {
            node = validateIfNodeIsTextual(objectMapper.readTree(node.asText()));
        } catch (Exception e) {
            LOGGER.error("Error converting textual node", e);
        }
    }
    return node;
}
 
Example 14
Source File: QualifiedName.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the name from the json.
 *
 * @param node json node
 * @return qualified name
 */
@JsonCreator
public static QualifiedName fromJson(@NonNull final JsonNode node) {
    final JsonNode catalogNameNode = node.path("catalogName");
    if (catalogNameNode.isMissingNode() || catalogNameNode.isNull() || !catalogNameNode.isTextual()) {
        // If catalogName is not present try to load from the qualifiedName node instead
        final JsonNode nameNode = node.path("qualifiedName");
        if (!nameNode.isNull() && nameNode.isTextual()) {
            return fromString(nameNode.asText(), false);
        } else {
            // if neither are available throw an exception
            throw new IllegalStateException("Node '" + node + "' is missing catalogName");
        }
    }
    final String catalogName = catalogNameNode.asText();
    final JsonNode databaseNameNode = node.path("databaseName");
    String databaseName = null;
    if (databaseNameNode != null) {
        databaseName = databaseNameNode.asText();
    }
    final JsonNode tableNameNode = node.path("tableName");
    String tableName = null;
    if (tableNameNode != null) {
        tableName = tableNameNode.asText();
    }
    final JsonNode partitionNameNode = node.path("partitionName");
    String partitionName = null;
    if (partitionNameNode != null) {
        partitionName = partitionNameNode.asText();
    }
    final JsonNode viewNameNode = node.path("viewName");
    String viewName = null;
    if (viewNameNode != null) {
        viewName = viewNameNode.asText();
    }
    return new QualifiedName(catalogName, databaseName, tableName, partitionName, viewName);
}
 
Example 15
Source File: Attribute.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the value of "attributes".ATTRIBUTE_NAME."type".
 * Must be a non-empty string containing a recognized type.
 *
 * @param value The value of "attributes".ATTRIBUTE_NAME."type".
 * @throws ValidationException
 */
private void validateType(JsonNode value) throws ValidationException {
    if (!value.isTextual())
        throw new ValidationException("'attributes." + this.name + ".type' must be a string.");
    if (Patterns.EMPTY_STRING.matcher(value.textValue()).matches())
        throw new ValidationException("'attributes." + this.name + ".type'' must not be empty.");
    if (!VALID_TYPES.contains(value.textValue()))
        throw new ValidationException("'attributes." + this.name + ".type' has an unrecognized type '" + value.textValue() + "'.");
}
 
Example 16
Source File: DatableConverter.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object jsonToTinkerpop(JsonNode json) throws IOException {
  if (!json.isTextual()) {
    throw new IOException("datable should be presented as String");
  }

  return json.toString();
}
 
Example 17
Source File: JsonPropertyConverter.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StringOfLimitedValuesProperty createStringOfLimitedValues(String propertyName, JsonNode value)
  throws IOException {
  if (!value.isTextual()) {
    throw new IOException(String.format("'%s' should be a String.", propertyName));
  }
  return new StringOfLimitedValuesProperty(propertyName, value.asText());
}
 
Example 18
Source File: JsonNodeAssertions.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Asserts that the current JsonNode is an array, where at least one element is equal to [str].
 */
public JsonNodeAssertions isArrayWithString(String str) {
    isNotNull();
    if(!actual.isArray()){
        failWithMessage("Expected an array, but was <%s>", actual);
    }
    for (int i = 0; i < actual.size(); i++) {
        JsonNode elem = actual.get(i);
        if (elem.isTextual() && elem.asText().equals(str)) {
            return this;
        }
    }
    failWithMessage("Expected array to contain string <%s>, but was <%s>", str, actual);
    return this;
}
 
Example 19
Source File: AbstractJsonUserAttributeMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static Object getJsonValue(JsonNode baseNode, String fieldPath) {
	logger.debug("Going to process JsonNode path " + fieldPath + " on data " + baseNode);
	if (baseNode != null) {

		List<String> fields = OIDCAttributeMapperHelper.splitClaimPath(fieldPath);
		if (fields.isEmpty() || fieldPath.endsWith(".")) {
			logger.debug("JSON path is invalid " + fieldPath);
			return null;
		}

		JsonNode currentNode = baseNode;
		for (String currentFieldName : fields) {

			// if array path, retrieve field name and index
			String currentNodeName = currentFieldName;
			int arrayIndex = -1;
			if (currentFieldName.endsWith("]")) {
				int bi = currentFieldName.indexOf("[");
				if (bi == -1) {
					logger.debug("Invalid array index construct in " + currentFieldName);
					return null;
				}
				try {
					String is = currentFieldName.substring(bi + 1, currentFieldName.length() - 1).trim();
					arrayIndex = Integer.parseInt(is);
					if( arrayIndex < 0) throw new ArrayIndexOutOfBoundsException();
				} catch (Exception e) {
					logger.debug("Invalid array index construct in " + currentFieldName);
					return null;
				}
				currentNodeName = currentFieldName.substring(0, bi).trim();
			}

			currentNode = currentNode.get(currentNodeName);
			if (arrayIndex > -1 && currentNode.isArray()) {
				logger.debug("Going to take array node at index " + arrayIndex);
				currentNode = currentNode.get(arrayIndex);
			}

			if (currentNode == null) {
				logger.debug("JsonNode not found for name " + currentFieldName);
				return null;
			}

			if (currentNode.isArray()) {
				List<String> values = new ArrayList<>();
				for (JsonNode childNode : currentNode) {
					if (childNode.isTextual()) {
						values.add(childNode.textValue());
					} else {
						logger.warn("JsonNode in array is not text value " + childNode);
					}
				}
				if (values.isEmpty()) {
					return null;
				}
				return values ;
			} else if (currentNode.isNull()) {

				logger.debug("JsonNode is null node for name " + currentFieldName);
				return null;
			} else if (currentNode.isValueNode()) {
				String ret = currentNode.asText();
				if (ret != null && !ret.trim().isEmpty())
					return ret.trim();
				else
					return null;

			}

		}
		return currentNode;
	}
	return null;
}
 
Example 20
Source File: DefaultChange.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@JsonCreator
static DefaultChange<?> deserialize(@JsonProperty("type") ChangeType type,
                                    @JsonProperty("path") String path,
                                    @JsonProperty("content") @Nullable JsonNode content) {
    requireNonNull(type, "type");
    final Class<?> contentType = type.contentType();
    if (contentType == Void.class) {
        if (content != null && !content.isNull()) {
            return rejectIncompatibleContent(content, Void.class);
        }
    } else if (type.contentType() == String.class) {
        if (content == null || !content.isTextual()) {
            return rejectIncompatibleContent(content, String.class);
        }
    }

    if (type == ChangeType.REMOVE) {
        return (DefaultChange<?>) Change.ofRemoval(path);
    }

    requireNonNull(content, "content");

    final Change<?> result;
    switch (type) {
        case UPSERT_JSON:
            result = Change.ofJsonUpsert(path, content);
            break;
        case UPSERT_TEXT:
            result = Change.ofTextUpsert(path, content.asText());
            break;
        case RENAME:
            result = Change.ofRename(path, content.asText());
            break;
        case APPLY_JSON_PATCH:
            result = Change.ofJsonPatch(path, content);
            break;
        case APPLY_TEXT_PATCH:
            result = Change.ofTextPatch(path, content.asText());
            break;
        default:
            // Should never reach here
            throw new Error();
    }

    // Ugly downcast, but otherwise we would have needed to write a custom serializer.
    return (DefaultChange<?>) result;
}