com.fasterxml.jackson.databind.node.BinaryNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.BinaryNode. 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: ObjectToJsonNode.java    From yosegi with Apache License 2.0 6 votes vote down vote up
/**
 * 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() );
  }
}
 
Example #2
Source File: TestJsonUtil.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchemaInferencePrimitiveTypes() throws Exception {
  Schema recordSchema = SchemaBuilder.record("Test").fields()
      .requiredBoolean("aBool")
      .requiredString("aString")
      .requiredInt("anInt")
      .requiredLong("aLong")
      .requiredDouble("aDouble")
      .requiredString("bytes")
      .endRecord();

  String encoded = BinaryNode.valueOf("soap".getBytes("utf-8")).toString();
  String jsonSample = "{" +
      "\"aBool\": false," +
      "\"aString\": \"triangle\"," +
      "\"anInt\": 34," +
      "\"aLong\": 1420502567564," +
      "\"aDouble\": 1420502567564.9," +
      "\"bytes\": " + encoded +
      "}";

  JsonNode datum = JsonUtil.parse(jsonSample);
  Assert.assertEquals("Should produce expected schema",
      recordSchema, JsonUtil.inferSchema(datum, "Test"));

  GenericData.Record expected = new GenericData.Record(recordSchema);
  expected.put("aBool", false);
  expected.put("aString", "triangle");
  expected.put("anInt", 34);
  expected.put("aLong", 1420502567564L);
  expected.put("aDouble", 1420502567564.9);
  expected.put("bytes", encoded.substring(1, encoded.length() - 1));
  Assert.assertEquals("Should convert to record",
      expected, convertGeneric(datum, recordSchema));
}
 
Example #3
Source File: SimpleRecord.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
protected static Object toJsonValue(Object val) {
  if (SimpleRecord.class.isAssignableFrom(val.getClass())) {
    return ((SimpleRecord) val).toJsonObject();
  } else if (byte[].class == val.getClass()) {
    return new BinaryNode((byte[]) val);
  } else {
    return val;
  }
}
 
Example #4
Source File: SimpleMapRecord.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
String keyToString(Object kvValue) {
  if (kvValue == null) {
    return "null";
  }

  Class<?> type = kvValue.getClass();
  if (type.isArray()) {
    if (type.getComponentType() == boolean.class) {
      return Arrays.toString((boolean[]) kvValue);
    }
    else if (type.getComponentType() == byte.class) {
      return new BinaryNode((byte[]) kvValue).asText();
    }
    else if (type.getComponentType() == char.class) {
      return Arrays.toString((char[]) kvValue);
    }
    else if (type.getComponentType() == double.class) {
      return Arrays.toString((double[]) kvValue);
    }
    else if (type.getComponentType() == float.class) {
      return Arrays.toString((float[]) kvValue);
    }
    else if (type.getComponentType() == int.class) {
      return Arrays.toString((int[]) kvValue);
    }
    else if (type.getComponentType() == long.class) {
      return Arrays.toString((long[]) kvValue);
    }
    else if (type.getComponentType() == short.class) {
      return Arrays.toString((short[]) kvValue);
    }
    else {
      return Arrays.toString((Object[]) kvValue);
    }
  } else {
    return String.valueOf(kvValue);
  }
}
 
Example #5
Source File: Datapoint.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public Datapoint addBytesValue(long time, byte[] value) {
    initialValues();
    if (values != null && !values.isEmpty() && (type == null || !type.equals(TsdbConstants.TYPE_BYTES))) {
        throw new IllegalStateException("There is already another type in datapoint, "
                + "could not add byte array type again");
    }
    type = TsdbConstants.TYPE_BYTES;
    values.add(Lists.<JsonNode> newArrayList(new LongNode(time), new BinaryNode(value)));
    return this;
}
 
Example #6
Source File: JsonNodePiiReplacer.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode apply(JsonNode value) {
  if (value instanceof TextNode) {
    return TextNode.valueOf(replacer.replace(value.asText()));
  } else if (value instanceof BinaryNode) {
    return BinaryNode.valueOf(new byte[0]);
  } else {
    return value;
  }
}
 
Example #7
Source File: JsonTypeMappingTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #8
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #9
Source File: RosettaBinder.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private Object unwrapJsonValue(JsonNode node) {
  if (node.isNull()) {
    return null;
  } else if (node.isBoolean()) {
    return node.booleanValue();
  } else if (node.isBinary()) {
    return ((BinaryNode) node).binaryValue();
  } else if (node.isNumber()) {
    return node.numberValue();
  } else {
    return node.asText();
  }
}
 
Example #10
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public BinaryNode parseValue(Object input) {
    if (input instanceof String) {
        return BinaryNode.valueOf(decoder.decode(input.toString()));
    }
    if (input instanceof BinaryNode) {
        return (BinaryNode) input;
    }
    throw valueParsingException(input, String.class, BinaryNode.class);
}
 
Example #11
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public String serialize(Object dataFetcherResult) {
    if (dataFetcherResult instanceof BinaryNode) {
        return encoder.encodeToString(((BinaryNode) dataFetcherResult).binaryValue());
    }
    if (dataFetcherResult instanceof String) {
        return (String) dataFetcherResult;
    }
    throw serializationException(dataFetcherResult, String.class, BinaryNode.class);
}
 
Example #12
Source File: PrimitiveObjectToJsonNode.java    From yosegi with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #13
Source File: JsonNodeToPrimitiveObject.java    From yosegi with Apache License 2.0 5 votes vote down vote up
/**
 * 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() );
  }
}
 
Example #14
Source File: JsonUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
    value="BC_UNCONFIRMED_CAST",
    justification="Uses precondition to validate casts")
public static <T> T visit(JsonNode node, JsonTreeVisitor<T> visitor) {
  switch (node.getNodeType()) {
    case OBJECT:
      Preconditions.checkArgument(node instanceof ObjectNode,
          "Expected instance of ObjectNode: " + node);

      // use LinkedHashMap to preserve field order
      Map<String, T> fields = Maps.newLinkedHashMap();

      Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
      while (iter.hasNext()) {
        Map.Entry<String, JsonNode> entry = iter.next();

        visitor.recordLevels.push(entry.getKey());
        fields.put(entry.getKey(), visit(entry.getValue(), visitor));
        visitor.recordLevels.pop();
      }

      return visitor.object((ObjectNode) node, fields);

    case ARRAY:
      Preconditions.checkArgument(node instanceof ArrayNode,
          "Expected instance of ArrayNode: " + node);

      List<T> elements = Lists.newArrayListWithExpectedSize(node.size());

      for (JsonNode element : node) {
        elements.add(visit(element, visitor));
      }

      return visitor.array((ArrayNode) node, elements);

    case BINARY:
      Preconditions.checkArgument(node instanceof BinaryNode,
          "Expected instance of BinaryNode: " + node);
      return visitor.binary((BinaryNode) node);

    case STRING:
      Preconditions.checkArgument(node instanceof TextNode,
          "Expected instance of TextNode: " + node);

      return visitor.text((TextNode) node);

    case NUMBER:
      Preconditions.checkArgument(node instanceof NumericNode,
          "Expected instance of NumericNode: " + node);

      return visitor.number((NumericNode) node);

    case BOOLEAN:
      Preconditions.checkArgument(node instanceof BooleanNode,
          "Expected instance of BooleanNode: " + node);

      return visitor.bool((BooleanNode) node);

    case MISSING:
      Preconditions.checkArgument(node instanceof MissingNode,
          "Expected instance of MissingNode: " + node);

      return visitor.missing((MissingNode) node);

    case NULL:
      Preconditions.checkArgument(node instanceof NullNode,
          "Expected instance of NullNode: " + node);

      return visitor.nullNode((NullNode) node);

    default:
      throw new IllegalArgumentException(
          "Unknown node type: " + node.getNodeType() + ": " + node);
  }
}
 
Example #15
Source File: JsonUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
@Override
public Schema binary(BinaryNode ignored) {
  return Schema.create(Schema.Type.BYTES);
}
 
Example #16
Source File: DistributedWorkplaceStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Activate
public void activate() {

    appId = coreService.registerApplication("org.onosproject.workplacestore");
    log.info("appId=" + appId);

    KryoNamespace workplaceNamespace = KryoNamespace.newBuilder()
            .register(KryoNamespaces.API)
            .register(WorkflowData.class)
            .register(Workplace.class)
            .register(DefaultWorkplace.class)
            .register(WorkflowContext.class)
            .register(DefaultWorkflowContext.class)
            .register(SystemWorkflowContext.class)
            .register(WorkflowState.class)
            .register(ProgramCounter.class)
            .register(DataModelTree.class)
            .register(JsonDataModelTree.class)
            .register(List.class)
            .register(ArrayList.class)
            .register(JsonNode.class)
            .register(ObjectNode.class)
            .register(TextNode.class)
            .register(LinkedHashMap.class)
            .register(ArrayNode.class)
            .register(BaseJsonNode.class)
            .register(BigIntegerNode.class)
            .register(BinaryNode.class)
            .register(BooleanNode.class)
            .register(ContainerNode.class)
            .register(DecimalNode.class)
            .register(DoubleNode.class)
            .register(FloatNode.class)
            .register(IntNode.class)
            .register(JsonNodeType.class)
            .register(LongNode.class)
            .register(MissingNode.class)
            .register(NullNode.class)
            .register(NumericNode.class)
            .register(POJONode.class)
            .register(ShortNode.class)
            .register(ValueNode.class)
            .register(JsonNodeCreator.class)
            .register(JsonNodeFactory.class)
            .build();

    localWorkplaceMap.clear();
    workplaceMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workplace-map")
            .withApplicationId(appId)
            .build();
    workplaceMap.addListener(workplaceMapEventListener);

    localContextMap.clear();
    contextMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workflow-context-map")
            .withApplicationId(appId)
            .build();
    contextMap.addListener(contextMapEventListener);

    workplaceMapEventListener.syncLocal();
    contextMapEventListener.syncLocal();
    log.info("Started");
}
 
Example #17
Source File: JsonTypeMappingTest.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public BinaryNode getBinary() {
    return binary;
}
 
Example #18
Source File: AvroJson.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
private static <T> T visit(JsonNode node, JsonTreeVisitor<T> visitor) {
  switch (node.getNodeType()) {
    case OBJECT:
      Preconditions.checkArgument(node instanceof ObjectNode,
          "Expected instance of ObjectNode: " + node);

      // use LinkedHashMap to preserve field order
      Map<String, T> fields = Maps.newLinkedHashMap();

      Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
      while (iter.hasNext()) {
        Map.Entry<String, JsonNode> entry = iter.next();

        visitor.recordLevels.push(entry.getKey());
        fields.put(entry.getKey(), visit(entry.getValue(), visitor));
        visitor.recordLevels.pop();
      }

      return visitor.object((ObjectNode) node, fields);

    case ARRAY:
      Preconditions.checkArgument(node instanceof ArrayNode,
          "Expected instance of ArrayNode: " + node);

      List<T> elements = Lists.newArrayListWithExpectedSize(node.size());

      for (JsonNode element : node) {
        elements.add(visit(element, visitor));
      }

      return visitor.array((ArrayNode) node, elements);

    case BINARY:
      Preconditions.checkArgument(node instanceof BinaryNode,
          "Expected instance of BinaryNode: " + node);
      return visitor.binary((BinaryNode) node);

    case STRING:
      Preconditions.checkArgument(node instanceof TextNode,
          "Expected instance of TextNode: " + node);

      return visitor.text((TextNode) node);

    case NUMBER:
      Preconditions.checkArgument(node instanceof NumericNode,
          "Expected instance of NumericNode: " + node);

      return visitor.number((NumericNode) node);

    case BOOLEAN:
      Preconditions.checkArgument(node instanceof BooleanNode,
          "Expected instance of BooleanNode: " + node);

      return visitor.bool((BooleanNode) node);

    case MISSING:
      Preconditions.checkArgument(node instanceof MissingNode,
          "Expected instance of MissingNode: " + node);

      return visitor.missing((MissingNode) node);

    case NULL:
      Preconditions.checkArgument(node instanceof NullNode,
          "Expected instance of NullNode: " + node);

      return visitor.nullNode((NullNode) node);

    default:
      throw new IllegalArgumentException(
          "Unknown node type: " + node.getNodeType() + ": " + node);
  }
}
 
Example #19
Source File: AvroJson.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
@Override
public Schema binary(BinaryNode ignored) {
  return Schema.create(Schema.Type.BYTES);
}
 
Example #20
Source File: SimpleRecord.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
public void prettyPrint(PrintWriter out, int depth) {
  for (NameValue value : values) {
    out.print(Strings.repeat(".", depth));

    out.print(value.getName());
    Object val = value.getValue();
    if (val == null) {
      out.print(" = ");
      out.print("<null>");
    } else if (byte[].class == val.getClass()) {
      out.print(" = ");
      out.print(new BinaryNode((byte[]) val).asText());
    } else if (short[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((short[])val));
    } else if (int[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((int[])val));
    } else if (long[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((long[])val));
    } else if (float[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((float[])val));
    } else if (double[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((double[])val));
    } else if (boolean[].class == val.getClass()) {
      out.print(" = ");
      out.print(Arrays.toString((boolean[])val));
    } else if (val.getClass().isArray()) {
      out.print(" = ");
      out.print(Arrays.deepToString((Object[])val));
    } else if (SimpleRecord.class.isAssignableFrom(val.getClass())) {
      out.println(":");
      ((SimpleRecord)val).prettyPrint(out, depth+1);
      continue;
    } else {
      out.print(" = ");
      out.print(String.valueOf(val));
    }

    out.println();
  }
}
 
Example #21
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public BinaryNode parseLiteral(Object input) {
    return new BinaryNode(decoder.decode(literalOrException(input, StringValue.class).getValue()));
}
 
Example #22
Source File: TestJsonNodeToPrimitiveObject.java    From yosegi with Apache License 2.0 4 votes vote down vote up
@Test
public void T_get_binaryObject() throws IOException {
  PrimitiveObject obj = JsonNodeToPrimitiveObject.get( BinaryNode.valueOf( "a".getBytes() ) );
  assertTrue( ( obj instanceof BytesObj ) );
}
 
Example #23
Source File: TestPrimitiveObjectToJsonNode.java    From yosegi with Apache License 2.0 4 votes vote down vote up
@Test
public void T_get_bytes() throws IOException {
  JsonNode node = PrimitiveObjectToJsonNode.get( new BytesObj( "a".getBytes() ) );
  assertTrue( ( node instanceof BinaryNode ) );
}
 
Example #24
Source File: JsonNodePiiReplacerTest.java    From data-highway with Apache License 2.0 4 votes vote down vote up
@Test
public void binaryNode() throws Exception {
  JsonNode jsonNode = underTest.apply(BinaryNode.valueOf(new byte[] { 1, 0, 1, 2 }));
  assertThat(jsonNode.isBinary(), is(true));
  assertThat(jsonNode.binaryValue().length, is(0));
}