Bug 8351: Enforce check-style rules for restconf - sal-rest-docgen
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / tx / AbstractWriteTx.java
1 /*
2  * Copyright (c) 2014, 2015 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
9 package org.opendaylight.netconf.sal.connect.netconf.sal.tx;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.SettableFuture;
18 import java.util.List;
19 import java.util.concurrent.CopyOnWriteArrayList;
20 import javax.annotation.Nullable;
21 import org.opendaylight.controller.config.util.xml.DocumentedException;
22 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
29 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
30 import org.opendaylight.yangtools.yang.common.RpcError;
31 import org.opendaylight.yangtools.yang.common.RpcResult;
32 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
33 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
36 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
42
43     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
44
45     protected final RemoteDeviceId id;
46     protected final NetconfBaseOps netOps;
47     protected final boolean rollbackSupport;
48     protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
49     private final List<TxListener> listeners = new CopyOnWriteArrayList<>();
50     // Allow commit to be called only once
51     protected boolean finished = false;
52
53     public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
54         this.netOps = netOps;
55         this.id = id;
56         this.rollbackSupport = rollbackSupport;
57         this.resultsFutures = Lists.newArrayList();
58         init();
59     }
60
61     protected static boolean isSuccess(final DOMRpcResult result) {
62         return result.getErrors().isEmpty();
63     }
64
65     protected void checkNotFinished() {
66         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
67     }
68
69     protected boolean isFinished() {
70         return finished;
71     }
72
73     @Override
74     public synchronized boolean cancel() {
75         if(isFinished()) {
76             return false;
77         }
78         listeners.forEach(listener -> listener.onTransactionCancelled(this));
79         finished = true;
80         cleanup();
81         return true;
82     }
83
84     protected abstract void init();
85
86     protected abstract void cleanup();
87
88     @Override
89     public Object getIdentifier() {
90         return this;
91     }
92
93     @Override
94     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
95         checkEditable(store);
96
97         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
98         if(containsOnlyNonVisibleData(path, data)) {
99             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
100             return;
101         }
102
103         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path);
104         editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
105     }
106
107     @Override
108     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
109         checkEditable(store);
110
111         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
112         if (containsOnlyNonVisibleData(path, data)) {
113             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
114             return;
115         }
116
117         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path);
118         editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
119     }
120
121     /**
122      * Check whether the data to be written consists only from mixins
123      */
124     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
125         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
126         // any other mixin nodes are contained by a "regular" node thus visible when serialized
127         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
128     }
129
130     @Override
131     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
132         checkEditable(store);
133         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path);
134         editConfig(path, Optional.<NormalizedNode<?, ?>>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete");
135     }
136
137     @Override
138     public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
139         listeners.forEach(listener -> listener.onTransactionSubmitted(this));
140         checkNotFinished();
141         finished = true;
142         final ListenableFuture<RpcResult<TransactionStatus>> result = performCommit();
143         Futures.addCallback(result, new FutureCallback<RpcResult<TransactionStatus>>() {
144             @Override
145             public void onSuccess(@Nullable final RpcResult<TransactionStatus> result) {
146                 if (result != null && result.isSuccessful()) {
147                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
148                 } else {
149                     final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", result.getErrors().toArray(new RpcError[result.getErrors().size()]));
150                     listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
151                 }
152             }
153
154             @Override
155             public void onFailure(final Throwable t) {
156                 listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, t));
157             }
158         });
159         return result;
160     }
161
162     protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
163
164     private void checkEditable(final LogicalDatastoreType store) {
165         checkNotFinished();
166         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
167     }
168
169     protected abstract void editConfig(final YangInstanceIdentifier path, final Optional<NormalizedNode<?, ?>> data, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final String operation);
170
171     protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
172         final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
173
174         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
175             @Override
176             public void onSuccess(final List<DOMRpcResult> domRpcResults) {
177                 domRpcResults.forEach(domRpcResult -> {
178                     if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
179                         final NetconfDocumentedException exception =
180                                 new NetconfDocumentedException(id + ":RPC during tx failed",
181                                         DocumentedException.ErrorType.APPLICATION,
182                                         DocumentedException.ErrorTag.OPERATION_FAILED,
183                                         DocumentedException.ErrorSeverity.ERROR);
184                         transformed.setException(exception);
185                     }
186                 });
187
188                 if(!transformed.isDone()) {
189                     transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
190                 }
191             }
192
193             @Override
194             public void onFailure(final Throwable throwable) {
195                 final NetconfDocumentedException exception =
196                         new NetconfDocumentedException(
197                                 id + ":RPC during tx returned an exception",
198                                 new Exception(throwable),
199                                 DocumentedException.ErrorType.APPLICATION,
200                                 DocumentedException.ErrorTag.OPERATION_FAILED,
201                                 DocumentedException.ErrorSeverity.ERROR);
202                 transformed.setException(exception);
203             }
204         });
205
206         return transformed;
207     }
208
209     AutoCloseable addListener(final TxListener listener) {
210         listeners.add(listener);
211         return () -> listeners.remove(listener);
212     }
213 }