Merge "Allow no payload for RPCs with no input"
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / handlers / TransactionChainHandler.java
1 /*
2  * Copyright (c) 2016 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.restconf.nb.rfc8040.handlers;
9
10 import java.util.Objects;
11 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
12 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
13 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
14 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
15 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 /**
20  * Implementation of {@link TransactionChainHandler}.
21  *
22  */
23 public class TransactionChainHandler implements Handler<DOMTransactionChain>, AutoCloseable {
24     private static final Logger LOG = LoggerFactory.getLogger(TransactionChainHandler.class);
25
26     private final DOMTransactionChainListener transactionChainListener = new DOMTransactionChainListener() {
27         @Override
28         public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
29                 final Throwable cause) {
30             LOG.warn("TransactionChain({}) {} FAILED!", chain, transaction.getIdentifier(), cause);
31             reset();
32             throw new RestconfDocumentedException("TransactionChain(" + chain + ") not committed correctly", cause);
33         }
34
35         @Override
36         public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
37             LOG.trace("TransactionChain({}) SUCCESSFUL", chain);
38         }
39     };
40
41     private final DOMDataBroker dataBroker;
42
43     private volatile DOMTransactionChain transactionChain;
44
45     /**
46      * Prepare transaction chain service for Restconf services.
47      */
48     public TransactionChainHandler(final DOMDataBroker dataBroker) {
49         this.dataBroker = Objects.requireNonNull(dataBroker);
50         transactionChain = Objects.requireNonNull(dataBroker.createTransactionChain(transactionChainListener));
51     }
52
53     @Override
54     public DOMTransactionChain get() {
55         return this.transactionChain;
56     }
57
58     public synchronized void reset() {
59         LOG.trace("Resetting TransactionChain({})", transactionChain);
60         transactionChain.close();
61         transactionChain = dataBroker.createTransactionChain(transactionChainListener);
62     }
63
64     @Override
65     public synchronized void close() {
66         transactionChain.close();
67     }
68 }