|
| 1 | +/* |
| 2 | + * Copyright (c) 2023. Smart Operating Block |
| 3 | + * |
| 4 | + * Use of this source code is governed by an MIT-style |
| 5 | + * license that can be found in the LICENSE file or at |
| 6 | + * https://opensource.org/licenses/MIT. |
| 7 | + */ |
| 8 | + |
| 9 | +package application.presenter.event.serialization; |
| 10 | + |
| 11 | +import application.presenter.event.model.Event; |
| 12 | +import application.presenter.event.model.medicaltechnology.MedicalTechnologyEvent; |
| 13 | +import application.presenter.event.model.medicaltechnology.payload.MedicalTechnologyUsagePayload; |
| 14 | +import application.presenter.event.model.roomevent.RoomEvent; |
| 15 | +import application.presenter.event.model.roomevent.payload.HumidityPayload; |
| 16 | +import application.presenter.event.model.roomevent.payload.LuminosityPayload; |
| 17 | +import application.presenter.event.model.roomevent.payload.PresencePayload; |
| 18 | +import application.presenter.event.model.roomevent.payload.TemperaturePayload; |
| 19 | +import com.google.gson.Gson; |
| 20 | +import com.google.gson.reflect.TypeToken; |
| 21 | + |
| 22 | +import java.lang.reflect.Type; |
| 23 | +import java.util.HashMap; |
| 24 | +import java.util.Map; |
| 25 | + |
| 26 | +/** |
| 27 | + * Implementation of the {@link EventDeserializer} interface that allows an event to be |
| 28 | + * deserialized from String. |
| 29 | + */ |
| 30 | +public class EventDeserializerImpl implements EventDeserializer { |
| 31 | + private final Map<String, Type> typeMap = new HashMap<>(); |
| 32 | + |
| 33 | + /** |
| 34 | + * Default constructor. |
| 35 | + */ |
| 36 | + public EventDeserializerImpl() { |
| 37 | + this.typeMap.put(TemperaturePayload.TEMPERATURE_EVENT_KEY, new TypeToken<RoomEvent<TemperaturePayload>>() { }.getType()); |
| 38 | + this.typeMap.put(HumidityPayload.HUMIDITY_EVENT_KEY, new TypeToken<RoomEvent<HumidityPayload>>() { }.getType()); |
| 39 | + this.typeMap.put(LuminosityPayload.LUMINOSITY_EVENT_KEY, new TypeToken<RoomEvent<LuminosityPayload>>() { }.getType()); |
| 40 | + this.typeMap.put(PresencePayload.PRESENCE_EVENT_KEY, new TypeToken<RoomEvent<PresencePayload>>() { }.getType()); |
| 41 | + this.typeMap.put( |
| 42 | + MedicalTechnologyUsagePayload.MEDICAL_TECHNOLOGY_USAGE_EVENT_KEY, |
| 43 | + new TypeToken<MedicalTechnologyEvent>() { }.getType() |
| 44 | + ); |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public final Event<?> fromString(final String eventKey, final String event) { |
| 49 | + if (!this.typeMap.containsKey(eventKey)) { |
| 50 | + throw new IllegalArgumentException("Event not supported"); |
| 51 | + } |
| 52 | + return new Gson().fromJson(event, this.typeMap.get(eventKey)); |
| 53 | + } |
| 54 | +} |
0 commit comments