Resolve Bug:445 Remove freemarker from config code generator.
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / AbstractForwardedTransaction.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.md.sal.binding.impl;
9
10 import java.util.ArrayList;
11 import java.util.EnumMap;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Map.Entry;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.TimeUnit;
17
18 import javax.annotation.Nullable;
19
20 import org.eclipse.xtext.xbase.lib.Exceptions;
21 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
28 import org.opendaylight.yangtools.concepts.Delegator;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
31 import org.opendaylight.yangtools.yang.common.RpcResult;
32 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.common.base.Function;
39 import com.google.common.base.Optional;
40 import com.google.common.cache.Cache;
41 import com.google.common.cache.CacheBuilder;
42 import com.google.common.util.concurrent.Futures;
43 import com.google.common.util.concurrent.ListenableFuture;
44
45 public class AbstractForwardedTransaction<T extends AsyncTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>>
46         implements Delegator<T> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(AbstractForwardedTransaction.class);
49     private final T delegate;
50     private final static CacheBuilder<Object, Object> CACHE_BUILDER = CacheBuilder.newBuilder()
51             .expireAfterWrite(10, TimeUnit.MILLISECONDS).maximumSize(100);
52     private final BindingToNormalizedNodeCodec codec;
53     private final EnumMap<LogicalDatastoreType, Cache<InstanceIdentifier<?>, DataObject>> cacheMap;
54
55     protected AbstractForwardedTransaction(final T delegate, final BindingToNormalizedNodeCodec codec) {
56         super();
57         this.delegate = delegate;
58         this.codec = codec;
59
60         this.cacheMap = new EnumMap<>(LogicalDatastoreType.class);
61         cacheMap.put(LogicalDatastoreType.OPERATIONAL, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
62         cacheMap.put(LogicalDatastoreType.CONFIGURATION, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
63
64     }
65
66     @Override
67     public T getDelegate() {
68         return delegate;
69     }
70
71     protected final BindingToNormalizedNodeCodec getCodec() {
72         return codec;
73     }
74
75     protected ListenableFuture<Optional<DataObject>> transformFuture(final LogicalDatastoreType store,
76             final InstanceIdentifier<?> path, final ListenableFuture<Optional<NormalizedNode<?, ?>>> future) {
77         return Futures.transform(future, new Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>>() {
78             @Nullable
79             @Override
80             public Optional<DataObject> apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
81                 try {
82                     final DataObject dataObject = normalizedNode.isPresent() ? codec.toBinding(path,
83                             normalizedNode.get()) : null;
84                     if(dataObject != null) {
85                         updateCache(store, path, dataObject);
86                     }
87                     return Optional.fromNullable(dataObject);
88                 } catch (DeserializationException e) {
89                     Exceptions.sneakyThrow(e);
90                 }
91                 return null;
92             }
93         });
94     }
95
96     protected void doPut(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
97             final InstanceIdentifier<?> path, final DataObject data) {
98         invalidateCache(store, path);
99         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
100                 .toNormalizedNode(path, data);
101         writeTransaction.put(store, normalized.getKey(), normalized.getValue());
102     }
103
104     protected void doPutWithEnsureParents(final DOMDataReadWriteTransaction writeTransaction,
105             final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
106         invalidateCache(store, path);
107         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
108                 .toNormalizedNode(path, data);
109
110         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
111         try {
112             List<PathArgument> currentArguments = new ArrayList<>();
113             DataNormalizationOperation<?> currentOp = codec.getDataNormalizer().getRootOperation();
114             Iterator<PathArgument> iterator = normalizedPath.getPath().iterator();
115             while (iterator.hasNext()) {
116                 PathArgument currentArg = iterator.next();
117                 currentOp = currentOp.getChild(currentArg);
118                 currentArguments.add(currentArg);
119                 org.opendaylight.yangtools.yang.data.api.InstanceIdentifier currentPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(
120                         currentArguments);
121                 boolean isPresent = writeTransaction.read(store, currentPath).get().isPresent();
122                 if (isPresent == false && iterator.hasNext()) {
123                     writeTransaction.put(store, currentPath, currentOp.createDefault(currentArg));
124                 }
125             }
126         } catch (InterruptedException | ExecutionException e) {
127             e.printStackTrace();
128         }
129         //LOG .info("Tx: {} : Putting data {}",getDelegate().getIdentifier(),normalized.getKey());
130         writeTransaction.put(store, normalized.getKey(), normalized.getValue());
131
132     }
133
134     protected void doMerge(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
135             final InstanceIdentifier<?> path, final DataObject data) {
136         invalidateCache(store, path);
137         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
138                 .toNormalizedNode(path, data);
139         writeTransaction.merge(store, normalized.getKey(), normalized.getValue());
140     }
141
142     protected void doDelete(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
143             final InstanceIdentifier<?> path) {
144         invalidateCache(store, path);
145         final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = codec.toNormalized(path);
146         writeTransaction.delete(store, normalized);
147     }
148
149     protected ListenableFuture<RpcResult<TransactionStatus>> doCommit(final DOMDataWriteTransaction writeTransaction) {
150         return writeTransaction.commit();
151     }
152
153     protected void doCancel(final DOMDataWriteTransaction writeTransaction) {
154         writeTransaction.cancel();
155     }
156
157     protected ListenableFuture<Optional<DataObject>> doRead(final DOMDataReadTransaction readTransaction,
158             final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
159         final DataObject dataObject = getFromCache(store, path);
160         if (dataObject == null) {
161             final ListenableFuture<Optional<NormalizedNode<?, ?>>> future = readTransaction.read(store,
162                     codec.toNormalized(path));
163             return transformFuture(store, path, future);
164         } else {
165             return Futures.immediateFuture(Optional.of(dataObject));
166         }
167     }
168
169     private DataObject getFromCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
170         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
171         if (cache != null) {
172             return cache.getIfPresent(path);
173         }
174         return null;
175     }
176
177     private void updateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
178             final DataObject dataObject) {
179         // Check if cache exists. If not create one.
180         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
181         if (cache == null) {
182             cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(1, TimeUnit.MINUTES).build();
183
184         }
185
186         cache.put(path, dataObject);
187     }
188
189     private void invalidateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
190         // FIXME: Optimization: invalidate only parents and children of path
191         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
192         cache.invalidateAll();
193         LOG.trace("Cache invalidated");
194     }
195
196 }