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
8 package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common;
10 import com.google.common.collect.ImmutableMap;
11 import java.util.HashMap;
13 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
14 import org.opendaylight.yangtools.yang.common.Uint8;
17 * Base class for a conversion reactor.
19 * @param <F> source type for conversion
21 public abstract class ConvertReactor<F> {
22 private final Map<ConvertorKey, ResultInjector<?, ?>> injectionMapping;
23 private final Map<Uint8, ConvertReactorConvertor<F, ?>> conversionMapping;
25 protected ConvertReactor() {
26 final Map<Uint8, ConvertReactorConvertor<F, ?>> conversions = new HashMap<>();
27 final Map<ConvertorKey, ResultInjector<?, ?>> injections = new HashMap<>();
28 initMappings(conversions, injections);
30 // Create optimized view of mappings
31 this.conversionMapping = ImmutableMap.copyOf(conversions);
32 this.injectionMapping = ImmutableMap.copyOf(injections);
36 * Fill conversion and injection mappings.
38 * @param conversions convert from
39 * @param injections injection
41 protected abstract void initMappings(Map<Uint8, ConvertReactorConvertor<F, ?>> conversions,
42 Map<ConvertorKey, ResultInjector<?, ?>> injections);
45 * Converts a source to a target.
49 * @param source convert from
50 * @param version openflow version
51 * @param target convert to
52 * @param convertorExecutor the convertor executor
54 @SuppressWarnings("unchecked")
55 public <R, T> void convert(final F source, final Uint8 version, final T target,
56 final ConvertorExecutor convertorExecutor) {
59 ConvertReactorConvertor<F, R> convertor = (ConvertReactorConvertor<F, R>) conversionMapping.get(version);
60 if (convertor == null) {
61 throw new IllegalArgumentException("convertor for given version [" + version + "] not found");
63 R convertedItem = convertor.convert(source, convertorExecutor);
66 ConvertorKey key = buildInjectionKey(version, convertedItem, target);
67 ResultInjector<R, T> injection = (ResultInjector<R, T>) injectionMapping.get(key);
68 if (injection == null) {
69 throw new IllegalArgumentException("injector for given version and target [" + key + "] not found");
71 injection.inject(convertedItem, target);
75 * Builds an injection key.
77 * @param version openflow version
78 * @param convertedItem to be injected
79 * @param target object
80 * @return injection key
82 protected ConvertorKey buildInjectionKey(final Uint8 version, final Object convertedItem, final Object target) {
83 return new ConvertorKey(version, target.getClass());