下面列出了com.fasterxml.jackson.databind.node.POJONode#com.fasterxml.jackson.databind.node.IntNode 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Judge Java objects and create JsonNode.
*/
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() );
}
}
@Test
public void testNamedModule() {
Map<String, Function> functions = new HashMap();
functions.put("test", new TestFunction());
ModuleImpl module = new ModuleImpl(functions);
Map<String, Module> modules = new HashMap();
modules.put("the test module", module);
StringReader jslt = new StringReader(
"import \"the test module\" as t t:test()"
);
Expression expr = new Parser(jslt)
.withNamedModules(modules)
.compile();
JsonNode result = expr.apply(null);
assertEquals(new IntNode(42), result);
}
@Override
public Points deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
TreeNode n = jp.getCodec().readTree(jp);
Map<String, Object> points = new HashMap<>();
Iterator<String> namesIter = n.fieldNames();
while(namesIter.hasNext()) {
String field = namesIter.next();
TreeNode child = n.get(field);
Object o;
if (child instanceof DoubleNode || child instanceof FloatNode) {
o = ((NumericNode) child).doubleValue();
} else if (child instanceof IntNode || child instanceof LongNode) {
o = ((NumericNode) child).longValue();
} else {
throw new MergeException("Unsupported Type, " + child.getClass());
}
points.put(field, o);
}
return new Points(points);
}
@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);
}
/** Does computerSummary compute the correct summary? */
@Test
public void testComputeSummary() {
// generate an answer with two rows
TableAnswerElement answer =
new TableAnswerElement(
new TableMetadata(
ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
answer.addRow(Row.builder().put("col", "val").build());
answer.addRow(Row.builder().put("col", "val").build());
Assertion assertion = new Assertion(AssertionType.countequals, new IntNode(1)); // wrong count
AnswerSummary summary = answer.computeSummary(assertion);
assertThat(summary.getNumResults(), equalTo(2));
assertThat(summary.getNumFailed(), equalTo(1));
assertThat(summary.getNumPassed(), equalTo(0));
}
/** Does evaluateAssertion do the right thing for counting assertions? */
@Test
public void testEvaluateAssertionCount() {
Assertion twoCount = new Assertion(AssertionType.countequals, new IntNode(2));
TableAnswerElement oneRow =
new TableAnswerElement(
new TableMetadata(
ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
oneRow.addRow(Row.builder().put("col", "val").build());
TableAnswerElement twoRows =
new TableAnswerElement(
new TableMetadata(
ImmutableList.of(new ColumnMetadata("col", Schema.STRING, "desc")), "no desc"));
twoRows.addRow(Row.builder().put("col", "val").build());
twoRows.addRow(Row.builder().put("col", "val").build());
assertThat(oneRow.evaluateAssertion(twoCount), equalTo(false));
assertThat(twoRows.evaluateAssertion(twoCount), equalTo(true));
}
@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;
}
@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");
}
@Override
public JsonNode sample() {
synchronized (this) {
if (dist == null) {
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));
}
} else {
return new LongNode(dist.sample());
}
}
}
/**
* Converts JsonNode to PrimitiveObject.
*/
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() );
}
}
/**
* Convert PrimitiveObject to JsonNode.
*/
public static JsonNode get( final PrimitiveObject obj ) throws IOException {
if ( obj == null ) {
return NullNode.getInstance();
}
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 NullNode.getInstance();
}
}
/**
* Merge two JSON documents.
* @param src JsonNode to be merged
* @param target JsonNode to merge to
*/
public static void merge(JsonNode src, JsonNode target) {
Iterator<Map.Entry<String, JsonNode>> fields = src.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
JsonNode subNode = entry.getValue();
switch (subNode.getNodeType()) {
case OBJECT:
writeObject(entry, target);
break;
case ARRAY:
writeArray(entry, target);
break;
case STRING:
updateObject(target, new TextNode(entry.getValue().textValue()), entry);
break;
case NUMBER:
updateObject(target, new IntNode(entry.getValue().intValue()), entry);
break;
case BOOLEAN:
updateObject(target, BooleanNode.valueOf(entry.getValue().booleanValue()), entry);
break;
default:
logger.warn("Unrecognized data type {} "+subNode.getNodeType());
}
}
}
public JsonNode call(JsonNode input, JsonNode[] arguments) {
JsonNode node = arguments[0];
if (node.isNull())
return NullNode.instance;
try {
// https://stackoverflow.com/a/18993481/90580
final Object obj = mapper.treeToValue(node, Object.class);
String jsonString = writer.writeValueAsString(obj);
return new IntNode(jsonString.hashCode());
} catch (JsonProcessingException e) {
throw new JsltException("hash-int: can't process json" + e);
}
}
public JsonNode call(JsonNode input, JsonNode[] arguments) {
if (arguments[0].isArray() || arguments[0].isObject())
return new IntNode(arguments[0].size());
else if (arguments[0].isTextual())
return new IntNode(arguments[0].asText().length());
else if (arguments[0].isNull())
return arguments[0];
else
throw new JsltException("Function size() cannot work on " + arguments[0]);
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamTagIdIsMissing() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("cp", new IntNode(1));
params.set("ct", null);
adapterRequest = givenBidder(builder -> builder.params(params));
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Missing TagId param ct");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamAdSizeIsMissing() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("cp", new IntNode(1));
params.set("ct", new IntNode(1));
params.set("cf", null);
adapterRequest = givenBidder(builder -> builder.params(params));
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Missing AdSize param cf");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamAdSizeIsInvalid() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("cp", new IntNode(1));
params.set("ct", new IntNode(1));
params.set("cf", new TextNode("invalid"));
adapterRequest = givenBidder(builder -> builder.params(params));
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Invalid AdSize param invalid");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamAdSizeWidthIsInvalid() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("cp", new IntNode(1));
params.set("ct", new IntNode(1));
params.set("cf", new TextNode("invalidX500"));
adapterRequest = givenBidder(builder -> builder.params(params));
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Invalid Width param invalid");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamAdSizeHeightIsInvalid() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("cp", new IntNode(1));
params.set("ct", new IntNode(1));
params.set("cf", new TextNode("100Xinvalid"));
adapterRequest = givenBidder(builder -> builder.params(params));
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Invalid Height param invalid");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamSiteIdIsMissing() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("accountId", new IntNode(1));
params.set("siteId", null);
adapterRequest = givenBidderCustomizable(builder -> builder.params(params), identity());
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Missing siteId param");
}
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamZoneIdIsMissing() {
// given
final ObjectNode params = mapper.createObjectNode();
params.set("accountId", new IntNode(1));
params.set("siteId", new IntNode(1));
params.set("zoneId", null);
adapterRequest = givenBidderCustomizable(builder -> builder.params(params), identity());
// when and then
assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
.isExactlyInstanceOf(PreBidException.class)
.hasMessage("Missing zoneId param");
}
@Override
public Number serialize(Object dataFetcherResult) {
if (dataFetcherResult instanceof IntNode) {
return ((IntNode) dataFetcherResult).numberValue();
} else {
throw serializationException(dataFetcherResult, IntNode.class);
}
}
@Override
public IntNode parseValue(Object input) {
if (input instanceof Number || input instanceof String) {
try {
return IntNode.valueOf(new BigInteger(input.toString()).intValueExact());
} catch (ArithmeticException e) {
throw new CoercingParseValueException(input + " does not fit into an int without a loss of precision");
}
}
if (input instanceof IntNode) {
return (IntNode) input;
}
throw valueParsingException(input, Number.class, String.class, IntNode.class);
}
@Override
public IntNode parseLiteral(Object input) {
if (input instanceof IntValue) {
try {
return IntNode.valueOf(((IntValue) input).getValue().intValueExact());
} catch (ArithmeticException e) {
throw new CoercingParseLiteralException(input + " does not fit into an int without a loss of precision");
}
} else {
throw new CoercingParseLiteralException(errorMessage(input, IntValue.class));
}
}
private static Map<Type, GraphQLScalarType> getScalarMapping() {
Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
scalarMapping.put(TextNode.class, JsonTextNode);
scalarMapping.put(BooleanNode.class, JsonBooleanNode);
scalarMapping.put(BinaryNode.class, JsonBinaryNode);
scalarMapping.put(BigIntegerNode.class, JsonBigIntegerNode);
scalarMapping.put(IntNode.class, JsonIntegerNode);
scalarMapping.put(ShortNode.class, JsonShortNode);
scalarMapping.put(DecimalNode.class, JsonDecimalNode);
scalarMapping.put(FloatNode.class, JsonFloatNode);
scalarMapping.put(DoubleNode.class, JsonDoubleNode);
scalarMapping.put(NumericNode.class, JsonDecimalNode);
return Collections.unmodifiableMap(scalarMapping);
}
public JacksonContainer(ObjectNode obj, JsonNode any, BinaryNode binary, TextNode text, IntNode integer,
DoubleNode dbl, BigIntegerNode bigInt, ArrayNode array) {
this.obj = obj;
this.any = any;
this.text = text;
this.binary = binary;
this.integer = integer;
this.dbl = dbl;
this.bigInt = bigInt;
this.array = array;
}
@Override
public ObjectNode toJson(JsonProperty jsonProperty) {
Function<Object,JsonNode> nodeCreator = value -> new IntNode((Integer) value);
final ObjectNode propertyNode = primitiveJsonPropertyBuilder.forProperty(jsonProperty)
.withType("integer").withDefaultAndAllowedValues(nodeCreator).build();
jsonProperty.getValueConstraints().getMin().ifPresent(x -> propertyNode.put("minimum", x));
jsonProperty.getValueConstraints().getMax().ifPresent(x -> propertyNode.put("maximum", x));
return propertyNode;
}
protected JsonNode resize(Context ctx, JsonNode node, boolean resizeWidth, int requested) {
String[] parts = splitDimensions(node);
if (parts == null || parts.length != 2) {
return new TextNode("Invalid source parameter. Pass in 'originalSize'.");
}
int width = Integer.parseInt(parts[0]);
int height = Integer.parseInt(parts[1]);
int value = 0;
if (resizeWidth) {
value = (int)(width * (requested / (float)height));
} else {
value = (int)(height * (requested / (float)width));
}
return new IntNode(value);
}
private Example createExample(JsonNode node) {
if (node instanceof ObjectNode) {
ObjectExample obj = new ObjectExample();
ObjectNode on = (ObjectNode) node;
for (Iterator<Entry<String, JsonNode>> x = on.fields(); x.hasNext(); ) {
Entry<String, JsonNode> i = x.next();
String key = i.getKey();
JsonNode value = i.getValue();
obj.put(key, createExample(value));
}
return obj;
} else if (node instanceof ArrayNode) {
ArrayExample arr = new ArrayExample();
ArrayNode an = (ArrayNode) node;
for (JsonNode childNode : an) {
arr.add(createExample(childNode));
}
return arr;
} else if (node instanceof DoubleNode) {
return new DoubleExample(node.doubleValue());
} else if (node instanceof IntNode || node instanceof ShortNode) {
return new IntegerExample(node.intValue());
} else if (node instanceof FloatNode) {
return new FloatExample(node.floatValue());
} else if (node instanceof BigIntegerNode) {
return new BigIntegerExample(node.bigIntegerValue());
} else if (node instanceof DecimalNode) {
return new DecimalExample(node.decimalValue());
} else if (node instanceof LongNode) {
return new LongExample(node.longValue());
} else if (node instanceof BooleanNode) {
return new BooleanExample(node.booleanValue());
} else {
return new StringExample(node.asText());
}
}
@Test
public void testDeserializeJsonWithAnyGetter() throws IOException {
JacksonAnyGetterType parsed = objectMapper.readValue(
"{\"simple_property\": \"simpleValue\", \"other_property\": 3}",
JacksonAnyGetterType.class);
assertEquals("simpleValue", parsed.getSimpleProperty());
assertNotNull(parsed.getUnknownProperties());
assertEquals(1, parsed.getUnknownProperties().size());
assertEquals(new IntNode(3), parsed.getUnknownProperties().get("other_property"));
}