]> git.basschouten.com Git - openhab-addons.git/blob
fae4e2de62a92a4d928fa3bda8e3dd029c11fdb3
[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.lifx.internal.dto;
14
15 import java.lang.reflect.Constructor;
16 import java.lang.reflect.Field;
17 import java.nio.ByteBuffer;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20
21 /**
22  * A generic handler that dynamically creates "standard" packet instances.
23  *
24  * <p>
25  * Packet types must have an empty constructor and cannot require any
26  * additional logic (other than parsing).
27  *
28  * @param <T> the packet subtype this handler constructs
29  *
30  * @author Tim Buckley - Initial contribution
31  * @author Karel Goderis - Enhancement for the V2 LIFX Firmware and LAN Protocol Specification
32  */
33 @NonNullByDefault
34 public class GenericHandler<T extends Packet> implements PacketHandler<T> {
35
36     private Constructor<T> constructor;
37
38     private boolean typeFound;
39     private int type;
40
41     public boolean isTypeFound() {
42         return typeFound;
43     }
44
45     public int getType() {
46         return type;
47     }
48
49     public GenericHandler(Class<T> clazz) {
50         try {
51             constructor = clazz.getConstructor();
52         } catch (NoSuchMethodException ex) {
53             throw new IllegalArgumentException("Packet class cannot be handled by GenericHandler", ex);
54         }
55
56         try {
57             Field typeField = clazz.getField("TYPE");
58             type = (int) typeField.get(null);
59             typeFound = true;
60         } catch (NoSuchFieldException | IllegalAccessException ex) {
61             // silently ignore
62             typeFound = false;
63         }
64     }
65
66     @Override
67     public T handle(ByteBuffer buf) {
68         try {
69             T ret = constructor.newInstance();
70             ret.parse(buf);
71             return ret;
72         } catch (ReflectiveOperationException ex) {
73             throw new IllegalArgumentException("Unable to instantiate empty packet", ex);
74         }
75     }
76 }