Fix Bug 271
[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.math.BigInteger;
12 import java.util.HashMap;
13 import java.util.Map;
14
15 /**
16  * @param <FROM> source type for conversion
17  * 
18  */
19 public abstract class ConvertReactor<FROM> {
20     
21     private Map<Short, Convertor<FROM, ?>> conversionMapping;
22     private Map<InjectionKey, ResultInjector<?, ?>> injectionMapping;
23     
24     protected ConvertReactor() {
25         conversionMapping = new HashMap<>();
26         injectionMapping = new HashMap<>();
27         initMappings(conversionMapping, injectionMapping);
28     }
29     
30     /**
31      * fill conversion and injection mappings
32      * @param conversions 
33      * @param injections 
34      */
35     protected abstract void initMappings(Map<Short, Convertor<FROM, ?>> conversions, 
36             Map<InjectionKey, ResultInjector<?, ?>> injections);
37     
38     /**
39      * @param source
40      * @param version
41      * @param target 
42      */
43     @SuppressWarnings("unchecked")
44     public <RESULT, TARGET> void convert(FROM source, short version, TARGET target,BigInteger datapathid) {
45         
46         //lookup converter
47         Convertor<FROM, RESULT> convertor = (Convertor<FROM, RESULT>) conversionMapping.get(version);
48         if (convertor == null) {
49             throw new IllegalArgumentException("convertor for given version ["+version+"] not found");
50         }
51         RESULT convertedItem = convertor.convert(source,datapathid);
52         
53         //lookup injection
54         InjectionKey key = new InjectionKey(version, target.getClass().getName());
55         ResultInjector<RESULT, TARGET> injection = (ResultInjector<RESULT, TARGET>) injectionMapping.get(key);
56         if (injection == null) {
57             throw new IllegalArgumentException("injector for given version and target ["+key+"] not found");
58         }
59         injection.inject(convertedItem, target);
60     }
61
62 }