2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common;
11 import com.google.common.collect.ImmutableMap;
12 import java.util.HashMap;
16 * @param <FROM> source type for conversion
19 public abstract class ConvertReactor<FROM> {
20 private final Map<InjectionKey, ResultInjector<?, ?>> injectionMapping;
21 private final Map<Short, Convertor<FROM, ?, ?>> conversionMapping;
23 protected ConvertReactor() {
24 final Map<Short, Convertor<FROM, ?, ?>> conversions = new HashMap<>();
25 final Map<InjectionKey, ResultInjector<?, ?>> injections = new HashMap<>();
26 initMappings(conversions, injections);
28 // Create optimized view of mappings
29 this.conversionMapping = ImmutableMap.copyOf(conversions);
30 this.injectionMapping = ImmutableMap.copyOf(injections);
34 * fill conversion and injection mappings
35 * @param conversions convert from
36 * @param injections injection
38 protected abstract void initMappings(Map<Short, Convertor<FROM, ?, ?>> conversions,
39 Map<InjectionKey, ResultInjector<?, ?>> injections);
42 * @param source convert from
43 * @param version openflow version
44 * @param target convert to
45 * @param <RESULT> result
46 * @param <TARGET> target
48 @SuppressWarnings("unchecked")
49 public <RESULT, TARGET> void convert(final FROM source, final short version, final TARGET target) {
52 Convertor<FROM, RESULT, ?> convertor = (Convertor<FROM, RESULT, ?>) conversionMapping.get(version);
53 if (convertor == null) {
54 throw new IllegalArgumentException("convertor for given version ["+version+"] not found");
56 RESULT convertedItem = convertor.convert(source, null);
59 InjectionKey key = buildInjectionKey(version, convertedItem, target);
60 ResultInjector<RESULT, TARGET> injection = (ResultInjector<RESULT, TARGET>) injectionMapping.get(key);
61 if (injection == null) {
62 throw new IllegalArgumentException("injector for given version and target ["+key+"] not found");
64 injection.inject(convertedItem, target);
68 * @param version openflow version
69 * @param convertedItem to be injected
70 * @param target object
71 * @return injection key
73 protected InjectionKey buildInjectionKey(final short version, final Object convertedItem, final Object target) {
74 return new InjectionKey(version, target.getClass());