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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#textValue() . 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: HostAndPortDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@Override
public HostAndPort deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException
{
    // Need to override this method, which otherwise would work just fine,
    // since we have legacy JSON Object format to support too:
    if (p.hasToken(JsonToken.START_OBJECT)) { // old style
        JsonNode root = p.readValueAsTree();
        // [datatypes-collections#45]: we actually have 2 possibilities depending on Guava version
        JsonNode hostNode = root.get("host");
        final String host = (hostNode == null) ? root.path("hostText").asText() : hostNode.textValue();
        JsonNode n = root.get("port");
        if (n == null) {
            return HostAndPort.fromString(host);
        }
        return HostAndPort.fromParts(host, n.asInt());
    }
    return super.deserialize(p, ctxt);
}
 
Example 2
Source File: ElasticsearchJson.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static Bucket parseBucket(JsonParser parser, String name, ObjectNode node)
    throws JsonProcessingException  {

  if (!node.has("key")) {
    throw new IllegalArgumentException("No 'key' attribute for " + node);
  }

  final JsonNode keyNode = node.get("key");
  final Object key;
  if (isMissingBucket(keyNode) || keyNode.isNull()) {
    key = null;
  } else if (keyNode.isTextual()) {
    key = keyNode.textValue();
  } else if (keyNode.isNumber()) {
    key = keyNode.numberValue();
  } else if (keyNode.isBoolean()) {
    key = keyNode.booleanValue();
  } else {
    // don't usually expect keys to be Objects
    key = parser.getCodec().treeToValue(node, Map.class);
  }

  return new Bucket(key, name, parseAggregations(parser, node));
}
 
Example 3
Source File: SpatialFilterDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
public SpatialFilter decodeJSON(JsonNode node, boolean validate)
        throws DecodingException {
    if (node == null || node.isNull() || node.isMissingNode()) {
        return null;
    }
    if (validate) {
        JSONValidator.getInstance().validateAndThrow(node, SchemaConstants.Common.SPATIAL_FILTER);
    }
    if (node.isObject()) {
        final String oName = node.fields().next().getKey();
        final SOp o = SOp.valueOf(oName);
        JsonNode value = node.path(oName).path(JSONConstants.VALUE);
        JsonNode ref = node.path(oName).path(JSONConstants.REF);
        return new SpatialFilter(o.getOp(), decodeGeometry(value), ref.textValue());
    } else {
        return null;
    }
}
 
Example 4
Source File: BaseResponseHandler.java    From agrest with Apache License 2.0 6 votes vote down vote up
private String readMessage(Response response) {

        String entity = response.readEntity(String.class);
        String message = null;

        if (entity != null) {
            try {
                JsonNode entityNode = new ObjectMapper().readTree(jsonFactory.createParser(entity));
                // parsed node will be null if the response did not contain a valid JSON
                if (entityNode != null) {
                    JsonNode messageNode = entityNode.get(MESSAGE_NODE);
                    if (messageNode != null) {
                        message = messageNode.textValue();
                    }
                }
            } catch (IOException e) {
                // do nothing...
            }
        }
        // return the response body if the Agrest message is not present
        return (message == null) ? entity : message;
    }
 
Example 5
Source File: Agent.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
public static Agent fromJson(JsonNode jsonNode) {
    
    String objectType = "Agent";
    JsonNode objectTypeNode = jsonNode.path("objectType");
    if (! objectTypeNode.isMissingNode()) {
        objectType = objectTypeNode.textValue();
    }
    
    return "Group".equals(objectType) ? new Group(jsonNode) : new Agent(jsonNode);
}
 
Example 6
Source File: AtlasGraphSONUtility.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private static Object getTypedValueFromJsonNode(JsonNode node) {
    Object theValue = null;

    if (node != null && !node.isNull()) {
        if (node.isBoolean()) {
            theValue = node.booleanValue();
        } else if (node.isDouble()) {
            theValue = node.doubleValue();
        } else if (node.isFloatingPointNumber()) {
            theValue = node.floatValue();
        } else if (node.isInt()) {
            theValue = node.intValue();
        } else if (node.isLong()) {
            theValue = node.longValue();
        } else if (node.isTextual()) {
            theValue = node.textValue();
        } else if (node.isArray()) {
            // this is an array so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else if (node.isObject()) {
            // this is an object so just send it back so that it can be
            // reprocessed to its primitive components
            theValue = node;
        } else {
            theValue = node.textValue();
        }
    }

    return theValue;
}
 
Example 7
Source File: SelectionResultSet.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public String getString(int rowIndex, int columnIndex) {
  JsonNode jsonValue = _resultsArray.get(rowIndex).get(columnIndex);
  if (jsonValue.isTextual()) {
    return jsonValue.textValue();
  } else {
    return jsonValue.toString();
  }
}
 
Example 8
Source File: BitmexTickDirection.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public BitmexTickDirection deserialize(JsonParser jsonParser, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {

  ObjectCodec oc = jsonParser.getCodec();
  JsonNode node = oc.readTree(jsonParser);
  String tickDirectionString = node.textValue();
  return fromString(tickDirectionString);
}
 
Example 9
Source File: LocalDateTimeJsonComponent.java    From angularjs-springmvc-sample-boot with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectCodec codec = p.getCodec();
    JsonNode tree = codec.readTree(p);
    String dateTimeAsString = tree.textValue();
    log.debug("dateTimeString value @" + dateTimeAsString);
    return LocalDateTime.ofInstant(Instant.parse(dateTimeAsString), ZoneId.systemDefault());
}
 
Example 10
Source File: JsonEventConventions.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public TenantId getTenantId(ObjectNode eventNode) {
    try {
        JsonNode got = eventNode.get(ReservedFields.TENANT_ID);
        if (got == null || got.isNull()) {
            return null;
        }
        return new TenantId(got.textValue());
    } catch (Exception ex) {
        LOG.debug("Failed to get tenantId: " + eventNode, ex);
        return null;
    }
}
 
Example 11
Source File: MrJobInfoExtractor.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void extractTaskDetail(String taskId, String user, File exportDir, String taskUrl, String urlBase) throws IOException {
    try {
        if (StringUtils.isEmpty(taskId)) {
            return;
        }

        String taskUrlBase = taskUrl + taskId;
        File destDir = new File(exportDir, taskId);

        // get task basic info
        String taskInfo = saveHttpResponseQuietly(new File(destDir, "task.json"), taskUrlBase);
        JsonNode taskAttempt = new ObjectMapper().readTree(taskInfo).path("task").path("successfulAttempt");
        String succAttemptId = taskAttempt.textValue();

        String attemptInfo = saveHttpResponseQuietly(new File(destDir, "task_attempts.json"), taskUrlBase + "/attempts/" + succAttemptId);
        JsonNode attemptAttempt = new ObjectMapper().readTree(attemptInfo).path("taskAttempt");
        String containerId = attemptAttempt.get("assignedContainerId").textValue();
        String nodeId = nodeInfoMap.get(attemptAttempt.get("nodeHttpAddress").textValue());

        // save task counters
        saveHttpResponseQuietly(new File(destDir, "task_counters.json"), taskUrlBase + "/counters");

        // save task logs
        String logUrl = urlBase + "/jobhistory/logs/" + nodeId + "/" + containerId + "/" + succAttemptId + "/" + user + "/syslog/?start=0";
        logger.debug("Fetch task log from url: " + logUrl);

        saveHttpResponseQuietly(new File(destDir, "task_log.txt"), logUrl);
    } catch (Exception e) {
        logger.warn("Failed to get task counters rest response" + e);
    }
}
 
Example 12
Source File: PluginFQNParser.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Evaluates plugin FQN from provided reference by trying to fetch and parse its meta information.
 *
 * @param reference plugin reference to evaluate FQN from
 * @param fileContentProvider content provider instance to perform plugin meta requests
 * @return plugin FQN evaluated from given reference
 * @throws InfrastructureException if plugin reference is invalid or inaccessible
 */
public ExtendedPluginFQN evaluateFqn(String reference, FileContentProvider fileContentProvider)
    throws InfrastructureException {
  JsonNode contentNode;
  try {
    String pluginMetaContent = fileContentProvider.fetchContent(reference);
    contentNode = yamlReader.readTree(pluginMetaContent);
  } catch (DevfileException | IOException e) {
    throw new InfrastructureException(
        format("Plugin reference URL '%s' is invalid.", reference), e);
  }
  JsonNode publisher = contentNode.path("publisher");
  if (publisher.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "publisher"));
  }
  JsonNode name = contentNode.get("name");
  if (name.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "name"));
  }
  JsonNode version = contentNode.get("version");
  if (version.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "version"));
  }
  if (!version.isValueNode()) {
    throw new InfrastructureException(
        format(
            "Plugin specified by reference URL '%s' has version field that cannot be parsed to string",
            reference));
  }
  return new ExtendedPluginFQN(
      reference, publisher.textValue(), name.textValue(), version.asText());
}
 
Example 13
Source File: TypeFactory.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public static JsonType getSchemaNodeType(JsonNode node) {
    //Single Type Definition
    if (node.isTextual()) {
        String type = node.textValue();
        if ("object".equals(type)) {
            return JsonType.OBJECT;
        }
        if ("array".equals(type)) {
            return JsonType.ARRAY;
        }
        if ("string".equals(type)) {
            return JsonType.STRING;
        }
        if ("number".equals(type)) {
            return JsonType.NUMBER;
        }
        if ("integer".equals(type)) {
            return JsonType.INTEGER;
        }
        if ("boolean".equals(type)) {
            return JsonType.BOOLEAN;
        }
        if ("any".equals(type)) {
            return JsonType.ANY;
        }
        if ("null".equals(type)) {
            return JsonType.NULL;
        }
    }

    //Union Type Definition
    if (node.isArray()) {
        return JsonType.UNION;
    }

    return JsonType.UNKNOWN;
}
 
Example 14
Source File: QueueManager.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getValue(String fieldName, JsonNode json) {
	JsonNode node = json.findValue(fieldName);
	if(node == null) {
		return null;
	}
	return node.textValue();
}
 
Example 15
Source File: CoinbaseButtonType.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public CoinbaseButtonType deserialize(JsonParser jsonParser, final DeserializationContext ctxt)
    throws IOException, JsonProcessingException {

  final ObjectCodec oc = jsonParser.getCodec();
  final JsonNode node = oc.readTree(jsonParser);
  final String jsonString = node.textValue();
  return FROM_STRING_HELPER.fromJsonString(jsonString);
}
 
Example 16
Source File: SerializableConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Serializable serializableNodeValue(JsonNode node) {
  if (node.isNumber()) {
    return node.numberValue();
  } else if (node.isBoolean()) {
    return node.booleanValue();
  } else if (node.isTextual()) {
    return node.textValue();
  } else {
    throw new RuntimeException("Unable to deserialize preference value:" + node.asText());
  }
}
 
Example 17
Source File: SchemaTransformer.java    From aws-apigateway-importer with Apache License 2.0 4 votes vote down vote up
private void buildSchemaReferenceMap(JsonNode model, JsonNode models, Map<String, String> modelMap) {
    Map<JsonNode, JsonNode> refs = new HashMap<>();
    findReferences(model, refs);

    for (JsonNode ref : refs.keySet()) {
        String canonicalRef = ref.textValue();

        String schemaName = getSchemaName(canonicalRef);

        JsonNode subSchema = getSchema(schemaName, models);

        // replace reference values with inline definitions
        replaceRef((ObjectNode) refs.get(ref), schemaName);

        buildSchemaReferenceMap(subSchema, models, modelMap);

        modelMap.put(schemaName, serializeExisting(subSchema));
    }
}
 
Example 18
Source File: EthernetJsonMatcher.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matchesSafely(JsonNode jsonEthernet) {

    // check source MAC
    final JsonNode jsonSourceMacNode = jsonEthernet.get("srcMac");
    if (ethernet.getSourceMAC() != null) {
        final String jsonSourceMac = jsonSourceMacNode.textValue();
        final String sourceMac = ethernet.getSourceMAC().toString();
        if (!jsonSourceMac.equals(sourceMac)) {
            reason = "source MAC " + ethernet.getSourceMAC().toString();
            return false;
        }
    } else {
        //  source MAC not specified, JSON representation must be empty
        if (jsonSourceMacNode != null) {
            reason = "source mac should be null ";
            return false;
        }
    }

    // check destination MAC
    final JsonNode jsonDestinationMacNode = jsonEthernet.get("destMac");
    if (ethernet.getDestinationMAC() != null) {
        final String jsonDestinationMac = jsonDestinationMacNode.textValue();
        final String destinationMac = ethernet.getDestinationMAC().toString();
        if (!jsonDestinationMac.equals(destinationMac)) {
            reason = "destination MAC " + ethernet.getDestinationMAC().toString();
            return false;
        }
    } else {
        //  destination MAC not specified, JSON representation must be empty
        if (jsonDestinationMacNode != null) {
            reason = "destination mac should be null ";
            return false;
        }
    }

    // check priority code
    final short jsonPriorityCode = jsonEthernet.get("priorityCode").shortValue();
    final short priorityCode = ethernet.getPriorityCode();
    if (jsonPriorityCode != priorityCode) {
        reason = "priority code " + Short.toString(ethernet.getPriorityCode());
        return false;
    }

    // check vlanId
    final short jsonVlanId = jsonEthernet.get("vlanId").shortValue();
    final short vlanId = ethernet.getVlanID();
    if (jsonVlanId != vlanId) {
        reason = "vlan id " + Short.toString(ethernet.getVlanID());
        return false;
    }

    // check etherType
    final short jsonEtherType = jsonEthernet.get("etherType").shortValue();
    final short etherType = ethernet.getEtherType();
    if (jsonEtherType != etherType) {
        reason = "etherType " + Short.toString(ethernet.getEtherType());
        return false;
    }

    // check pad
    final boolean jsonPad = jsonEthernet.get("pad").asBoolean();
    final boolean pad = ethernet.isPad();
    if (jsonPad != pad) {
        reason = "pad " + Boolean.toString(ethernet.isPad());
        return false;
    }

    return true;
}
 
Example 19
Source File: IndexField.java    From zentity with Apache License 2.0 4 votes vote down vote up
public void matcher(JsonNode value) throws ValidationException {
    validateMatcher(value);
    this.matcher = value.textValue();
}
 
Example 20
Source File: Envelope.java    From evercam-android with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Helper to retrieve the value of "ref" from the payload
 *
 * @return The ref string or null if not found
 */
public String getRef() {
    if (ref != null) return ref;
    final JsonNode refNode = payload.get("ref");
    return refNode != null ? refNode.textValue() : null;
}