public static JsonNode get( final PrimitiveObject obj ) throws IOException{ switch( obj.getPrimitiveType() ){ case BOOLEAN: return BooleanNode.valueOf( obj.getBoolean() ); case BYTE: return IntNode.valueOf( obj.getInt() ); case SHORT: return IntNode.valueOf( obj.getInt() ); case INTEGER: return IntNode.valueOf( obj.getInt() ); case LONG: return new LongNode( obj.getLong() ); case FLOAT: return new DoubleNode( obj.getDouble() ); case DOUBLE: return new DoubleNode( obj.getDouble() ); case STRING: return new TextNode( obj.getString() ); case BYTES: return new BinaryNode( obj.getBytes() ); default: return new TextNode( null ); } }
@Activate public void activate() { Serializer serializer = Serializer.using(KryoNamespaces.API, ObjectNode.class, ArrayNode.class, JsonNodeFactory.class, LinkedHashMap.class, TextNode.class, BooleanNode.class, LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class, NullNode.class); prefsConsistentMap = storageService.<String, ObjectNode>consistentMapBuilder() .withName(ONOS_USER_PREFERENCES) .withSerializer(serializer) .withRelaxedReadConsistency() .build(); prefsConsistentMap.addListener(prefsListener); prefs = prefsConsistentMap.asJavaMap(); register(core); log.info("Started"); }
@Activate public void activate() { KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder() .register(KryoNamespaces.API) .register(ConfigKey.class, ObjectNode.class, ArrayNode.class, JsonNodeFactory.class, LinkedHashMap.class, TextNode.class, BooleanNode.class, LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class, NullNode.class); configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder() .withSerializer(Serializer.using(kryoBuilder.build())) .withName("onos-network-configs") .withRelaxedReadConsistency() .build(); configs.addListener(listener); log.info("Started"); }
@Test public void deserialize() throws Exception { StratumMessage m1 = readValue("{\"id\":123, \"method\":\"a.b\", \"params\":[1, \"x\", null]}"); assertEquals(123L, (long)m1.id); assertEquals("a.b", m1.method); assertEquals(Lists.newArrayList(new IntNode(1), new TextNode("x"), NullNode.getInstance()), m1.params); StratumMessage m2 = readValue("{\"id\":123, \"result\":{\"x\": 123}}"); assertTrue(m2.isResult()); assertEquals(123L, (long)m2.id); assertEquals(mapper.createObjectNode().put("x", 123), m2.result); StratumMessage m3 = readValue("{\"id\":123, \"result\":[\"x\"]}"); assertEquals(123L, (long)m3.id); //noinspection AssertEqualsBetweenInconvertibleTypes assertEquals(mapper.createArrayNode().add("x"), m3.result); }
/** * Obtain the value for 'name' from the given stack frame's node. */ private JsonNode resolve(Object name, Frame frame) { // Special internal variable @index points to the array index for a // given stack frame. if (name instanceof String) { String strName = (String)name; if (strName.startsWith("@")) { if (name.equals("@index")) { if (frame.currentIndex != -1) { // @index is 1-based return new IntNode(frame.currentIndex + 1); } return Constants.MISSING_NODE; } JsonNode node = frame.getVar(strName); return (node == null) ? Constants.MISSING_NODE : node; } // Fall through } return nodePath(frame.node(), name); }
@Test public void deserializePrimitiveTest() { assertEquals(Boolean.TRUE, Deserializer.fromJson(TypeNode.fromString("bool"), BooleanNode.TRUE)); assertEquals(Boolean.FALSE, Deserializer.fromJson(TypeNode.fromString("bool"), BooleanNode.FALSE)); assertEquals('a', Deserializer.fromJson(TypeNode.fromString("char"), TextNode.valueOf("a"))); assertEquals(Integer.valueOf(123), Deserializer.fromJson(TypeNode.fromString("int"), IntNode.valueOf(123))); assertEquals(Long.valueOf(123), Deserializer.fromJson(TypeNode.fromString("long"), IntNode.valueOf(123))); assertEquals(Double.valueOf(123.0), Deserializer.fromJson(TypeNode.fromString("double"), DoubleNode.valueOf(123.0))); assertEquals("algohub", Deserializer.fromJson(TypeNode.fromString("string"), TextNode.valueOf("algohub"))); }
@Test public void primitiveToJsonTest() { assertEquals(BooleanNode.TRUE, Serializer.toJson(true, TypeNode.fromString("bool"))); assertEquals(BooleanNode.FALSE, Serializer.toJson(false, TypeNode.fromString("bool"))); assertEquals(TextNode.valueOf("a"), Serializer.toJson('a', TypeNode.fromString("char"))); assertEquals(IntNode.valueOf(123), Serializer.toJson(123, TypeNode.fromString("int"))); assertEquals(LongNode.valueOf(123), Serializer.toJson(123L, TypeNode.fromString("long"))); assertEquals(DoubleNode.valueOf(123.0), Serializer.toJson(123.0, TypeNode.fromString("double"))); assertEquals(TextNode.valueOf("123"), Serializer.toJson("123", TypeNode.fromString("string"))); }
@Override public Location deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); int id = (Integer) ((IntNode) node.get("locationId")).numberValue(); String countryCode = node.get("countryCode").asText(); String defaultLanguage = node.get("defaultLanguage").asText(); Locale locale = new Locale.Builder().setLanguage(defaultLanguage).setRegion(countryCode).build(); String name = node.get("locationName").asText(); JsonNode mapSection = node.get("mapSection"); Coordinates center = new Coordinates(mapSection.get("center").get("latitude").asDouble(), mapSection.get("center").get("longitude").asDouble()); Coordinates lowerRight = new Coordinates(mapSection.get("lowerRight").get("latitude").asDouble(), mapSection.get("lowerRight").get("longitude").asDouble()); Coordinates upperLeft = new Coordinates(mapSection.get("upperLeft").get("latitude").asDouble(), mapSection.get("upperLeft").get("longitude").asDouble()); TimeZone timezone = TimeZone.getTimeZone(node.get("timezone").asText()); return new Location(id, locale, name, center, lowerRight, upperLeft, timezone); }
@Deprecated public static ValueNode toValueNode(Object value) { if (value == null) return NullNode.instance; if (value instanceof ValueNode) return (ValueNode) value; if (value instanceof Boolean) return BooleanNode.valueOf((boolean) value); else if (value instanceof Integer) return IntNode.valueOf((int) value); else if (value instanceof Long) return LongNode.valueOf((long) value); else if (value instanceof Double) return DoubleNode.valueOf((double) value); else if (value instanceof Float) return FloatNode.valueOf((float) value); return TextNode.valueOf(value.toString()); }
public static ValueNode toValueNode(Object value) { if (value == null) return NullNode.instance; if (value instanceof ValueNode) return (ValueNode) value; if (value instanceof Boolean) return BooleanNode.valueOf((boolean) value); else if (value instanceof Integer) return IntNode.valueOf((int) value); else if (value instanceof Long) return LongNode.valueOf((long) value); else if (value instanceof Double) return DoubleNode.valueOf((double) value); else if (value instanceof Float) return FloatNode.valueOf((float) value); return TextNode.valueOf(value.toString()); }
private static JobLaunchingData getJobLaunchingData(final JsonNode payload, final JsonNode jobJsonNode) { final String jobName = jobJsonNode.get("name").asText(); final JobParametersBuilder jobParametersBuilder = new JobParametersBuilder(); final JsonNode commercetools = payload.get("commercetools"); commercetools.fields().forEachRemaining(stringJsonNodeEntry -> { jobParametersBuilder.addString("commercetools." + stringJsonNodeEntry.getKey(), stringJsonNodeEntry.getValue().asText()); }); jobJsonNode.fields().forEachRemaining(jobField -> { //TODO prepare for other classes if (jobField.getValue() instanceof TextNode) { jobParametersBuilder.addString(jobField.getKey(), jobField.getValue().asText()); } else if (jobField.getValue() instanceof IntNode || jobField.getValue() instanceof LongNode) { jobParametersBuilder.addLong(jobField.getKey(), jobField.getValue().asLong()); } }); return new JobLaunchingData(jobName, jobParametersBuilder.toJobParameters()); }
/** * Get an Avro schema using {@link AvroUtils#wrapAsNullable(Schema)} by node type. * * @param node Json node. * @return an Avro schema using {@link AvroUtils#wrapAsNullable(Schema)} by node type. */ public Schema getAvroSchema(JsonNode node) { if (node instanceof TextNode) { return AvroUtils.wrapAsNullable(AvroUtils._string()); } else if (node instanceof IntNode) { return AvroUtils.wrapAsNullable(AvroUtils._int()); } else if (node instanceof LongNode) { return AvroUtils.wrapAsNullable(AvroUtils._long()); } else if (node instanceof DoubleNode) { return AvroUtils.wrapAsNullable(AvroUtils._double()); } else if (node instanceof BooleanNode) { return AvroUtils.wrapAsNullable(AvroUtils._boolean()); } else if (node instanceof NullNode) { return AvroUtils.wrapAsNullable(AvroUtils._string()); } else { return Schema.createRecord(getSubRecordRandomName(), null, null, false, getFields(node)); } }
@Test public void add() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data String name = uid("T"); EntityDataStoreRecord record = store.add(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(15)); // Checks assertNotNull(record); assertTrue(record.getId() > 0); assertEquals(CATEGORY, record.getCategory()); assertNotNull(record.getSignature()); assertEquals(name, record.getName()); assertNull(record.getGroupName()); assertEquals(branch.getProjectEntityType(), record.getEntity().getProjectEntityType()); assertEquals(branch.getId(), record.getEntity().getId()); assertJsonEquals( new IntNode(15), record.getData() ); }
@Test public void replaceOrAdd() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data String name = uid("T"); EntityDataStoreRecord record = store.add(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(15)); // Checks assertTrue(record.getId() > 0); assertEquals(CATEGORY, record.getCategory()); assertJsonEquals( new IntNode(15), record.getData() ); // Updates the same name EntityDataStoreRecord secondRecord = store.replaceOrAdd(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(16)); // Checks assertEquals(record.getId(), secondRecord.getId()); assertJsonEquals( new IntNode(16), secondRecord.getData() ); }
@Test public void replaveOrAddForNewRecord() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data String name = uid("T"); EntityDataStoreRecord record = store.add(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(15)); // Checks assertTrue(record.getId() > 0); assertEquals(CATEGORY, record.getCategory()); assertJsonEquals( new IntNode(15), record.getData() ); // Updates with a different same name EntityDataStoreRecord secondRecord = store.replaceOrAdd(branch, CATEGORY, name + "2", Signature.of(TEST_USER), null, new IntNode(16)); // Checks assertNotEquals(record.getId(), secondRecord.getId()); assertJsonEquals( new IntNode(16), secondRecord.getData() ); }
@Test public void delete_by_group() { // Entity Branch branch = do_create_branch(); // Adds some data for the group String group = uid("G"); String name = uid("T"); int id1 = store.add(branch, CATEGORY, name + 1, Signature.of(TEST_USER), group, new IntNode(10)).getId(); int id2 = store.add(branch, CATEGORY, name + 2, Signature.of(TEST_USER), group, new IntNode(10)).getId(); // Gets by ID assertTrue(store.getById(branch, id1).isPresent()); assertTrue(store.getById(branch, id2).isPresent()); // Deletes by group store.deleteByGroup(branch, CATEGORY, group); // Gets by ID ot possible any longer assertFalse(store.getById(branch, id1).isPresent()); assertFalse(store.getById(branch, id2).isPresent()); }
@Test public void delete_by_category() { // Entities Branch branch1 = do_create_branch(); Branch branch2 = do_create_branch(); // Adds some data with same name for different entities String name = uid("T"); int id1 = store.add(branch1, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(10)).getId(); int id2 = store.add(branch2, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(10)).getId(); // Gets by ID assertTrue(store.getById(branch1, id1).isPresent()); assertTrue(store.getById(branch2, id2).isPresent()); // Deletes by category store.deleteByCategoryBefore(CATEGORY, Time.now()); // Gets by ID ot possible any longer assertFalse(store.getById(branch1, id1).isPresent()); assertFalse(store.getById(branch2, id2).isPresent()); }
@Test public void last_by_category_and_name() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data, twice, for the same name String name = uid("T"); @SuppressWarnings("unused") int id1 = store.add(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(15)).getId(); int id2 = store.add(branch, CATEGORY, name, Signature.of(TEST_USER), null, new IntNode(16)).getId(); // Gets last by category / name EntityDataStoreRecord record = store.findLastByCategoryAndName(branch, CATEGORY, name, Time.now()).orElse(null); // Checks assertNotNull(record); assertEquals(record.getId(), id2); assertJsonEquals( new IntNode(16), record.getData() ); }
@Test public void last_by_category_and_group_and_name() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data, twice, for the same name, and several names, but for a same group String group = uid("G"); String name1 = uid("T"); String name2 = uid("T"); @SuppressWarnings("unused") int id11 = store.add(branch, CATEGORY, name1, Signature.of(TEST_USER), group, new IntNode(11)).getId(); int id12 = store.add(branch, CATEGORY, name1, Signature.of(TEST_USER), group, new IntNode(12)).getId(); @SuppressWarnings("unused") int id21 = store.add(branch, CATEGORY, name2, Signature.of(TEST_USER), group, new IntNode(21)).getId(); @SuppressWarnings("unused") int id22 = store.add(branch, CATEGORY, name2, Signature.of(TEST_USER), group, new IntNode(22)).getId(); // Gets last by category / name / group EntityDataStoreRecord record = store.findLastByCategoryAndGroupAndName(branch, CATEGORY, group, name1).orElse(null); // Checks assertNotNull(record); assertEquals(record.getId(), id12); assertJsonEquals( new IntNode(12), record.getData() ); }
@Test public void last_by_category() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data, twice, for the same name, and several names, but for a same group String name1 = uid("T"); String name2 = uid("T"); String name3 = uid("T"); @SuppressWarnings("unused") int id11 = store.add(branch, CATEGORY, name1, Signature.of(TEST_USER), null, new IntNode(11)).getId(); int id12 = store.add(branch, CATEGORY, name1, Signature.of(TEST_USER), null, new IntNode(12)).getId(); @SuppressWarnings("unused") int id21 = store.add(branch, CATEGORY, name2, Signature.of(TEST_USER), null, new IntNode(21)).getId(); int id22 = store.add(branch, CATEGORY, name2, Signature.of(TEST_USER), null, new IntNode(22)).getId(); @SuppressWarnings("unused") int id31 = store.add(branch, CATEGORY, name3, Signature.of(TEST_USER), null, new IntNode(31)).getId(); @SuppressWarnings("unused") int id32 = store.add(branch, CATEGORY, name3, Signature.of(TEST_USER), null, new IntNode(32)).getId(); int id33 = store.add(branch, CATEGORY, name3, Signature.of(TEST_USER), null, new IntNode(33)).getId(); // Gets last by name in category List<EntityDataStoreRecord> records = store.findLastRecordsByNameInCategory(branch, CATEGORY); assertEquals(3, records.size()); // Checks assertEquals(id33, records.get(0).getId()); assertEquals(id22, records.get(1).getId()); assertEquals(id12, records.get(2).getId()); }
@Test public void addObject() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data String name = uid("T"); EntityDataStoreRecord record = store.addObject(branch, CATEGORY, name, Signature.of(TEST_USER), null, 15); // Checks assertNotNull(record); assertTrue(record.getId() > 0); assertEquals(CATEGORY, record.getCategory()); assertNotNull(record.getSignature()); assertEquals(name, record.getName()); assertNull(record.getGroupName()); assertEquals(branch.getProjectEntityType(), record.getEntity().getProjectEntityType()); assertEquals(branch.getId(), record.getEntity().getId()); assertJsonEquals( new IntNode(15), record.getData() ); }
@Test public void replaceOrAddObject() throws JsonProcessingException { // Entity Branch branch = do_create_branch(); // Adds some data String name = uid("T"); EntityDataStoreRecord record = store.addObject(branch, CATEGORY, name, Signature.of(TEST_USER), null, 15); // Checks assertTrue(record.getId() > 0); assertEquals(CATEGORY, record.getCategory()); assertJsonEquals( new IntNode(15), record.getData() ); // Updates the same name EntityDataStoreRecord secondRecord = store.replaceOrAddObject(branch, CATEGORY, name, Signature.of(TEST_USER), null, 16); // Checks assertEquals(record.getId(), secondRecord.getId()); assertJsonEquals( new IntNode(16), secondRecord.getData() ); }
@Test public void compare_on_date_only() { Project project = Project.of(NameDescription.nd("P", "")); LocalDateTime now = Time.now(); LocalDateTime t1 = now.minusDays(1); LocalDateTime t2 = now.minusDays(2); List<EntityDataStoreRecord> records = Arrays.asList( new EntityDataStoreRecord(1, project, "TEST", "N1", null, Signature.of(t1, "test"), new IntNode(10)), new EntityDataStoreRecord(2, project, "TEST", "N1", null, Signature.of(t2, "test"), new IntNode(10)) ); records.sort(Comparator.naturalOrder()); assertTrue( "Newest record is first", records.get(0).getId() == 1 ); }
@Test public void compare_on_id_needed() { Project project = Project.of(NameDescription.nd("P", "")); LocalDateTime now = Time.now(); List<EntityDataStoreRecord> records = Arrays.asList( new EntityDataStoreRecord(1, project, "TEST", "N1", null, Signature.of(now, "test"), new IntNode(10)), new EntityDataStoreRecord(2, project, "TEST", "N1", null, Signature.of(now, "test"), new IntNode(10)) ); records.sort(Comparator.naturalOrder()); assertTrue( "Newest record is first by ID if dates are equal", records.get(0).getId() == 2 ); }
@Override public String format(WampMessage<JsonNode> message) { try { JsonNode[] arguments = message.getArguments(); JsonNode[] array = new JsonNode[arguments.length + 1]; System.arraycopy(arguments, 0, array, 1, arguments.length); array[0] = new IntNode(message.getMessageType()); JsonNode node = mapper.valueToTree(array); StringWriter stringWriter = new StringWriter(); mapper.writeTree(jsonFactory.createGenerator(stringWriter), node); return stringWriter.toString(); } catch (Exception ex) { return null; } }
@Override public void setProp(HasProp hasProp, String group, String key, Object value) { try { ObjectNode groupJSON = getOrCreateJsonGroup(hasProp, group); if (value == null) { groupJSON.put(key, NullNode.getInstance()); } else if (value instanceof Long) { groupJSON.put(key, LongNode.valueOf((Long) value)); } else if (value instanceof Double) { groupJSON.put(key, DoubleNode.valueOf((Double) value)); } else if (value instanceof Integer) { groupJSON.put(key, IntNode.valueOf((Integer) value)); } else if (value instanceof Float) { groupJSON.put(key, new DoubleNode((double) value)); } else if (value instanceof String) { groupJSON.put(key, TextNode.valueOf((String) value)); } else if (value instanceof Boolean) { groupJSON.put(key, BooleanNode.valueOf((Boolean) value)); } hasProp.setPropsJson(group, groupJSON.toString()); } catch (Exception e) { logSetProp(hasProp, group, key, value); } }
@Override public JsonNode apply(final JsonNode championTree) { if(championTree == null) { return championTree; } // Swap key and id. They're reversed between ddragon and the API. if(championTree.has("key") && championTree.has("id")) { final ObjectNode champion = (ObjectNode)championTree; final String id = champion.get("key").asText(); champion.set("key", champion.get("id")); champion.set("id", new IntNode(Integer.parseInt(id))); } // Fix spell coeff field final JsonNode temp = championTree.get("spells"); if(temp == null) { return championTree; } for(final JsonNode spell : temp) { SPELL_PROCESSOR.apply(spell); } return championTree; }
public boolean arrayNodesHaveSameValues(JsonNode expected, JsonNode actual) { int i = 0; for (Iterator<JsonNode> nodes = expected.elements(); nodes.hasNext(); i++) { JsonNode node = nodes.next(); if (node instanceof TextNode) { return textNodesHaveSameValue(node, actual.get(i)); } else if (node instanceof IntNode) { return intNodesHaveSameValue(node, actual.get(i)); } else if (node instanceof DoubleNode) { return doubleNodesHaveSameValue(node, actual.get(i)); } } return true; }
@Test public void testRemoval() { ObjectNode jsonObject = new ObjectNode(JsonNodeFactory.instance); jsonObject.put("key", "value"); jsonObject.put("hello", "world"); ArrayNode jsonArray = new ArrayNode(JsonNodeFactory.instance); jsonArray.add(new TextNode("Hello there")); jsonArray.add(new IntNode(42)); jsonArray.add(jsonObject); InvalidDocumentFilter filter = new InvalidDocumentFilter(source, registry); ArrayNode jsonResult = filter.doFilter(jsonArray); Assert.assertEquals(1, jsonResult.size()); Assert.assertEquals(jsonResult.get(0), jsonObject); }
/** Query parameters with both intervals are correct. */ public void queryStringBoth() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); intervalNode.setAll(buildIntervalNode(TimeUnit.MINUTE, new IntNode(-10), new IntNode(10), "relative")); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); getService().setupViewLoader(viewId, ViewType.CHART).setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)) .setTimeInterval(new RelativeInterval<TimeUnit>(TimeUnit.MINUTE, -10, 10)).loadContent(); server.assertRequestUris(viewsUri); }
/** system locale doesn't affect upper/lowercase conversion */ @Test(dataProvider = "intervalUnitProvider", groups = "locale") public void localeCaseConversion(IntervalUnit unit) throws UnknownViewTypeException { Locale.setDefault(new Locale("tr")); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode intervalNode = buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative"); // set the aggregation type to lower case in English conversion // when converted back using Turkish, i will not become I String unitType = unit instanceof DateUnit ? "dateInterval" : "timeInterval"; ObjectNode typeNode = (ObjectNode) intervalNode.get(unitType); typeNode.put("aggregationType", typeNode.get("aggregationType").asText().toLowerCase(Locale.ENGLISH)); viewNode.put("dateTimeDefinition", intervalNode); View view = ViewImpl.buildView(getService(), viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } }
/** Query parameters with both intervals are correct. */ public void queryStringBoth() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); intervalNode.setAll(buildIntervalNode(TimeUnit.MINUTE, new IntNode(-10), new IntNode(10), "relative")); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)) .setTimeInterval(new RelativeInterval<TimeUnit>(TimeUnit.MINUTE, -10, 10)).loadContent(); server.assertRequestUris(viewsUri); }
/** system locale doesn't affect upper/lowercase conversion */ @Test(dataProvider = "intervalUnitProvider", groups = "locale") public void localeCaseConversion(IntervalUnit unit) throws UnknownViewTypeException { Locale.setDefault(new Locale("tr")); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode intervalNode = buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative"); // set the aggregation type to lower case in English conversion // when converted back using Turkish, i will not become I String unitType = unit instanceof DateUnit ? "dateInterval" : "timeInterval"; ObjectNode typeNode = (ObjectNode) intervalNode.get(unitType); typeNode.put("aggregationType", typeNode.get("aggregationType").asText().toLowerCase(Locale.ENGLISH)); viewNode.put("dateTimeDefinition", intervalNode); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } }
@Override public JsonNode sample() { synchronized (this) { int r = power >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; if (power >= 0) { for (int i = 0; i <= power; i++) { r = Math.min(r, min + base.nextInt(max - min)); } } else { int n = -power; for (int i = 0; i <= n; i++) { r = Math.max(r, min + base.nextInt(max - min)); } } if (format == null) { return new IntNode(r); }else { return new TextNode(String.format(format, r)); } } }
public void testCachesAndEvictsResults() throws Exception { GeoIpCache cache = new GeoIpCache(1); final NodeCache.Loader loader = key -> new IntNode(key); JsonNode jsonNode1 = cache.get(1, loader); assertSame(jsonNode1, cache.get(1, loader)); // evict old key by adding another value cache.get(2, loader); assertNotSame(jsonNode1, cache.get(1, loader)); }
public static PrimitiveObject get( final JsonNode jsonNode ) throws IOException{ if( jsonNode instanceof TextNode ){ return new StringObj( ( (TextNode)jsonNode ).textValue() ); } else if( jsonNode instanceof BooleanNode ){ return new BooleanObj( ( (BooleanNode)jsonNode ).booleanValue() ); } else if( jsonNode instanceof IntNode ){ return new IntegerObj( ( (IntNode)jsonNode ).intValue() ); } else if( jsonNode instanceof LongNode ){ return new LongObj( ( (LongNode)jsonNode ).longValue() ); } else if( jsonNode instanceof DoubleNode ){ return new DoubleObj( ( (DoubleNode)jsonNode ).doubleValue() ); } else if( jsonNode instanceof BigIntegerNode ){ return new StringObj( ( (BigIntegerNode)jsonNode ).bigIntegerValue().toString() ); } else if( jsonNode instanceof DecimalNode ){ return new StringObj( ( (DecimalNode)jsonNode ).decimalValue().toString() ); } else if( jsonNode instanceof BinaryNode ){ return new BytesObj( ( (BinaryNode)jsonNode ).binaryValue() ); } else if( jsonNode instanceof POJONode ){ return new BytesObj( ( (POJONode)jsonNode ).binaryValue() ); } else if( jsonNode instanceof NullNode ){ return NullObj.getInstance(); } else if( jsonNode instanceof MissingNode ){ return NullObj.getInstance(); } else{ return new StringObj( jsonNode.toString() ); } }
public static JsonNode get( final Object obj ) throws IOException{ if( obj instanceof PrimitiveObject ){ return PrimitiveObjectToJsonNode.get( (PrimitiveObject)obj ); } else if( obj instanceof String ){ return new TextNode( (String)obj ); } else if( obj instanceof Boolean ){ return BooleanNode.valueOf( (Boolean)obj ); } else if( obj instanceof Short ){ return IntNode.valueOf( ( (Short)obj ).intValue() ); } else if( obj instanceof Integer ){ return IntNode.valueOf( (Integer)obj ); } else if( obj instanceof Long ){ return new LongNode( (Long)obj ); } else if( obj instanceof Float ){ return new DoubleNode( ( (Float)obj ).doubleValue() ); } else if( obj instanceof Double ){ return new DoubleNode( (Double)obj ); } else if( obj instanceof byte[] ){ return new BinaryNode( (byte[])obj ); } else if( obj == null ){ return NullNode.getInstance(); } else{ return new TextNode( obj.toString() ); } }
@Override // This method is used to tell the deserializer what it needs to do with the variable and how it shuld return them as an object. public DataPS deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); String name = node.get("name").asText(); int score = (Integer) ((IntNode) node.get("score")).numberValue(); return new DataPS(name,score); }
@Test public void deserializesDataPoint() throws IOException { final JsonNode jsonNode = mock(JsonNode.class); given(objectCodec.readTree(same(jsonParser))).willReturn(jsonNode); given(jsonNode.get(0)).willReturn(LongNode.valueOf(123L)); given(jsonNode.get(1)).willReturn(DoubleNode.valueOf(234D)); given(jsonNode.get(2)).willReturn(IntNode.valueOf(5)); final QueryResponse.Tag.Result.DataPoint dataPoint = new QueryResponse.Tag.Result.DataPointDeserializer().deserialize(jsonParser, null); assertThat(dataPoint.getTimestamp().getTime(), is(123L)); assertThat(dataPoint.getMeasure(), is(234D)); assertThat(dataPoint.getQuality(), is(5)); }