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