Use mdsal's MappingCheckedFuture
[mdsal.git] / dom / mdsal-dom-api / src / main / java / org / opendaylight / mdsal / dom / api / DOMDataTreeCommitCohort.java
1 /*
2  * Copyright (c) 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 package org.opendaylight.mdsal.dom.api;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.collect.Iterables;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.mdsal.common.api.DataValidationFailedException;
21 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
22 import org.opendaylight.mdsal.common.api.PostCanCommitStep;
23 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
24 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Commit cohort participating in commit of data modification, which can validate data tree
29  * modifications, with option to reject supplied modification, and with callbacks describing state
30  * of commit.
31  *
32  * <h2>Performance implications</h2>
33  * {@link DOMDataTreeCommitCohort}s are hooked up into commit of data tree changes and MAY
34  * negatively affect performance of data broker / store.
35  * Implementations of this interface are discouraged, unless you really need ability to veto data
36  * tree changes, or to provide external state change in sync with visibility of committed data.
37  *
38  * <h2>Implementation requirements</h2>
39  * <h3>Correctness assumptions</h3> Implementation SHOULD use only the {@link DOMDataTreeCandidate} instances and
40  * provided {@link SchemaContext} for validation purposes.
41  * Use of any other external mutable state is discouraged, implementation MUST NOT use any
42  * transaction related APIs on same data broker / data store instance during invocation of
43  * callbacks, except ones provided as argument. Note that this MAY BE enforced by some
44  * implementations of {@link DOMDataBroker} or DOMDataCommitCoordinator
45  * Note that this may be enforced by some implementations of {@link DOMDataTreeCommitCohortRegistry}
46  * and such calls may fail.
47  * <h3>Correct model usage</h3> If implementation is performing YANG-model driven validation
48  * implementation SHOULD use provided schema context.
49  * Any other instance of {@link SchemaContext} obtained by other means, may not be valid for the
50  * associated DOMDataTreeCandidates and it may lead to incorrect validation or processing of provided
51  * data.
52  * <h3>DataTreeCandidate assumptions</h3> Implementation SHOULD NOT make any assumptions on a
53  * {@link DOMDataTreeCandidate} being successfully committed until associated
54  * {@link PostCanCommitStep#preCommit()} and
55  * {@link org.opendaylight.mdsal.common.api.PostPreCommitStep#commit()} callback was invoked.
56  * <h2>Usage patterns</h2>
57  * <h3>Data Tree Validator</h3>
58  * Validator is implementation, which only validates {@link DOMDataTreeCandidate} instances and does not
59  * retain any state derived from edited data - does not care if a {@link DOMDataTreeCandidate} was
60  * rejected afterwards or transaction was cancelled.
61  * Implementation may opt-out from receiving {@code preCommit()}, {@code commit()}, {@code abort()}
62  * callbacks by returning {@link PostCanCommitStep#NOOP}.
63  *
64  * <p>
65  * @author Tony Tkacik
66  */
67 // TODO: Provide example and describe more usage patterns
68 @Beta
69 public interface DOMDataTreeCommitCohort {
70
71     /**
72      * DO NOT implement or invoke this method. It is deprecated in favor of
73      * {@link #canCommit(Object, Collection, SchemaContext)} and only exists for backwards compatibility. The
74      * default implementation returns {@link PostCanCommitStep#NOOP_SUCCESS_FUTURE} and is invoked by the
75      * default implementation of {@link #canCommit(Object, Collection, SchemaContext)}.
76      *
77      * @deprecated Implement and invoke {@link #canCommit(Object, Collection, SchemaContext)} instead.
78      */
79     @Deprecated
80     @Nonnull
81     default CheckedFuture<PostCanCommitStep, DataValidationFailedException> canCommit(@Nonnull final Object txId,
82             @Nonnull final DOMDataTreeCandidate candidate, @Nonnull final SchemaContext ctx) {
83         LoggerFactory.getLogger(getClass()).error(
84                 "The default implementation of DOMDataTreeCommitCohort#canCommit(Object, DOMDataTreeCandidate, "
85                 + "SchemaContext) was invoked on {}", getClass());
86         return PostCanCommitStep.NOOP_SUCCESS_FUTURE;
87     }
88
89     /**
90      * Validates supplied data tree candidates and associates cohort-specific steps with data broker
91      * transaction.
92      * If {@link DataValidationFailedException} is thrown by implementation, commit of supplied data
93      * will be prevented, with the DataBroker transaction providing the thrown exception as the
94      * cause of failure.
95      * Note the implementations are expected to do validation and processing asynchronous.
96      * Implementations SHOULD do processing fast, and are discouraged SHOULD NOT block on any
97      * external resources.
98      * Implementation MUST NOT access any data transaction related APIs during invocation of
99      * callback. Note that this may be enforced by some implementations of
100      * {@link DOMDataTreeCommitCohortRegistry} and such calls may fail.
101      * Implementation MAY opt-out from implementing other steps by returning
102      * {@link PostCanCommitStep#NOOP}. Otherwise implementation MUST return instance of
103      * {@link PostCanCommitStep}, which will be used to invoke
104      * {@link org.opendaylight.mdsal.common.api.PostPreCommitStep#commit()} or
105      * {@link PostCanCommitStep#abort()} based on accepting data by data broker and or other commit
106      * cohorts.
107      *
108      * @param txId Transaction identifier. SHOULD be used only for reporting and correlation.
109      *        Implementation MUST NOT use {@code txId} for validation.
110      * @param candidates Data Tree candidates to be validated and committed.
111      * @param ctx Schema Context to which Data Tree candidate should conform.
112      * @return Checked future which will successfully complete with the user-supplied implementation of
113      *         {@link PostCanCommitStep} if all candidates are valid, or a failed checked future with a
114      *         {@link DataValidationFailedException} if and only if a provided
115      *         {@link DOMDataTreeCandidate} instance did not pass validation. Users are encouraged to use
116      *         more specific subclasses of this exception to provide additional information about
117      *         validation failure reason.
118      */
119     @Nonnull
120     default CheckedFuture<PostCanCommitStep, DataValidationFailedException> canCommit(@Nonnull final Object txId,
121             @Nonnull final Collection<DOMDataTreeCandidate> candidates, @Nonnull final SchemaContext ctx) {
122         LoggerFactory.getLogger(getClass()).warn("DOMDataTreeCommitCohort implementation {} should override "
123                 + "canCommit(Object, Collection, SchemaContext)", getClass());
124
125         // For backwards compatibility, the default implementation is to invoke the deprecated
126         // canCommit(Object, DOMDataTreeCandidate, SchemaContext) method for each DOMDataTreeCandidate and return the
127         // last PostCanCommitStep.
128         List<ListenableFuture<PostCanCommitStep>> futures = new ArrayList<>();
129         for (DOMDataTreeCandidate candidate : candidates) {
130             futures.add(canCommit(txId, candidate, ctx));
131         }
132
133         final ListenableFuture<PostCanCommitStep> resultFuture = Futures.transform(Futures.allAsList(futures),
134             input -> input.get(input.size() - 1), MoreExecutors.directExecutor());
135         return MappingCheckedFuture.create(resultFuture, new DataValidationFailedExceptionMapper("canCommit",
136                 Iterables.getLast(candidates).getRootPath()));
137     }
138
139     /**
140      * An ExceptionMapper that translates an Exception to a DataValidationFailedException.
141      */
142     class DataValidationFailedExceptionMapper extends ExceptionMapper<DataValidationFailedException> {
143         private final DOMDataTreeIdentifier failedTreeId;
144
145         public DataValidationFailedExceptionMapper(final String opName, final DOMDataTreeIdentifier failedTreeId) {
146             super(opName, DataValidationFailedException.class);
147             this.failedTreeId = failedTreeId;
148         }
149
150         @Override
151         protected DataValidationFailedException newWithCause(final String message, final Throwable cause) {
152             return new DataValidationFailedException(DOMDataTreeIdentifier.class, failedTreeId, message, cause);
153         }
154     }
155 }