]> git.basschouten.com Git - openhab-addons.git/blob
e6f944d64eea1285769b5550b60cc92b216e475f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ecobee.internal.dto.thermostat;
14
15 import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.ECOBEE_DATETIME_FORMAT;
16
17 import java.lang.reflect.Type;
18 import java.time.Instant;
19 import java.time.LocalDateTime;
20 import java.time.ZoneOffset;
21 import java.time.format.DateTimeFormatter;
22 import java.time.format.DateTimeParseException;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26
27 import com.google.gson.JsonDeserializationContext;
28 import com.google.gson.JsonDeserializer;
29 import com.google.gson.JsonElement;
30 import com.google.gson.JsonParseException;
31
32 /**
33  * The {@link InstantDeserializer} is responsible for handling the UTC dates returned from
34  * the Ecobee API service.
35  *
36  * @author Mark Hilbush - Initial contribution
37  */
38 @NonNullByDefault
39 public class InstantDeserializer implements JsonDeserializer<Instant> {
40
41     @Override
42     public @Nullable Instant deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2)
43             throws JsonParseException {
44         try {
45             DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ECOBEE_DATETIME_FORMAT);
46             LocalDateTime localDateTime = formatter.parse(element.getAsString(), LocalDateTime::from);
47             return localDateTime.toInstant(ZoneOffset.UTC);
48         } catch (DateTimeParseException e) {
49             return null;
50         }
51     }
52 }