]> git.basschouten.com Git - openhab-addons.git/blob
ad2d894259ca99a2cf848bb4398b25950807b7b4
[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.gpstracker.internal.message;
14
15 import java.util.HashMap;
16 import java.util.Map;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.gpstracker.internal.message.dto.LocationMessage;
21 import org.openhab.binding.gpstracker.internal.message.dto.TransitionMessage;
22
23 import com.google.gson.Gson;
24
25 /**
26  * Message handling utility
27  *
28  * @author Gabor Bicskei - Initial contribution
29  */
30 @NonNullByDefault
31 public class MessageUtil {
32     /**
33      * Patterns to identify incoming JSON payload.
34      */
35     private static final String[] PATTERNS = new String[] { ".*\"_type\"\\s*:\\s*\"transition\".*", // transition
36             ".*\"_type\"\\s*:\\s*\"location\".*", // location
37     };
38
39     /**
40      * Supported message types
41      */
42     private static final Map<String, Class<? extends LocationMessage>> MESSAGE_TYPES = new HashMap<>();
43
44     static {
45         MESSAGE_TYPES.put(PATTERNS[0], TransitionMessage.class);
46         MESSAGE_TYPES.put(PATTERNS[1], LocationMessage.class);
47     }
48
49     private final Gson gson = new Gson();
50
51     /**
52      * Parses JSON message into an object with type determined by message pattern.
53      *
54      * @param json JSON string.
55      * @return Parsed message POJO or null without pattern match
56      */
57     public @Nullable LocationMessage fromJson(String json) {
58         for (String pattern : PATTERNS) {
59             Class<? extends LocationMessage> c = MESSAGE_TYPES.get(pattern);
60             if (c != null && json.matches(pattern)) {
61                 return gson.fromJson(json, c);
62             }
63         }
64         return null;
65     }
66
67     /**
68      * Converts object to JSON sting.
69      *
70      * @param o Object to convert
71      * @return JSON string
72      */
73     public String toJson(Object o) {
74         return gson.toJson(o);
75     }
76 }