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