Merge "Bug 714 - Fixed creating DOM Document's element with namespace"
[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.DataNormalizationException;
25 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.yangtools.concepts.Delegator;
30 import org.opendaylight.yangtools.yang.binding.DataObject;
31 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
32 import org.opendaylight.yangtools.yang.common.RpcResult;
33 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.common.base.Function;
40 import com.google.common.base.Optional;
41 import com.google.common.cache.Cache;
42 import com.google.common.cache.CacheBuilder;
43 import com.google.common.util.concurrent.Futures;
44 import com.google.common.util.concurrent.ListenableFuture;
45
46 public class AbstractForwardedTransaction<T extends AsyncTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>>
47         implements Delegator<T> {
48
49     private static final Logger LOG = LoggerFactory.getLogger(AbstractForwardedTransaction.class);
50     private final T delegate;
51     private final static CacheBuilder<Object, Object> CACHE_BUILDER = CacheBuilder.newBuilder()
52             .expireAfterWrite(10, TimeUnit.MILLISECONDS).maximumSize(100);
53     private final BindingToNormalizedNodeCodec codec;
54     private final EnumMap<LogicalDatastoreType, Cache<InstanceIdentifier<?>, DataObject>> cacheMap;
55
56     protected AbstractForwardedTransaction(final T delegate, final BindingToNormalizedNodeCodec codec) {
57         super();
58         this.delegate = delegate;
59         this.codec = codec;
60
61         this.cacheMap = new EnumMap<>(LogicalDatastoreType.class);
62         cacheMap.put(LogicalDatastoreType.OPERATIONAL, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
63         cacheMap.put(LogicalDatastoreType.CONFIGURATION, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
64
65     }
66
67     @Override
68     public T getDelegate() {
69         return delegate;
70     }
71
72     protected final BindingToNormalizedNodeCodec getCodec() {
73         return codec;
74     }
75
76     protected ListenableFuture<Optional<DataObject>> transformFuture(final LogicalDatastoreType store,
77             final InstanceIdentifier<?> path, final ListenableFuture<Optional<NormalizedNode<?, ?>>> future) {
78         return Futures.transform(future, new Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>>() {
79             @Nullable
80             @Override
81             public Optional<DataObject> apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
82                 try {
83                     final DataObject dataObject = normalizedNode.isPresent() ? codec.toBinding(path,
84                             normalizedNode.get()) : null;
85                     if(dataObject != null) {
86                         updateCache(store, path, dataObject);
87                     }
88                     return Optional.fromNullable(dataObject);
89                 } catch (DeserializationException e) {
90                     Exceptions.sneakyThrow(e);
91                 }
92                 return null;
93             }
94         });
95     }
96
97     protected void doPut(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
98             final InstanceIdentifier<?> path, final DataObject data) {
99         invalidateCache(store, path);
100         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
101                 .toNormalizedNode(path, data);
102         writeTransaction.put(store, normalized.getKey(), normalized.getValue());
103     }
104
105     protected void doPutWithEnsureParents(final DOMDataReadWriteTransaction writeTransaction,
106             final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
107         invalidateCache(store, path);
108         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
109                 .toNormalizedNode(path, data);
110
111         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
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             try {
118                 currentOp = currentOp.getChild(currentArg);
119             } catch (DataNormalizationException e) {
120                 throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
121             }
122             currentArguments.add(currentArg);
123             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier currentPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(
124                     currentArguments);
125
126             final Optional<NormalizedNode<?, ?>> d;
127             try {
128                 d = writeTransaction.read(store, currentPath).get();
129             } catch (InterruptedException | ExecutionException e) {
130                 LOG.error("Failed to read pre-existing data from store {} path {}", store, currentPath, e);
131                 throw new IllegalStateException("Failed to read pre-existing data", e);
132             }
133
134             if (!d.isPresent() && iterator.hasNext()) {
135                 writeTransaction.put(store, currentPath, currentOp.createDefault(currentArg));
136             }
137         }
138         //LOG .info("Tx: {} : Putting data {}",getDelegate().getIdentifier(),normalized.getKey());
139         writeTransaction.put(store, normalized.getKey(), normalized.getValue());
140     }
141
142     protected void doMerge(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
143             final InstanceIdentifier<?> path, final DataObject data) {
144         invalidateCache(store, path);
145         final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
146                 .toNormalizedNode(path, data);
147         writeTransaction.merge(store, normalized.getKey(), normalized.getValue());
148     }
149
150     protected void doDelete(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
151             final InstanceIdentifier<?> path) {
152         invalidateCache(store, path);
153         final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = codec.toNormalized(path);
154         writeTransaction.delete(store, normalized);
155     }
156
157     protected ListenableFuture<RpcResult<TransactionStatus>> doCommit(final DOMDataWriteTransaction writeTransaction) {
158         return writeTransaction.commit();
159     }
160
161     protected void doCancel(final DOMDataWriteTransaction writeTransaction) {
162         writeTransaction.cancel();
163     }
164
165     protected ListenableFuture<Optional<DataObject>> doRead(final DOMDataReadTransaction readTransaction,
166             final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
167         final DataObject dataObject = getFromCache(store, path);
168         if (dataObject == null) {
169             final ListenableFuture<Optional<NormalizedNode<?, ?>>> future = readTransaction.read(store,
170                     codec.toNormalized(path));
171             return transformFuture(store, path, future);
172         } else {
173             return Futures.immediateFuture(Optional.of(dataObject));
174         }
175     }
176
177     private DataObject getFromCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
178         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
179         if (cache != null) {
180             return cache.getIfPresent(path);
181         }
182         return null;
183     }
184
185     private void updateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
186             final DataObject dataObject) {
187         // Check if cache exists. If not create one.
188         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
189         if (cache == null) {
190             cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(1, TimeUnit.MINUTES).build();
191
192         }
193
194         cache.put(path, dataObject);
195     }
196
197     private void invalidateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
198         // FIXME: Optimization: invalidate only parents and children of path
199         Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
200         cache.invalidateAll();
201         LOG.trace("Cache invalidated");
202     }
203
204 }