Jonathan Hart | 3c25916 | 2015-10-21 21:31:19 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2015 Open Networking Laboratory |
| 3 | * |
| 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 | |
| 17 | package org.onosproject.net.flow.instructions; |
| 18 | |
| 19 | import java.lang.reflect.Field; |
| 20 | import java.util.ArrayList; |
| 21 | import java.util.List; |
| 22 | |
| 23 | /** |
| 24 | * Abstract implementation of the set/get property methods of ExtensionInstruction. |
| 25 | */ |
| 26 | public abstract class AbstractExtensionInstruction implements ExtensionInstruction { |
| 27 | |
| 28 | private static final String INVALID_KEY = "Invalid property key: "; |
| 29 | private static final String INVALID_TYPE = "Given type does not match field type: "; |
| 30 | |
| 31 | @Override |
| 32 | public <T> void setPropertyValue(String key, T value) throws ExtensionPropertyException { |
| 33 | Class<?> clazz = this.getClass(); |
| 34 | try { |
| 35 | Field field = clazz.getDeclaredField(key); |
| 36 | field.setAccessible(true); |
| 37 | field.set(this, value); |
| 38 | } catch (NoSuchFieldException | IllegalAccessException e) { |
| 39 | throw new ExtensionPropertyException(INVALID_KEY + key); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | @Override |
| 44 | public <T> T getPropertyValue(String key) throws ExtensionPropertyException { |
| 45 | Class<?> clazz = this.getClass(); |
| 46 | try { |
| 47 | Field field = clazz.getDeclaredField(key); |
| 48 | field.setAccessible(true); |
| 49 | @SuppressWarnings("unchecked") |
| 50 | T result = (T) field.get(this); |
| 51 | return result; |
| 52 | } catch (NoSuchFieldException | IllegalAccessException e) { |
| 53 | throw new ExtensionPropertyException(INVALID_KEY + key); |
| 54 | } catch (ClassCastException e) { |
| 55 | throw new ExtensionPropertyException(INVALID_TYPE + key); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public List<String> getProperties() { |
| 61 | Class<?> clazz = this.getClass(); |
| 62 | |
| 63 | List<String> fields = new ArrayList<>(); |
| 64 | |
| 65 | for (Field field : clazz.getDeclaredFields()) { |
| 66 | fields.add(field.getName()); |
| 67 | } |
| 68 | |
| 69 | return fields; |
| 70 | } |
| 71 | } |