]> git.basschouten.com Git - openhab-addons.git/blob
bc99d6b6e74bea989d68553b50cddffb020d1ec6
[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.io.hueemulation.internal;
14
15 import java.net.InetAddress;
16 import java.net.NetworkInterface;
17 import java.net.SocketException;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.Set;
22
23 import javax.ws.rs.core.Response;
24 import javax.ws.rs.core.Response.ResponseBuilder;
25 import javax.ws.rs.core.UriInfo;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.io.hueemulation.internal.dto.response.HueResponse;
30 import org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage;
31 import org.openhab.io.hueemulation.internal.dto.response.HueResponseSuccessSimple;
32 import org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric;
33
34 import com.google.gson.Gson;
35 import com.google.gson.reflect.TypeToken;
36
37 /**
38  * Network utility methods
39  *
40  * @author David Graeff - Initial contribution
41  */
42 @NonNullByDefault
43 public class NetworkUtils {
44     /**
45      * Try to get the ethernet interface MAC for the network interface that belongs to the given IP address.
46      * Returns a default MAC on any failure.
47      *
48      * @param address IP address
49      * @return A MAC of the form "00:00:88:00:bb:ee"
50      */
51     static String getMAC(InetAddress address) {
52         NetworkInterface networkInterface;
53         final byte[] mac;
54         try {
55             networkInterface = NetworkInterface.getByInetAddress(address);
56             if (networkInterface == null) {
57                 return "00:00:88:00:bb:ee";
58             }
59             mac = networkInterface.getHardwareAddress();
60             if (mac == null) {
61                 return "00:00:88:00:bb:ee";
62             }
63         } catch (SocketException e) {
64             return "00:00:88:00:bb:ee";
65         }
66
67         StringBuilder sb = new StringBuilder();
68         for (int i = 0; i < mac.length; i++) {
69             sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
70         }
71         return sb.toString();
72     }
73
74     /**
75      * Adds cors headers to the given response and returns it.
76      */
77     public static ResponseBuilder responseWithCors(ResponseBuilder response) {
78         return response.encoding(StandardCharsets.UTF_8.name()) //
79                 .header("Access-Control-Allow-Origin", "*")
80                 .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
81                 .header("Access-Control-Allow-Credentials", "true")
82                 .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
83                 .header("Access-Control-Max-Age", "1209600");
84     }
85
86     /**
87      * Creates a json response with the correct Hue error code
88      *
89      * @param gson A gson instance
90      * @param uri The original uri of the request
91      * @param type Any of HueResponse.*
92      * @param message A message
93      * @return
94      */
95     public static Response singleError(Gson gson, UriInfo uri, int type, @Nullable String message) {
96         HueResponse e = new HueResponse(
97                 new HueErrorMessage(type, uri.getPath().replace("/api", ""), message != null ? message : ""));
98         String str = gson.toJson(Set.of(e), new TypeToken<List<?>>() {
99         }.getType());
100         int httpCode = 500;
101         switch (type) {
102             case HueResponse.UNAUTHORIZED:
103                 httpCode = 403;
104                 break;
105             case HueResponse.METHOD_NOT_ALLOWED:
106                 httpCode = 405;
107                 break;
108             case HueResponse.NOT_AVAILABLE:
109                 httpCode = 404;
110                 break;
111             case HueResponse.ARGUMENTS_INVALID:
112             case HueResponse.LINK_BUTTON_NOT_PRESSED:
113                 httpCode = 200;
114                 break;
115         }
116         return Response.status(httpCode).entity(str).build();
117     }
118
119     public static Response singleSuccess(Gson gson, String message, String uriPart) {
120         List<HueResponse> responses = new ArrayList<>();
121         responses.add(new HueResponse(new HueSuccessGeneric(message, uriPart)));
122         return Response.ok(gson.toJson(responses, new TypeToken<List<?>>() {
123         }.getType())).build();
124     }
125
126     public static Response singleSuccess(Gson gson, String message) {
127         List<HueResponseSuccessSimple> responses = new ArrayList<>();
128         responses.add(new HueResponseSuccessSimple(message));
129         return Response.ok(gson.toJson(responses, new TypeToken<List<?>>() {
130         }.getType())).build();
131     }
132
133     public static Response successList(Gson gson, List<HueSuccessGeneric> successList) {
134         List<HueResponse> responses = new ArrayList<>();
135         for (HueSuccessGeneric s : successList) {
136             if (s.isValid()) {
137                 responses.add(new HueResponse(s));
138             }
139         }
140         return Response.ok(gson.toJson(responses, new TypeToken<List<?>>() {
141         }.getType())).build();
142     }
143 }