Search in sources :

Example 1 with JsonSerializationContext

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();
}
Also used : HashMap(java.util.HashMap) JdbcWriterCommands(org.apache.gobblin.writer.commands.JdbcWriterCommands) WorkUnitState(org.apache.gobblin.configuration.WorkUnitState) Schema(org.apache.avro.Schema) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Time(java.sql.Time) JsonSerializer(com.google.gson.JsonSerializer) Timestamp(java.sql.Timestamp) DataFileReader(org.apache.avro.file.DataFileReader) GenericRecord(org.apache.avro.generic.GenericRecord) JdbcWriterCommandsFactory(org.apache.gobblin.writer.commands.JdbcWriterCommandsFactory) JsonParser(com.google.gson.JsonParser) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) Connection(java.sql.Connection) Date(java.sql.Date) JsonArray(com.google.gson.JsonArray) DestinationType(org.apache.gobblin.writer.Destination.DestinationType) Type(java.lang.reflect.Type) WorkUnitState(org.apache.gobblin.configuration.WorkUnitState) State(org.apache.gobblin.configuration.State) JsonElement(com.google.gson.JsonElement) JsonSerializationContext(com.google.gson.JsonSerializationContext) File(java.io.File) Test(org.testng.annotations.Test)

Example 2 with JsonSerializationContext

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()));
}
Also used : JsonObject(com.google.gson.JsonObject) TypeToken(com.google.gson.reflect.TypeToken) NBTTagByte(net.minecraft.nbt.NBTTagByte) NBTTagByteArray(net.minecraft.nbt.NBTTagByteArray) Constants(net.minecraftforge.common.util.Constants) HashMap(java.util.HashMap) JsonSerializer(com.google.gson.JsonSerializer) ArrayUtils(org.apache.commons.lang3.ArrayUtils) NBTTagString(net.minecraft.nbt.NBTTagString) GsonBuilder(com.google.gson.GsonBuilder) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) NBTTagFloat(net.minecraft.nbt.NBTTagFloat) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) NBTTagList(net.minecraft.nbt.NBTTagList) ImmutableList(com.google.common.collect.ImmutableList) Gson(com.google.gson.Gson) Map(java.util.Map) JsonSerializationContext(com.google.gson.JsonSerializationContext) BigInteger(java.math.BigInteger) StreamSupport(java.util.stream.StreamSupport) JsonPrimitive(com.google.gson.JsonPrimitive) JsonWriter(com.google.gson.stream.JsonWriter) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) NBTTagInt(net.minecraft.nbt.NBTTagInt) NBTTagDouble(net.minecraft.nbt.NBTTagDouble) NBTTagShort(net.minecraft.nbt.NBTTagShort) Streams(com.google.gson.internal.Streams) ImmutableMap(com.google.common.collect.ImmutableMap) JsonSyntaxException(com.google.gson.JsonSyntaxException) NBTBase(net.minecraft.nbt.NBTBase) NBTTagIntArray(net.minecraft.nbt.NBTTagIntArray) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) Type(java.lang.reflect.Type) JsonNull(com.google.gson.JsonNull) Entry(java.util.Map.Entry) JsonDeserializer(com.google.gson.JsonDeserializer) NBTTagLong(net.minecraft.nbt.NBTTagLong) TypeAdapterFactory(com.google.gson.TypeAdapterFactory) JsonPrimitive(com.google.gson.JsonPrimitive) NBTTagByte(net.minecraft.nbt.NBTTagByte) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonSerializer(com.google.gson.JsonSerializer) NBTTagString(net.minecraft.nbt.NBTTagString) JsonDeserializer(com.google.gson.JsonDeserializer) NBTTagIntArray(net.minecraft.nbt.NBTTagIntArray) NBTTagList(net.minecraft.nbt.NBTTagList) Entry(java.util.Map.Entry) NBTBase(net.minecraft.nbt.NBTBase) JsonReader(com.google.gson.stream.JsonReader) NBTTagString(net.minecraft.nbt.NBTTagString) NBTTagShort(net.minecraft.nbt.NBTTagShort) TypeAdapterFactory(com.google.gson.TypeAdapterFactory) NBTTagFloat(net.minecraft.nbt.NBTTagFloat) NBTTagInt(net.minecraft.nbt.NBTTagInt) JsonWriter(com.google.gson.stream.JsonWriter) BigInteger(java.math.BigInteger) JsonArray(com.google.gson.JsonArray) Type(java.lang.reflect.Type) NBTTagShort(net.minecraft.nbt.NBTTagShort) JsonElement(com.google.gson.JsonElement) JsonSerializationContext(com.google.gson.JsonSerializationContext) NBTTagByte(net.minecraft.nbt.NBTTagByte) TypeAdapter(com.google.gson.TypeAdapter) NBTTagLong(net.minecraft.nbt.NBTTagLong) BigInteger(java.math.BigInteger) JsonObject(com.google.gson.JsonObject) NBTTagByteArray(net.minecraft.nbt.NBTTagByteArray) NBTTagLong(net.minecraft.nbt.NBTTagLong) NBTTagDouble(net.minecraft.nbt.NBTTagDouble)

Example 3 with JsonSerializationContext

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));
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonSerializationContext(com.google.gson.JsonSerializationContext) DateTime(org.joda.time.DateTime) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 4 with JsonSerializationContext

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));
}
Also used : Path(java.nio.file.Path) JsonPrimitive(com.google.gson.JsonPrimitive) JsonSerializationContext(com.google.gson.JsonSerializationContext) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 5 with JsonSerializationContext

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);
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) Entity(org.molgenis.data.Entity) EntityType(org.molgenis.data.meta.model.EntityType) Type(java.lang.reflect.Type) Attribute(org.molgenis.data.meta.model.Attribute) JsonPrimitive(com.google.gson.JsonPrimitive) JsonSerializationContext(com.google.gson.JsonSerializationContext) Test(org.testng.annotations.Test)

Aggregations

JsonSerializationContext (com.google.gson.JsonSerializationContext)9 JsonPrimitive (com.google.gson.JsonPrimitive)7 Type (java.lang.reflect.Type)7 JsonElement (com.google.gson.JsonElement)6 GsonBuilder (com.google.gson.GsonBuilder)5 Gson (com.google.gson.Gson)4 JsonSerializer (com.google.gson.JsonSerializer)4 JsonArray (com.google.gson.JsonArray)3 JsonObject (com.google.gson.JsonObject)3 JsonDeserializationContext (com.google.gson.JsonDeserializationContext)2 JsonDeserializer (com.google.gson.JsonDeserializer)2 ArrayList (java.util.ArrayList)2 Calendar (java.util.Calendar)2 HashMap (java.util.HashMap)2 BeforeMethod (org.testng.annotations.BeforeMethod)2 LobWrapper (angularBeans.io.LobWrapper)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 JsonNull (com.google.gson.JsonNull)1 JsonParseException (com.google.gson.JsonParseException)1