Line data Source code
1 : // Copyright (C) 2014 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.events; 16 : 17 : import com.google.gson.JsonDeserializationContext; 18 : import com.google.gson.JsonDeserializer; 19 : import com.google.gson.JsonElement; 20 : import com.google.gson.JsonParseException; 21 : import java.lang.reflect.Type; 22 : 23 : /** 24 : * JSON deserializer for {@link Event}s. 25 : * 26 : * <p>Deserialized objects are of an appropriate subclass based on the value of the top-level "type" 27 : * element. 28 : */ 29 2 : public class EventDeserializer implements JsonDeserializer<Event> { 30 : @Override 31 : public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 32 : throws JsonParseException { 33 0 : if (!json.isJsonObject()) { 34 0 : throw new JsonParseException("Not an object"); 35 : } 36 0 : JsonElement typeJson = json.getAsJsonObject().get("type"); 37 0 : if (typeJson == null 38 0 : || !typeJson.isJsonPrimitive() 39 0 : || !typeJson.getAsJsonPrimitive().isString()) { 40 0 : throw new JsonParseException("Type is not a string: " + typeJson); 41 : } 42 0 : String type = typeJson.getAsJsonPrimitive().getAsString(); 43 0 : Class<?> cls = EventTypes.getClass(type); 44 0 : if (cls == null) { 45 0 : throw new JsonParseException("Unknown event type: " + type); 46 : } 47 0 : return context.deserialize(json, cls); 48 : } 49 : }