07711628034df5bd0e03db31ca8e97152fd76010
[mdsal.git] / dom / mdsal-dom-spi / src / main / java / org / opendaylight / mdsal / dom / spi / store / AbstractDOMStoreTransaction.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.mdsal.dom.spi.store;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.eclipse.jdt.annotation.Nullable;
18
19 /**
20  * Abstract DOM Store Transaction.
21  * Convenience super implementation of DOM Store transaction which provides common implementation of
22  * {@link #toString()} and {@link #getIdentifier()}.
23  * It can optionally capture the context where it was allocated.
24  *
25  * @param <T> identifier type
26  */
27 @Beta
28 @NonNullByDefault
29 public abstract class AbstractDOMStoreTransaction<T> implements DOMStoreTransaction {
30     private final @Nullable Throwable debugContext;
31     private final T identifier;
32
33     protected AbstractDOMStoreTransaction(final T identifier) {
34         this(identifier, false);
35     }
36
37     @SuppressFBWarnings("NP_STORE_INTO_NONNULL_FIELD")
38     protected AbstractDOMStoreTransaction(final T identifier, final boolean debug) {
39         this.identifier = requireNonNull(identifier, "Identifier must not be null.");
40         this.debugContext = debug ? new Throwable().fillInStackTrace() : null;
41     }
42
43     @Override
44     public final T getIdentifier() {
45         return identifier;
46     }
47
48     /**
49      * Return the context in which this transaction was allocated.
50      *
51      * @return The context in which this transaction was allocated, or null
52      *         if the context was not recorded.
53      */
54     public final @Nullable Throwable getDebugContext() {
55         return debugContext;
56     }
57
58     @Override
59     public final String toString() {
60         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
61     }
62
63     /**
64      * Add class-specific toString attributes.
65      *
66      * @param toStringHelper
67      *            ToStringHelper instance
68      * @return ToStringHelper instance which was passed in
69      */
70     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
71         return toStringHelper.add("id", identifier);
72     }
73 }