2edd7bd2ee54f299aea93e21f15847f601741ce5
[genius.git] / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / genius / mdsalutil / matches / MatchInfoHelper.java
1 /*
2  * Copyright © 2017 Red Hat, Inc. and others.
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 package org.opendaylight.genius.mdsalutil.matches;
9
10 import java.util.Map;
11 import org.opendaylight.genius.mdsalutil.MatchInfo;
12 import org.opendaylight.genius.utils.SuperTypeUtil;
13 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
14 import org.opendaylight.yangtools.concepts.Builder;
15 import org.opendaylight.yangtools.yang.binding.DataObject;
16
17 /**
18  * Helper for matches (this is designed to be absorbed into MatchInfo once we've cleaned up downstream users).
19  */
20 public abstract class MatchInfoHelper<T extends DataObject, B extends Builder<T>> extends MatchInfo {
21     private final Class<B> builderClass;
22
23     MatchInfoHelper() {
24         builderClass = SuperTypeUtil.getTypeParameter(getClass(), 1);
25     }
26
27     @Override
28     public void createInnerMatchBuilder(Map<Class<?>, Object> mapMatchBuilder) {
29         populateBuilder((B) mapMatchBuilder.computeIfAbsent(builderClass, key -> {
30             try {
31                 return builderClass.newInstance();
32             } catch (InstantiationException | IllegalAccessException e) {
33                 throw new IllegalStateException("Unable to create an instance of " + builderClass, e);
34             }
35         }));
36     }
37
38     @Override
39     public void setMatch(MatchBuilder matchBuilder, Map<Class<?>, Object> mapMatchBuilder) {
40         B builder = (B) mapMatchBuilder.remove(builderClass);
41
42         if (builder != null) {
43             applyValue(matchBuilder, builder.build());
44         }
45     }
46
47     protected abstract void applyValue(MatchBuilder matchBuilder, T value);
48
49     protected abstract void populateBuilder(B builder);
50
51     @Override
52     public boolean equals(Object other) {
53         if (this == other) {
54             return true;
55         }
56         if (other == null || getClass() != other.getClass()) {
57             return false;
58         }
59
60         MatchInfoHelper<?, ?> that = (MatchInfoHelper<?, ?>) other;
61
62         return builderClass != null ? builderClass.equals(that.builderClass) : that.builderClass == null;
63     }
64
65     @Override
66     public int hashCode() {
67         return builderClass != null ? builderClass.hashCode() : 0;
68     }
69 }