blob: c62762fa3a11d8f872c63cba6956dba1d7415c88 [file] [log] [blame]
Jonathan Hart3c259162015-10-21 21:31:19 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Jonathan Hart3c259162015-10-21 21:31:19 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jonathan Hart26a8d952015-12-02 15:16:35 -080017package org.onosproject.net.flow;
18
19import org.onosproject.net.flow.instructions.ExtensionPropertyException;
Jonathan Hart3c259162015-10-21 21:31:19 -070020
21import java.lang.reflect.Field;
22import java.util.ArrayList;
23import java.util.List;
24
25/**
Jonathan Hart26a8d952015-12-02 15:16:35 -080026 * Abstract implementation of the set/get property methods of Extension.
Jonathan Hart3c259162015-10-21 21:31:19 -070027 */
Jonathan Hart26a8d952015-12-02 15:16:35 -080028public abstract class AbstractExtension implements Extension {
Jonathan Hart3c259162015-10-21 21:31:19 -070029
30 private static final String INVALID_KEY = "Invalid property key: ";
31 private static final String INVALID_TYPE = "Given type does not match field type: ";
32
33 @Override
Jonathan Hart26a8d952015-12-02 15:16:35 -080034 public <T> void setPropertyValue(String key, T value) throws
35 ExtensionPropertyException {
Jonathan Hart3c259162015-10-21 21:31:19 -070036 Class<?> clazz = this.getClass();
37 try {
38 Field field = clazz.getDeclaredField(key);
39 field.setAccessible(true);
40 field.set(this, value);
41 } catch (NoSuchFieldException | IllegalAccessException e) {
42 throw new ExtensionPropertyException(INVALID_KEY + key);
43 }
44 }
45
46 @Override
47 public <T> T getPropertyValue(String key) throws ExtensionPropertyException {
48 Class<?> clazz = this.getClass();
49 try {
50 Field field = clazz.getDeclaredField(key);
51 field.setAccessible(true);
52 @SuppressWarnings("unchecked")
53 T result = (T) field.get(this);
54 return result;
55 } catch (NoSuchFieldException | IllegalAccessException e) {
56 throw new ExtensionPropertyException(INVALID_KEY + key);
57 } catch (ClassCastException e) {
58 throw new ExtensionPropertyException(INVALID_TYPE + key);
59 }
60 }
61
62 @Override
63 public List<String> getProperties() {
64 Class<?> clazz = this.getClass();
65
66 List<String> fields = new ArrayList<>();
67
68 for (Field field : clazz.getDeclaredFields()) {
69 fields.add(field.getName());
70 }
71
72 return fields;
73 }
74}