use of com.google.gson.JsonSerializationContext in project incubator-gobblin by apache.
the class AvroToJdbcEntryConverterTest method testFlattening.
@Test
public void testFlattening() throws IOException, SchemaConversionException, SQLException, URISyntaxException, DataConversionException {
final String db = "db";
final String table = "users";
Map<String, JdbcType> dateColums = new HashMap<>();
dateColums.put("date_of_birth", JdbcType.DATE);
dateColums.put("last_modified", JdbcType.TIME);
dateColums.put("created", JdbcType.TIMESTAMP);
JdbcWriterCommands mockWriterCommands = mock(JdbcWriterCommands.class);
when(mockWriterCommands.retrieveDateColumns(db, table)).thenReturn(dateColums);
JdbcWriterCommandsFactory factory = mock(JdbcWriterCommandsFactory.class);
when(factory.newInstance(any(State.class), any(Connection.class))).thenReturn(mockWriterCommands);
List<JdbcEntryMetaDatum> jdbcEntryMetaData = new ArrayList<>();
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("name", JdbcType.VARCHAR));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("favorite_number", JdbcType.VARCHAR));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("favorite_color", JdbcType.VARCHAR));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("date_of_birth", JdbcType.DATE));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("last_modified", JdbcType.TIME));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("created", JdbcType.TIMESTAMP));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("nested1_nested1_string", JdbcType.VARCHAR));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("nested1_nested1_int", JdbcType.INTEGER));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("nested1_nested2_union_nested2_string", JdbcType.VARCHAR));
jdbcEntryMetaData.add(new JdbcEntryMetaDatum("nested1_nested2_union_nested2_int", JdbcType.INTEGER));
JdbcEntrySchema expected = new JdbcEntrySchema(jdbcEntryMetaData);
Schema inputSchema = new Schema.Parser().parse(getClass().getResourceAsStream("/converter/pickfields_nested_with_union.avsc"));
WorkUnitState workUnitState = new WorkUnitState();
workUnitState.appendToListProp(JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME, table);
AvroToJdbcEntryConverter converter = new AvroToJdbcEntryConverter(workUnitState);
Map<String, JdbcType> dateColumnMapping = Maps.newHashMap();
dateColumnMapping.put("date_of_birth", JdbcType.DATE);
dateColumnMapping.put("last_modified", JdbcType.TIME);
dateColumnMapping.put("created", JdbcType.TIMESTAMP);
workUnitState.appendToListProp(AvroToJdbcEntryConverter.CONVERTER_AVRO_JDBC_DATE_FIELDS, new Gson().toJson(dateColumnMapping));
JdbcEntrySchema actualSchema = converter.convertSchema(inputSchema, workUnitState);
Assert.assertEquals(expected, actualSchema);
try (DataFileReader<GenericRecord> srcDataFileReader = new DataFileReader<GenericRecord>(new File(getClass().getResource("/converter/pickfields_nested_with_union.avro").toURI()), new GenericDatumReader<GenericRecord>(inputSchema))) {
List<JdbcEntryData> entries = new ArrayList<>();
while (srcDataFileReader.hasNext()) {
JdbcEntryData actualData = converter.convertRecord(actualSchema, srcDataFileReader.next(), workUnitState).iterator().next();
entries.add(actualData);
}
final JsonSerializer<JdbcEntryDatum> datumSer = new JsonSerializer<JdbcEntryDatum>() {
@Override
public JsonElement serialize(JdbcEntryDatum datum, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jso = new JsonObject();
if (datum.getVal() == null) {
jso.add(datum.getColumnName(), null);
return jso;
}
if (datum.getVal() instanceof Date) {
jso.addProperty(datum.getColumnName(), ((Date) datum.getVal()).getTime());
} else if (datum.getVal() instanceof Timestamp) {
jso.addProperty(datum.getColumnName(), ((Timestamp) datum.getVal()).getTime());
} else if (datum.getVal() instanceof Time) {
jso.addProperty(datum.getColumnName(), ((Time) datum.getVal()).getTime());
} else {
jso.addProperty(datum.getColumnName(), datum.getVal().toString());
}
return jso;
}
};
JsonSerializer<JdbcEntryData> serializer = new JsonSerializer<JdbcEntryData>() {
@Override
public JsonElement serialize(JdbcEntryData src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray arr = new JsonArray();
for (JdbcEntryDatum datum : src) {
arr.add(datumSer.serialize(datum, datum.getClass(), context));
}
return arr;
}
};
Gson gson = new GsonBuilder().registerTypeAdapter(JdbcEntryData.class, serializer).serializeNulls().create();
JsonElement actualSerialized = gson.toJsonTree(entries);
JsonElement expectedSerialized = new JsonParser().parse(new InputStreamReader(getClass().getResourceAsStream("/converter/pickfields_nested_with_union.json")));
Assert.assertEquals(actualSerialized, expectedSerialized);
}
converter.close();
}
use of com.google.gson.JsonSerializationContext in project BuildCraft by BuildCraft.
the class JsonUtil method registerNbtSerializersDeserializers.
public static GsonBuilder registerNbtSerializersDeserializers(GsonBuilder gsonBuilder) {
return gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return type.getRawType() == NBTBase.class ? new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
// noinspection unchecked, RedundantCast
Streams.write(((JsonSerializer<T>) (JsonSerializer<NBTBase>) (src, typeOfSrc, context) -> {
if (src == NBTUtilBC.NBT_NULL) {
return JsonNull.INSTANCE;
}
switch(src.getId()) {
case Constants.NBT.TAG_BYTE:
return context.serialize(src, NBTTagByte.class);
case Constants.NBT.TAG_SHORT:
return context.serialize(src, NBTTagShort.class);
case Constants.NBT.TAG_INT:
return context.serialize(src, NBTTagInt.class);
case Constants.NBT.TAG_LONG:
return context.serialize(src, NBTTagLong.class);
case Constants.NBT.TAG_FLOAT:
return context.serialize(src, NBTTagFloat.class);
case Constants.NBT.TAG_DOUBLE:
return context.serialize(src, NBTTagDouble.class);
case Constants.NBT.TAG_BYTE_ARRAY:
return context.serialize(src, NBTTagByteArray.class);
case Constants.NBT.TAG_STRING:
return context.serialize(src, NBTTagString.class);
case Constants.NBT.TAG_LIST:
return context.serialize(src, NBTTagList.class);
case Constants.NBT.TAG_COMPOUND:
return context.serialize(src, NBTTagCompound.class);
case Constants.NBT.TAG_INT_ARRAY:
return context.serialize(src, NBTTagIntArray.class);
default:
throw new IllegalArgumentException(src.toString());
}
}).serialize(value, type.getType(), new JsonSerializationContext() {
@Override
public JsonElement serialize(Object src) {
return gson.toJsonTree(src);
}
@Override
public JsonElement serialize(Object src, Type typeOfSrc) {
return gson.toJsonTree(src, typeOfSrc);
}
}), out);
}
@Override
public T read(JsonReader in) throws IOException {
return ((JsonDeserializer<T>) (json, typeOfT, context) -> {
if (json.isJsonNull()) {
// noinspection unchecked
return (T) NBTUtilBC.NBT_NULL;
}
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
Number number = json.getAsJsonPrimitive().getAsNumber();
if (number instanceof BigInteger || number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte) {
return context.deserialize(json, NBTTagLong.class);
} else {
return context.deserialize(json, NBTTagDouble.class);
}
}
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean()) {
return context.deserialize(new JsonPrimitive(json.getAsJsonPrimitive().getAsBoolean() ? (byte) 1 : (byte) 0), NBTTagByte.class);
}
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
return context.deserialize(json, NBTTagString.class);
}
if (json.isJsonArray()) {
return context.deserialize(json, NBTTagList.class);
}
if (json.isJsonObject()) {
return context.deserialize(json, NBTTagCompound.class);
}
throw new IllegalArgumentException(json.toString());
}).deserialize(Streams.parse(in), type.getType(), gson::fromJson);
}
} : null;
}
}).registerTypeAdapter(NBTTagByte.class, (JsonSerializer<NBTTagByte>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getByte())).registerTypeAdapter(NBTTagByte.class, (JsonDeserializer<NBTTagByte>) (json, typeOfT, context) -> new NBTTagByte(json.getAsJsonPrimitive().getAsByte())).registerTypeAdapter(NBTTagShort.class, (JsonSerializer<NBTTagShort>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getShort())).registerTypeAdapter(NBTTagShort.class, (JsonDeserializer<NBTTagShort>) (json, typeOfT, context) -> new NBTTagShort(json.getAsJsonPrimitive().getAsShort())).registerTypeAdapter(NBTTagInt.class, (JsonSerializer<NBTTagInt>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getInt())).registerTypeAdapter(NBTTagInt.class, (JsonDeserializer<NBTTagInt>) (json, typeOfT, context) -> new NBTTagInt(json.getAsJsonPrimitive().getAsInt())).registerTypeAdapter(NBTTagLong.class, (JsonSerializer<NBTTagLong>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getLong())).registerTypeAdapter(NBTTagLong.class, (JsonDeserializer<NBTTagLong>) (json, typeOfT, context) -> new NBTTagLong(json.getAsJsonPrimitive().getAsLong())).registerTypeAdapter(NBTTagFloat.class, (JsonSerializer<NBTTagFloat>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getFloat())).registerTypeAdapter(NBTTagFloat.class, (JsonDeserializer<NBTTagFloat>) (json, typeOfT, context) -> new NBTTagFloat(json.getAsJsonPrimitive().getAsFloat())).registerTypeAdapter(NBTTagDouble.class, (JsonSerializer<NBTTagDouble>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getDouble())).registerTypeAdapter(NBTTagDouble.class, (JsonDeserializer<NBTTagDouble>) (json, typeOfT, context) -> new NBTTagDouble(json.getAsJsonPrimitive().getAsDouble())).registerTypeAdapter(NBTTagByteArray.class, (JsonSerializer<NBTTagByteArray>) (src, typeOfSrc, context) -> {
JsonArray jsonArray = new JsonArray();
for (byte element : src.getByteArray()) {
jsonArray.add(new JsonPrimitive(element));
}
return jsonArray;
}).registerTypeAdapter(NBTTagByteArray.class, (JsonDeserializer<NBTTagByteArray>) (json, typeOfT, context) -> new NBTTagByteArray(ArrayUtils.toPrimitive(StreamSupport.stream(json.getAsJsonArray().spliterator(), false).map(JsonElement::getAsByte).toArray(Byte[]::new)))).registerTypeAdapter(NBTTagString.class, (JsonSerializer<NBTTagString>) (src, typeOfSrc, context) -> new JsonPrimitive(src.getString())).registerTypeAdapter(NBTTagString.class, (JsonDeserializer<NBTTagString>) (json, typeOfT, context) -> new NBTTagString(json.getAsJsonPrimitive().getAsString())).registerTypeAdapter(NBTTagList.class, (JsonSerializer<NBTTagList>) (src, typeOfSrc, context) -> {
JsonArray jsonArray = new JsonArray();
for (int i = 0; i < src.tagCount(); i++) {
NBTBase element = src.get(i);
jsonArray.add(context.serialize(element, NBTBase.class));
}
return jsonArray;
}).registerTypeAdapter(NBTTagList.class, (JsonDeserializer<NBTTagList>) (json, typeOfT, context) -> {
NBTTagList nbtTagList = new NBTTagList();
StreamSupport.stream(json.getAsJsonArray().spliterator(), false).map(element -> context.<NBTBase>deserialize(element, NBTBase.class)).forEach(nbtTagList::appendTag);
return nbtTagList;
}).registerTypeAdapter(NBTTagCompound.class, (JsonSerializer<NBTTagCompound>) (src, typeOfSrc, context) -> {
JsonObject jsonObject = new JsonObject();
for (String key : src.getKeySet()) {
jsonObject.add(key, context.serialize(src.getTag(key), NBTBase.class));
}
return jsonObject;
}).registerTypeAdapter(NBTTagCompound.class, (JsonDeserializer<NBTTagCompound>) (json, typeOfT, context) -> {
NBTTagCompound nbtTagCompound = new NBTTagCompound();
for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
nbtTagCompound.setTag(entry.getKey(), context.deserialize(entry.getValue(), NBTBase.class));
}
return nbtTagCompound;
}).registerTypeAdapter(NBTTagIntArray.class, (JsonSerializer<NBTTagIntArray>) (src, typeOfSrc, context) -> {
JsonArray jsonArray = new JsonArray();
for (int element : src.getIntArray()) {
jsonArray.add(new JsonPrimitive(element));
}
return jsonArray;
}).registerTypeAdapter(NBTTagIntArray.class, (JsonDeserializer<NBTTagIntArray>) (json, typeOfT, context) -> new NBTTagIntArray(StreamSupport.stream(json.getAsJsonArray().spliterator(), false).mapToInt(JsonElement::getAsByte).toArray()));
}
use of com.google.gson.JsonSerializationContext in project sakuli by ConSol.
the class DateSerializerTest method setUp.
@BeforeMethod
public void setUp() throws Exception {
jsonSerializationContext = mock(JsonSerializationContext.class);
doReturn(new JsonPrimitive("2017-10-01T00:00:00.000+02:00")).when(jsonSerializationContext).serialize(any(), eq(DateTime.class));
}
use of com.google.gson.JsonSerializationContext in project sakuli by ConSol.
the class ThrowableSerializerTest method setUp.
@BeforeMethod
public void setUp() throws Exception {
jsonSerializationContext = mock(JsonSerializationContext.class);
doReturn(new JsonPrimitive("pathToScreenshot")).when(jsonSerializationContext).serialize(any(), eq(Path.class));
}
use of com.google.gson.JsonSerializationContext in project molgenis by molgenis.
the class EntitySerializerTest method testSerialize.
@Test
public void testSerialize() throws Exception {
EntityType entityType = mock(EntityType.class);
when(entityType.getId()).thenReturn("entity");
Attribute oneToManyAttr = mock(Attribute.class);
String oneToManyAttrName = "oneToManyAttr";
when(oneToManyAttr.getName()).thenReturn(oneToManyAttrName);
when(oneToManyAttr.getDataType()).thenReturn(ONE_TO_MANY);
Attribute manyToOneAttr = mock(Attribute.class);
String manyToOneAttrName = "xrefAttr";
when(manyToOneAttr.getName()).thenReturn(manyToOneAttrName);
when(manyToOneAttr.getDataType()).thenReturn(XREF);
when(entityType.getAtomicAttributes()).thenReturn(newArrayList(oneToManyAttr, manyToOneAttr));
EntityType refEntityType = mock(EntityType.class);
when(refEntityType.getId()).thenReturn("refEntity");
String oneToManyEntity0IdValue = "oneToManyEntity0";
String oneToManyEntity0LabelValue = "oneToManyEntityLabel0";
Entity oneToManyEntity0 = mock(Entity.class);
when(oneToManyEntity0.getEntityType()).thenReturn(refEntityType);
when(oneToManyEntity0.getIdValue()).thenReturn(oneToManyEntity0IdValue);
when(oneToManyEntity0.getLabelValue()).thenReturn(oneToManyEntity0LabelValue);
String oneToManyEntity1IdValue = "oneToManyEntity1";
String oneToManyEntity1LabelValue = "oneToManyEntityLabel1";
Entity oneToManyEntity1 = mock(Entity.class);
when(oneToManyEntity1.getIdValue()).thenReturn(oneToManyEntity1IdValue);
when(oneToManyEntity1.getLabelValue()).thenReturn(oneToManyEntity1LabelValue);
when(oneToManyEntity1.getEntityType()).thenReturn(refEntityType);
List<Entity> oneToManyEntities = newArrayList(oneToManyEntity0, oneToManyEntity1);
String manyToOneEntityIdValue = "xrefEntity0";
String manyToOneEntityLabelValue = "xrefEntityLabel0";
Entity manyToOneEntity = mock(Entity.class);
when(manyToOneEntity.getEntityType()).thenReturn(refEntityType);
when(manyToOneEntity.getIdValue()).thenReturn(manyToOneEntityIdValue);
when(manyToOneEntity.getLabelValue()).thenReturn(manyToOneEntityLabelValue);
Entity entity = mock(Entity.class);
when(entity.getEntityType()).thenReturn(entityType);
when(entity.get(oneToManyAttrName)).thenReturn(oneToManyEntities);
when(entity.get(manyToOneAttrName)).thenReturn(manyToOneEntity);
when(entity.getEntities(oneToManyAttrName)).thenReturn(oneToManyEntities);
when(entity.getEntity(manyToOneAttrName)).thenReturn(manyToOneEntity);
Type type = mock(Type.class);
JsonSerializationContext context = mock(JsonSerializationContext.class);
when(context.serialize(oneToManyEntity0IdValue)).thenReturn(new JsonPrimitive(oneToManyEntity0IdValue));
when(context.serialize(oneToManyEntity0LabelValue)).thenReturn(new JsonPrimitive(oneToManyEntity0LabelValue));
when(context.serialize(oneToManyEntity1IdValue)).thenReturn(new JsonPrimitive(oneToManyEntity1IdValue));
when(context.serialize(oneToManyEntity1LabelValue)).thenReturn(new JsonPrimitive(oneToManyEntity1LabelValue));
when(context.serialize(manyToOneEntityIdValue)).thenReturn(new JsonPrimitive(manyToOneEntityIdValue));
when(context.serialize(manyToOneEntityLabelValue)).thenReturn(new JsonPrimitive(manyToOneEntityLabelValue));
String expectedJson = "{\"__entityTypeId\":\"entity\",\"oneToManyAttr\":[{\"__entityTypeId\":\"refEntity\",\"__idValue\":\"oneToManyEntity0\",\"__labelValue\":\"oneToManyEntityLabel0\"},{\"__entityTypeId\":\"refEntity\",\"__idValue\":\"oneToManyEntity1\",\"__labelValue\":\"oneToManyEntityLabel1\"}],\"xrefAttr\":{\"__entityTypeId\":\"refEntity\",\"__idValue\":\"xrefEntity0\",\"__labelValue\":\"xrefEntityLabel0\"}}";
assertEquals(entitySerializer.serialize(entity, type, context).toString(), expectedJson);
}
Aggregations