| Dariusz Luksza | db006d8 | 2016-03-14 22:55:50 +0100 | [diff] [blame] | 1 | // Copyright (C) 2016 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 | package com.google.gerrit.server.events; |
| 15 | |
| 16 | import static com.google.common.base.Preconditions.checkArgument; |
| 17 | |
| 18 | import com.google.common.base.Supplier; |
| 19 | import com.google.common.base.Suppliers; |
| 20 | import com.google.gson.JsonDeserializationContext; |
| 21 | import com.google.gson.JsonDeserializer; |
| 22 | import com.google.gson.JsonElement; |
| 23 | import com.google.gson.JsonParseException; |
| Dariusz Luksza | db006d8 | 2016-03-14 22:55:50 +0100 | [diff] [blame] | 24 | import java.lang.reflect.ParameterizedType; |
| 25 | import java.lang.reflect.Type; |
| 26 | |
| 27 | public class SupplierDeserializer implements JsonDeserializer<Supplier<?>> { |
| 28 | |
| 29 | @Override |
| Dave Borowitz | 292fa15 | 2016-11-13 09:56:32 -0800 | [diff] [blame] | 30 | public Supplier<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) |
| 31 | throws JsonParseException { |
| Dariusz Luksza | db006d8 | 2016-03-14 22:55:50 +0100 | [diff] [blame] | 32 | checkArgument(typeOfT instanceof ParameterizedType); |
| 33 | ParameterizedType parameterizedType = (ParameterizedType) typeOfT; |
| 34 | if (parameterizedType.getActualTypeArguments().length != 1) { |
| Dave Borowitz | 292fa15 | 2016-11-13 09:56:32 -0800 | [diff] [blame] | 35 | throw new JsonParseException("Expected one parameter type in Supplier interface."); |
| Dariusz Luksza | db006d8 | 2016-03-14 22:55:50 +0100 | [diff] [blame] | 36 | } |
| 37 | Type supplierOf = parameterizedType.getActualTypeArguments()[0]; |
| 38 | return Suppliers.ofInstance(context.deserialize(json, supplierOf)); |
| 39 | } |
| 40 | } |