List of usage examples for com.fasterxml.jackson.databind JsonNode asLong
public long asLong()
From source file:com.redhat.lightblue.metadata.mongo.BSONParser.java
private static Object convertValue(JsonNode node) { if (node instanceof BigIntegerNode) { return node.bigIntegerValue(); } else if (node instanceof BooleanNode) { return new Boolean(node.asBoolean()); } else if (node instanceof DecimalNode) { return node.decimalValue(); } else if (node instanceof DoubleNode || node instanceof FloatNode) { return node.asDouble(); } else if (node instanceof IntNode || node instanceof LongNode || node instanceof ShortNode) { return node.asLong(); }//from w ww .j a v a 2s . c om return node.asText(); }
From source file:org.kiji.rest.util.RowResourceUtil.java
/** * Util method to write a rest row into Kiji. * * @param kijiTable is the table to write into. * @param entityId is the entity id of the row to write. * @param kijiRestRow is the row model to write to Kiji. * @param schemaTable is the handle to the schema table used to resolve the KijiRestCell's * writer schema if it was specified as a UID. * @throws IOException if there a failure writing the row. *///from w w w . ja v a 2 s. co m public static void writeRow(KijiTable kijiTable, EntityId entityId, KijiRestRow kijiRestRow, KijiSchemaTable schemaTable) throws IOException { final KijiTableWriter writer = kijiTable.openTableWriter(); // Default global timestamp. long globalTimestamp = System.currentTimeMillis(); try { for (Entry<String, NavigableMap<String, List<KijiRestCell>>> familyEntry : kijiRestRow.getCells() .entrySet()) { String columnFamily = familyEntry.getKey(); NavigableMap<String, List<KijiRestCell>> qualifiedCells = familyEntry.getValue(); for (Entry<String, List<KijiRestCell>> qualifiedCell : qualifiedCells.entrySet()) { final KijiColumnName column = new KijiColumnName(columnFamily, qualifiedCell.getKey()); if (!kijiTable.getLayout().exists(column)) { throw new WebApplicationException( new IllegalArgumentException("Specified column does not exist: " + column), Response.Status.BAD_REQUEST); } for (KijiRestCell restCell : qualifiedCell.getValue()) { final long timestamp; if (null != restCell.getTimestamp()) { timestamp = restCell.getTimestamp(); } else { timestamp = globalTimestamp; } if (timestamp >= 0) { // Put to either a counter or a regular cell. if (SchemaType.COUNTER == kijiTable.getLayout().getCellSchema(column).getType()) { JsonNode parsedCounterValue = BASIC_MAPPER.valueToTree(restCell.getValue()); if (parsedCounterValue.isIntegralNumber()) { // Write the counter cell. writer.put(entityId, column.getFamily(), column.getQualifier(), timestamp, parsedCounterValue.asLong()); } else if (parsedCounterValue.isContainerNode()) { if (null != parsedCounterValue.get(COUNTER_INCREMENT_KEY) && parsedCounterValue.get(COUNTER_INCREMENT_KEY).isIntegralNumber()) { // Counter incrementation does not support timestamp. if (null != restCell.getTimestamp()) { throw new WebApplicationException(new IllegalArgumentException( "Counter incrementation does not support " + "timestamp. Do not specify timestamp in request.")); } // Increment counter cell. writer.increment(entityId, column.getFamily(), column.getQualifier(), parsedCounterValue.get(COUNTER_INCREMENT_KEY).asLong()); } else { throw new WebApplicationException(new IllegalArgumentException( "Counter increment could not be parsed " + "as long: " + parsedCounterValue + ". Provide a json node such as {\"incr\" : 123}."), Response.Status.BAD_REQUEST); } } else { // Could not parse parameter to a long. throw new WebApplicationException(new IllegalArgumentException( "Counter value could not be parsed as long: " + parsedCounterValue + ". Provide a long value to set the counter."), Response.Status.BAD_REQUEST); } } else { // Write the cell. String jsonValue = restCell.getValue().toString(); // TODO: This is ugly. Converting from Map to JSON to String. if (restCell.getValue() instanceof Map<?, ?>) { JsonNode node = BASIC_MAPPER.valueToTree(restCell.getValue()); jsonValue = node.toString(); } Schema actualWriter = restCell.getWriterSchema(schemaTable); if (actualWriter == null) { throw new IOException("Unrecognized schema " + restCell.getValue()); } putCell(writer, entityId, jsonValue, column, timestamp, actualWriter); } } } } } } finally { ResourceUtils.closeOrLog(writer); } }
From source file:com.ikanow.aleph2.data_model.utils.JsonUtils.java
/** Converts (possibly recursively) a JsonNode to its Java equivalent * @param to_convert - the JsonNode to convert to... * @return - ...a Java primitive, or Map<String, Object>, or List<Object> (where Object is a java type) *///w ww . j a v a 2 s.co m public static Object jacksonToJava(final JsonNode to_convert) { final JsonNodeType type = to_convert.getNodeType(); // (we'll go old school for this...) switch (type) { case ARRAY: return Optionals.streamOf(to_convert.elements(), false).map(j -> jacksonToJava(j)) .collect(Collectors.toList()); case BINARY: try { return to_convert.binaryValue(); } catch (IOException e) { return null; } case BOOLEAN: return to_convert.asBoolean(); case NUMBER: if (to_convert.isFloatingPointNumber()) { return to_convert.asDouble(); } else { return to_convert.asLong(); } case OBJECT: return _mapper.convertValue(to_convert, Map.class); case POJO: return ((POJONode) to_convert).getPojo(); case STRING: return to_convert.asText(); default: // (MISSING, NULL) return null; } }
From source file:fr.gouv.vitam.query.parser.EsQueryParser.java
private static final Object getAsObject(JsonNode value) { if (value.isBoolean()) { return value.asBoolean(); } else if (value.canConvertToLong()) { return value.asLong(); } else if (value.isDouble()) { return value.asDouble(); } else {/*from w ww . j ava 2s . co m*/ return value.asText(); } }
From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java
/** Converts a JsonNode to a timestamp if possible * @param in/*from w w w. j av a2 s .c o m*/ * @return */ public static Optional<Long> getTimestampFromJsonNode(final JsonNode in) { if (null == in) { return Optional.empty(); } else if (in.isNumber()) { return Optional.of(in.asLong()); } else if (in.isTextual()) { return Optional.ofNullable( TimeUtils.parseIsoString(in.asText()).validation(fail -> null, success -> success.getTime())); } else { return Optional.empty(); } }
From source file:org.bndtools.rt.repository.marshall.CapReqJson.java
private static void toAttribute(CapReqBuilder builder, JsonNode attrNode) throws IllegalArgumentException { String name = getRequiredValueField(attrNode, "name").asText(); Object value;/* w w w . j a va2 s . c o m*/ JsonNode valueNode = getRequiredValueField(attrNode, "value"); JsonNode typeNode = attrNode.get("type"); AttributeType type = AttributeType.DEFAULT; if (typeNode != null) { String typeName = typeNode.asText(); type = AttributeType.parseTypeName(typeName); } if (valueNode.isFloatingPointNumber()) { if (typeNode == null || type.equals(AttributeType.DOUBLE)) value = valueNode.asDouble(); else throw new IllegalArgumentException(String .format("JSON type for value is floating point, does not match declared type '%s'", type)); } else if (valueNode.isIntegralNumber()) { if (typeNode == null || type.equals(AttributeType.LONG)) value = valueNode.asLong(); else if (type.equals(AttributeType.DOUBLE)) value = valueNode.asDouble(); else throw new IllegalArgumentException( String.format("JSON type for value is integral, does not match declared type '%s'", type)); } else if (valueNode.isTextual()) { String valueStr = valueNode.asText(); value = type.parseString(valueStr); } else { throw new IllegalArgumentException("JSON value node is not a recognised type"); } builder.addAttribute(name, value); }
From source file:com.redhat.lightblue.metadata.types.IntegerType.java
@Override public Object fromJson(JsonNode node) { if (node.isValueNode()) { return node.asLong(); } else {/*w w w . j a v a2 s. c o m*/ throw Error.get(NAME, MetadataConstants.ERR_INCOMPATIBLE_VALUE, node.toString()); } }
From source file:org.kiji.rest.serializers.JsonToSchemaOption.java
/** * {@inheritDoc}/*w w w . j ava2 s.c o m*/ */ @Override public SchemaOption deserialize(JsonParser parser, DeserializationContext context) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode schemaNode = mapper.readTree(parser); SchemaOption returnSchema = null; if (schemaNode.isInt()) { returnSchema = new SchemaOption(schemaNode.asLong()); } else { String schemaString = schemaNode.toString(); returnSchema = new SchemaOption(schemaString); } return returnSchema; }
From source file:com.baasbox.controllers.Root.java
/** * /root/configuration (POST)//from w w w . j av a2s. co m * * this method allows to set (or override) just two configuration parameter (at the moment) * the db size Threshold in bytes: * baasbox.db.size * A percentage needed by the console to show alerts on dashboard when DB size is near the defined Threshold * baasbox.db.alert * * @return a 200 OK with the new values */ @With({ RootCredentialWrapFilter.class }) public static Result overrideConfiguration() { Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); JsonNode newDBAlert = bodyJson.get(BBConfiguration.DB_ALERT_THRESHOLD); JsonNode newDBSize = bodyJson.get(BBConfiguration.DB_SIZE_THRESHOLD); try { if (newDBAlert != null && !newDBAlert.isInt() && newDBAlert.asInt() < 1) throw new IllegalArgumentException( BBConfiguration.DB_ALERT_THRESHOLD + " must be a positive integer value"); if (newDBSize != null && !newDBSize.isLong() && newDBSize.asInt() < 0) throw new IllegalArgumentException(BBConfiguration.DB_SIZE_THRESHOLD + " must be a positive integer value, or 0 to disable it"); } catch (Throwable e) { return badRequest(ExceptionUtils.getMessage(e)); } if (newDBAlert != null) BBConfiguration.setDBAlertThreshold(newDBAlert.asInt()); if (newDBSize != null) BBConfiguration.setDBSizeThreshold(BigInteger.valueOf(newDBSize.asLong())); HashMap returnMap = new HashMap(); returnMap.put(BBConfiguration.DB_ALERT_THRESHOLD, BBConfiguration.getDBAlertThreshold()); returnMap.put(BBConfiguration.DB_SIZE_THRESHOLD, BBConfiguration.getDBSizeThreshold()); try { return ok(new ObjectMapper().writeValueAsString(returnMap)); } catch (JsonProcessingException e) { return internalServerError(ExceptionUtils.getMessage(e)); } }
From source file:io.gravitee.definition.jackson.datatype.services.healthcheck.deser.HealthCheckDeserializer.java
@Override public HealthCheck deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); HealthCheck healthCheck = new HealthCheck(); final JsonNode intervalNode = node.get("interval"); if (intervalNode != null) { healthCheck.setInterval(intervalNode.asLong()); } else {//w ww . ja v a 2 s . c o m throw ctxt.mappingException("[healthcheck] Interval is required"); } final JsonNode unitNode = node.get("unit"); if (unitNode != null) { healthCheck.setUnit(TimeUnit.valueOf(unitNode.asText().toUpperCase())); } else { throw ctxt.mappingException("[healthcheck] Unit is required"); } final JsonNode requestNode = node.get("request"); if (requestNode != null) { healthCheck.setRequest(requestNode.traverse(jp.getCodec()).readValueAs(Request.class)); } else { throw ctxt.mappingException("[healthcheck] Request is required"); } final JsonNode expectationNode = node.get("expectation"); if (expectationNode != null) { healthCheck.setExpectation(expectationNode.traverse(jp.getCodec()).readValueAs(Expectation.class)); } else { Expectation expectation = new Expectation(); expectation.setAssertions(Collections.singletonList(Expectation.DEFAULT_ASSERTION)); healthCheck.setExpectation(expectation); } final JsonNode healthCheckEnabledNode = node.get("enabled"); if (healthCheckEnabledNode != null) { healthCheck.setEnabled(healthCheckEnabledNode.asBoolean(true)); } else { healthCheck.setEnabled(true); } return healthCheck; }