136b5db37165b6674dc13d7531c2c942e6a04a18
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / sal / convertor / common / ConvertReactor.java
1 /**
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common;
10
11 import java.util.HashMap;
12 import java.util.Map;
13
14 /**
15  * @param <FROM> source type for conversion
16  * 
17  */
18 public abstract class ConvertReactor<FROM> {
19     
20     private Map<Short, Convertor<FROM, ?>> conversionMapping;
21     private Map<InjectionKey, ResultInjector<?, ?>> injectionMapping;
22     
23     protected ConvertReactor() {
24         conversionMapping = new HashMap<>();
25         injectionMapping = new HashMap<>();
26         initMappings(conversionMapping, injectionMapping);
27     }
28     
29     /**
30      * fill conversion and injection mappings
31      * @param conversions 
32      * @param injections 
33      */
34     protected abstract void initMappings(Map<Short, Convertor<FROM, ?>> conversions, 
35             Map<InjectionKey, ResultInjector<?, ?>> injections);
36     
37     /**
38      * @param source
39      * @param version
40      * @param target 
41      */
42     @SuppressWarnings("unchecked")
43     public <RESULT, TARGET> void convert(FROM source, short version, TARGET target) {
44         
45         //lookup converter
46         Convertor<FROM, RESULT> convertor = (Convertor<FROM, RESULT>) conversionMapping.get(version);
47         if (convertor == null) {
48             throw new IllegalArgumentException("convertor for given version ["+version+"] not found");
49         }
50         RESULT convertedItem = convertor.convert(source);
51         
52         //lookup injection
53         InjectionKey key = new InjectionKey(version, target.getClass().getName());
54         ResultInjector<RESULT, TARGET> injection = (ResultInjector<RESULT, TARGET>) injectionMapping.get(key);
55         if (injection == null) {
56             throw new IllegalArgumentException("injector for given version and target ["+key+"] not found");
57         }
58         injection.inject(convertedItem, target);
59     }
60
61 }