a0e835ffba3991d1b5fa6f57f071c0444adede33
[policy/models.git] / models-interactions / model-impl / so / src / main / java / org / onap / policy / so / util / SoLocalDateTimeTypeAdapter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.so.util;
22
23 import com.google.gson.JsonParseException;
24 import com.google.gson.TypeAdapter;
25 import com.google.gson.stream.JsonReader;
26 import com.google.gson.stream.JsonToken;
27 import com.google.gson.stream.JsonWriter;
28 import java.io.IOException;
29 import java.time.LocalDateTime;
30 import java.time.format.DateTimeFormatter;
31 import java.time.format.DateTimeParseException;
32
33 /*
34  * TODO: combine the functionality of this adapter with existing LocalDateTimeTypeAdapter and eliminate this class.
35  */
36
37 /**
38  * GSON Type Adapter for "LocalDateTime" fields, that uses the standard RFC_1123_DATE_TIME
39  * formatter.
40  */
41 public class SoLocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> {
42     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.RFC_1123_DATE_TIME;
43
44     @Override
45     public LocalDateTime read(JsonReader in) throws IOException {
46         try {
47             if (in.peek() == JsonToken.NULL) {
48                 in.nextNull();
49                 return null;
50             } else {
51                 return LocalDateTime.parse(in.nextString(), FORMATTER);
52             }
53
54         } catch (DateTimeParseException e) {
55             throw new JsonParseException("invalid date", e);
56         }
57     }
58
59     @Override
60     public void write(JsonWriter out, LocalDateTime value) throws IOException {
61         if (value == null) {
62             out.nullValue();
63         } else {
64             String text = value.format(FORMATTER);
65             out.value(text);
66         }
67     }
68 }