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