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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isLong() . 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: JsonUtils.java    From template-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * Compare two JsonNode objects and return an integer.
 *
 * @return  a negative integer, zero, or a positive integer as this object
 *          is less than, equal to, or greater than the specified object.
 */
public static int compare(JsonNode left, JsonNode right) {
  if (left.isLong() || left.isInt()) {
    return Long.compare(left.asLong(), right.asLong());

  } else if (left.isDouble() || left.isFloat()) {
    return Double.compare(left.asDouble(), right.asDouble());

  } else if (left.isTextual()) {
    return left.asText().compareTo(right.asText());

  } else if (left.isBoolean()) {
    return Boolean.compare(left.asBoolean(), right.asBoolean());
  }

  // Not comparable in a relative sense, default to equals.
  return left.equals(right) ? 0 : -1;
}
 
Example 2
Source File: SanskritObjectImpl.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(SanskritVisitor visitor) {
  Iterator<Map.Entry<String, JsonNode>> fields = mappings.fields();
  while (fields.hasNext()) {
    Map.Entry<String, JsonNode> entry = fields.next();
    String key = entry.getKey();
    JsonNode value = entry.getValue();
    if (value.isTextual()) {
      visitor.setString(key, value.textValue());
    } else if (value.isLong()) {
      visitor.setLong(key, value.longValue());
    } else if (value.isObject()) {
      visitor.setObject(key, new SanskritObjectImpl(objectMapper, (ObjectNode) value));
    } else {
      visitor.setExternal(key, value);
    }
  }
}
 
Example 3
Source File: WorkflowParser.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
private static Object toDefaultValue(String descTop,
        String id,
        JsonNode defaultNode) throws CWLException {
    Object value = null;
    if (defaultNode != null) {
        if (defaultNode.isTextual()) {
            value = defaultNode.asText();
        } else if (defaultNode.isInt()) {
            value = Integer.valueOf(defaultNode.asInt());
        } else if (defaultNode.isLong()) {
            value = Long.valueOf(defaultNode.asLong());
        } else if (defaultNode.isFloat()) {
            value = Float.valueOf(defaultNode.floatValue());
        } else if (defaultNode.isDouble()) {
            value = Double.valueOf(defaultNode.asDouble());
        } else if (defaultNode.isBoolean()) {
            value = Boolean.valueOf(defaultNode.asBoolean());
        } else if (defaultNode.isArray()) {
            value = toDefaultArrayValue(descTop, id, defaultNode);
        } else if (defaultNode.isObject()) {
            value = toDefaultObjectValue(descTop, id, defaultNode);
        }
    }
    return value;
}
 
Example 4
Source File: PredictionBusinessServiceImpl.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
private JsonNode getValidatedJson(ConsumerBean consumer,String jsonRaw,boolean addExtraFeatures) throws JsonParseException, IOException
{
	ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(jsonRaw);
    JsonNode actualObj = mapper.readTree(parser);
    if (addExtraFeatures) // only for events not at predict time
    {
    	((ObjectNode) actualObj).put(CLIENT_KEY,consumer.getShort_name());
    	if (actualObj.get(TIMESTAMP_KEY) == null)
    	{
    		((ObjectNode) actualObj).put(TIMESTAMP_KEY,getTimeStamp());
    	}
    	else
    	{
    		JsonNode timeNode = actualObj.get(TIMESTAMP_KEY);
    		if (!(timeNode.isInt() || timeNode.isLong()))
    		{
    			throw new APIException(APIException.INVALID_JSON);
    		}
    	}
    }
    return actualObj;
}
 
Example 5
Source File: BaseParser.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
private static void setPhysicalFileAttr(File file, CWLFile cwlFile, JsonNode fileNode, boolean nochecksum) {
    // checksum
    JsonNode checksumNode = fileNode.get("checksum");
    if (checksumNode != null && checksumNode.isTextual()) {
        cwlFile.setChecksum(checksumNode.asText());
    } else if (file.exists() && !nochecksum) {
        String path = cwlFile.getPath();
        if (path != null && path.startsWith(IOUtil.FILE_PREFIX)) {
            path = path.substring(7);
        }
        cwlFile.setChecksum("sha1$" + IOUtil.md5(path));
    }
    // size
    JsonNode sizeNode = fileNode.get("size");
    if (sizeNode != null && sizeNode.isLong()) {
        cwlFile.setSize(sizeNode.asLong());
    } else if (file.exists()) {
        cwlFile.setSize(file.length());
    }
}
 
Example 6
Source File: MahutaCustomRepositoryImpl.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize a JSONNode to a primitive object
 *
 * @param node JSON node
 * @return primitive object
 */
public static Object deserialize(JsonNode node) {

    if (node == null || node.isMissingNode() || node.isNull()) {
        return ""; // Because toMap doesn't accept null value ...
    } else if (node.isBoolean()) {
        return node.asBoolean();
    } else if (node.isLong()) {
        return node.asLong();
    } else if (node.isInt()) {
        return node.asInt();
    } else if (node.isDouble()) {
        return node.asDouble();
    } else if (node.isArray()) {
        return StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(node.elements(), Spliterator.ORDERED), false)
                .map(MahutaCustomRepositoryImpl::deserialize).collect(Collectors.toList());
    } else {
        return node.asText();
    }
}
 
Example 7
Source File: BeatsCodec.java    From graylog-plugin-beats with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private Object valueNode(JsonNode jsonNode) {
    if (jsonNode.isInt()) {
        return jsonNode.asInt();
    } else if (jsonNode.isLong()) {
        return jsonNode.asLong();
    } else if (jsonNode.isIntegralNumber()) {
        return jsonNode.asLong();
    } else if (jsonNode.isFloatingPointNumber()) {
        return jsonNode.asDouble();
    } else if (jsonNode.isBoolean()) {
        return jsonNode.asBoolean();
    } else if (jsonNode.isNull()) {
        return null;
    } else {
        return jsonNode.asText();
    }
}
 
Example 8
Source File: StandardCommunity.java    From batfish with Apache License 2.0 6 votes vote down vote up
@JsonCreator
private static StandardCommunity create(@Nullable JsonNode value) {
  // Keep this creator backwards compatible with previous communities implementation
  checkArgument(value != null && !value.isNull(), "Standard community string must not be null");
  if (value.isTextual()) {
    return parse(value.textValue());
  } else if (value.isInt() || value.isLong()) {
    return StandardCommunity.of(value.longValue());
  } else if (value.isArray()
      && value.has(0)
      && value.get(0).textValue().equalsIgnoreCase("standard")) {
    return parse(value.get(1).textValue());
  } else {
    throw new IllegalArgumentException(
        String.format("Invalid standard community value: %s", value));
  }
}
 
Example 9
Source File: DecodeInstructionCodecHelper.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts port number of the given json node.
 *
 * @param jsonNode json node
 * @return port number
 */
private PortNumber getPortNumber(ObjectNode jsonNode) {
    PortNumber portNumber;
    JsonNode portNode = nullIsIllegal(jsonNode.get(InstructionCodec.PORT),
            InstructionCodec.PORT + InstructionCodec.ERROR_MESSAGE);
    if (portNode.isLong() || portNode.isInt()) {
        portNumber = PortNumber.portNumber(portNode.asLong());
    } else if (portNode.isTextual()) {
        portNumber = PortNumber.fromString(portNode.textValue());
    } else {
        throw new IllegalArgumentException("Port value "
                + portNode.toString()
                + " is not supported");
    }
    return portNumber;
}
 
Example 10
Source File: ExtractJsonPathsBuilder.java    From kite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void flatten(JsonNode datum, List list) { 
  if (datum == null) {
    return;
  }

  if (datum.isObject()) {
    for (JsonNode child : datum) {
      flatten(child, list);
    }
  } else if (datum.isArray()) {
    Iterator<JsonNode> iter = datum.elements();
    while (iter.hasNext()) {
      flatten(iter.next(), list);
    }        
  } else if (datum.isTextual()) {
    list.add(datum.asText());
  } else if (datum.isBoolean()) {
    list.add(datum.asBoolean());
  } else if (datum.isInt()) {
    list.add(datum.asInt());
  } else if (datum.isLong()) {
    list.add(datum.asLong());
  } else if (datum.isShort()) {
    list.add(datum.shortValue());
  } else if (datum.isDouble()) {
    list.add(datum.asDouble());
  } else if (datum.isFloat()) {
    list.add(datum.floatValue());
  } else if (datum.isBigInteger()) {
    list.add(datum.bigIntegerValue());
  } else if (datum.isBigDecimal()) {
    list.add(datum.decimalValue());
  } else if (datum.isNull()) {
    ; // ignore
  } else {
    list.add(datum.toString());
  }
}
 
Example 11
Source File: GetFormModelWithVariablesCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void fillVariablesWithFormInstanceValues(Map<String, JsonNode> formInstanceFieldMap, List<FormField> allFields, String formInstanceId) {
    for (FormField field : allFields) {

        JsonNode fieldValueNode = formInstanceFieldMap.get(field.getId());

        if (fieldValueNode == null || fieldValueNode.isNull()) {
            continue;
        }

        String fieldType = field.getType();
        String fieldValue = fieldValueNode.asText();

        if (FormFieldTypes.DATE.equals(fieldType)) {
            try {
                if (StringUtils.isNotEmpty(fieldValue)) {
                    LocalDate dateValue = LocalDate.parse(fieldValue);
                    variables.put(field.getId(), dateValue.toString("yyyy-M-d"));
                }
                
            } catch (Exception e) {
                LOGGER.error("Error parsing form date value for form instance {} with value {}", formInstanceId, fieldValue, e);
            }
            
        } else if (fieldValueNode.isBoolean()) {
            variables.put(field.getId(), fieldValueNode.asBoolean());
            
        } else if (fieldValueNode.isLong()) {
            variables.put(field.getId(), fieldValueNode.asLong());
            
        } else if (fieldValueNode.isDouble()) {
            variables.put(field.getId(), fieldValueNode.asDouble());

        } else {
            variables.put(field.getId(), fieldValue);
        }
    }
}
 
Example 12
Source File: PrimitiveTypeProvider.java    From cineast with MIT License 5 votes vote down vote up
public static PrimitiveTypeProvider fromJSON(JsonNode json) {
  if (json == null) {
    return NothingProvider.INSTANCE;
  }

  if (json.isTextual()) {
    return new StringTypeProvider(json.asText());
  }

  if (json.isInt()) {
    return new IntTypeProvider(json.asInt());
  }

  if (json.isLong()) {
    return new LongTypeProvider(json.asLong());
  }

  if (json.isFloat()) {
    return new FloatTypeProvider(json.floatValue());
  }

  if (json.isDouble()) {
    return new DoubleTypeProvider(json.doubleValue());
  }

  if (json.isBoolean()) {
    return new BooleanTypeProvider(json.asBoolean());
  }

  // TODO are arrays relevant here?
  return NothingProvider.INSTANCE;
}
 
Example 13
Source File: SyncTokenDeserializer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public SyncToken deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    Object value = null;
    if (tree.has("value")) {
        JsonNode node = tree.get("value");
        if (node.isBoolean()) {
            value = node.asBoolean();
        } else if (node.isDouble()) {
            value = node.asDouble();
        } else if (node.isLong()) {
            value = node.asLong();
        } else if (node.isInt()) {
            value = node.asInt();
        } else {
            value = node.asText();
        }

        if (value instanceof String) {
            String base64 = (String) value;
            try {
                value = Base64.getDecoder().decode(base64);
            } catch (RuntimeException e) {
                value = base64;
            }
        }
    }

    return new SyncToken(Objects.requireNonNull(value));
}
 
Example 14
Source File: JsonNodeELResolver.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * If the base object is a map, returns the value associated with the given key, as specified by
 * the property argument. If the key was not found, null is returned. If the base is a Map, the
 * propertyResolved property of the ELContext object must be set to true by this resolver,
 * before returning. If this property is not true after this method is called, the caller should
 * ignore the return value. Just as in java.util.Map.get(Object), just because null is returned
 * doesn't mean there is no mapping for the key; it's also possible that the Map explicitly maps
 * the key to null.
 * 
 * @param context
 *            The context of this evaluation.
 * @param base
 *            The map to analyze. Only bases of type Map are handled by this resolver.
 * @param property
 *            The key to return the acceptable type for. Ignored by this resolver.
 * @return If the propertyResolved property of ELContext was set to true, then the value
 *         associated with the given key or null if the key was not found. Otherwise, undefined.
 * @throws ClassCastException
 *             if the key is of an inappropriate type for this map (optionally thrown by the
 *             underlying Map).
 * @throws NullPointerException
 *             if context is null, or if the key is null and this map does not permit null keys
 *             (the latter is optionally thrown by the underlying Map).
 * @throws ELException
 *             if an exception was thrown while performing the property or variable resolution.
 *             The thrown exception must be included as the cause property of this exception, if
 *             available.
 */
@Override
public Object getValue(ELContext context, Object base, Object property) {
  if (context == null) {
    throw new NullPointerException("context is null");
  }
  Object result = null;
  if (isResolvable(base)) {
    JsonNode resultNode = ((JsonNode) base).get(property.toString());
    if (resultNode != null && resultNode.isValueNode()) {
      if (resultNode.isBoolean()) {
        result = resultNode.asBoolean();
      } else if (resultNode.isLong()) {
        result = resultNode.asLong();
      } else if (resultNode.isBigDecimal() || resultNode.isDouble()) {
        result = resultNode.asDouble();
      } else if (resultNode.isTextual()) {
        result = resultNode.asText();
      } else {
        result = resultNode.toString();
      }
      
    } else {
      result = resultNode;
    }
    context.setPropertyResolved(true);
  }
  return result;
}
 
Example 15
Source File: ColumnType.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
static long maxFromJson(final JsonNode json) {
    final JsonNode maxNode = json.get("max");
    if (maxNode != null) {
        if (maxNode.isLong()) {
            return maxNode.asLong();
        }
        if (maxNode.isTextual() && "unlimited".equals(maxNode.asText())) {
            return Long.MAX_VALUE;
        }
    }
    return 1;
}
 
Example 16
Source File: BaseParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
protected static Long processLongField(String key, JsonNode longNode) throws CWLException {
    Long longVal = null;
    if (longNode != null) {
        if (longNode.isLong()) {
            longVal = Long.valueOf(longNode.asLong());
        } else if (longNode.isInt()) {
            longVal = Long.valueOf(longNode.asInt());
        } else {
            throw new CWLException(ResourceLoader.getMessage(CWL_PARSER_INVALID_TYPE, key, "long"), 251);
        }
    }
    return longVal;
}
 
Example 17
Source File: JsonFileReader.java    From kafka-connect-fs with Apache License 2.0 4 votes vote down vote up
private Object mapValue(Schema schema, JsonNode value) {
    if (value == null) return null;

    switch (value.getNodeType()) {
        case BOOLEAN:
            return value.booleanValue();
        case NUMBER:
            if (value.isShort()) {
                return value.shortValue();
            } else if (value.isInt()) {
                return value.intValue();
            } else if (value.isLong()) {
                return value.longValue();
            } else if (value.isFloat()) {
                return value.floatValue();
            } else if (value.isDouble()) {
                return value.doubleValue();
            } else if (value.isBigInteger()) {
                return value.bigIntegerValue();
            } else {
                return value.numberValue();
            }
        case STRING:
            return value.asText();
        case BINARY:
            try {
                return value.binaryValue();
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        case OBJECT:
        case POJO:
            Struct struct = new Struct(schema);
            Iterable<Map.Entry<String, JsonNode>> fields = value::fields;
            StreamSupport.stream(fields.spliterator(), false)
                    .forEach(field -> struct.put(field.getKey(),
                            mapValue(extractSchema(field.getValue()), field.getValue()))
                    );
            return struct;
        case ARRAY:
            Iterable<JsonNode> arrayElements = value::elements;
            return StreamSupport.stream(arrayElements.spliterator(), false)
                    .map(elm -> mapValue(schema, elm))
                    .collect(Collectors.toList());
        case NULL:
        case MISSING:
        default:
            return null;
    }
}
 
Example 18
Source File: MaximumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public MaximumValidator(String schemaPath, final JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MAXIMUM, validationContext);

    if (!schemaNode.isNumber()) {
        throw new JsonSchemaException("maximum value is not a number");
    }

    JsonNode exclusiveMaximumNode = getParentSchema().getSchemaNode().get(PROPERTY_EXCLUSIVE_MAXIMUM);
    if (exclusiveMaximumNode != null && exclusiveMaximumNode.isBoolean()) {
        excludeEqual = exclusiveMaximumNode.booleanValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());

    final String maximumText = schemaNode.asText();
    if ((schemaNode.isLong() || schemaNode.isInt()) && (JsonType.INTEGER.toString().equals(getNodeFieldType()))) {
        // "integer", and within long range
        final long lm = schemaNode.asLong();
        typedMaximum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (node.isBigInteger()) {
                    //node.isBigInteger is not trustable, the type BigInteger doesn't mean it is a big number.
                    int compare = node.bigIntegerValue().compareTo(new BigInteger(schemaNode.asText()));
                    return compare > 0 || (excludeEqual && compare == 0);

                } else if (node.isTextual()) {
                    BigDecimal max = new BigDecimal(maximumText);
                    BigDecimal value = new BigDecimal(node.asText());
                    int compare = value.compareTo(max);
                    return compare > 0 || (excludeEqual && compare == 0);
                }
                long val = node.asLong();
                return lm < val || (excludeEqual && lm == val);
            }

            @Override
            public String thresholdValue() {
                return String.valueOf(lm);
            }
        };
    } else {
        typedMaximum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.POSITIVE_INFINITY) {
                    return false;
                }
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return false;
                }
                if (node.isDouble() && node.doubleValue() == Double.POSITIVE_INFINITY) {
                    return true;
                }
                final BigDecimal max = new BigDecimal(maximumText);
                BigDecimal value = new BigDecimal(node.asText());
                int compare = value.compareTo(max);
                return compare > 0 || (excludeEqual && compare == 0);
            }

            @Override
            public String thresholdValue() {
                return maximumText;
            }
        };
    }
}
 
Example 19
Source File: AvroJson.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
private static boolean matches(JsonNode datum, Schema schema) {
  switch (schema.getType()) {
    case RECORD:
      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.defaultVal() == 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;
}
 
Example 20
Source File: JsonUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
private static boolean matches(JsonNode datum, Schema schema) {
  switch (schema.getType()) {
    case RECORD:
      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;
}