1 // Copyright 2011 Google. All Rights Reserved.
2 package com
.google
.appengine
.api
.datastore
;
4 import com
.google
.common
.base
.Preconditions
;
5 import com
.google
.common
.collect
.Iterables
;
6 import com
.google
.common
.collect
.Multimap
;
8 import java
.util
.Collection
;
9 import java
.util
.Collections
;
10 import java
.util
.List
;
13 * Abstract base class with a common {@link CallbackContext} implementation.
16 abstract class BaseCallbackContext
<T
> implements CallbackContext
<T
> {
17 private final CurrentTransactionProvider currentTxnProvider
;
20 * All elements provided to the operation that triggered the callback.
22 private final List
<T
> elements
;
25 * The index into {@link #elements} of the "current" element.
27 private int currentIndex
;
30 * @param currentTxnProvider Provides the current transaction
31 * @param elements All elements involved in the operation that triggered the
34 BaseCallbackContext(CurrentTransactionProvider currentTxnProvider
, List
<T
> elements
) {
35 this.currentTxnProvider
= Preconditions
.checkNotNull(currentTxnProvider
);
36 this.elements
= Collections
.unmodifiableList(Preconditions
.checkNotNull(elements
));
40 public List
<T
> getElements() {
45 public Transaction
getCurrentTransaction() {
46 return currentTxnProvider
.getCurrentTransaction(null);
50 public int getCurrentIndex() {
55 public T
getCurrentElement() {
56 return elements
.get(currentIndex
);
60 * Executes all appropriate callbacks for the elements in this context.
62 * @param callbacksByKind A Multimap containing lists of callbacks, organized by
64 * @param noKindCallbacks Callbacks that apply to all elements, independent
67 * @throws IllegalStateException If this method has already been called.
69 void executeCallbacks(Multimap
<String
, DatastoreCallbacksImpl
.Callback
> callbacksByKind
,
70 Collection
<DatastoreCallbacksImpl
.Callback
> noKindCallbacks
) {
71 Preconditions
.checkState(currentIndex
== 0,
72 "executeCallbacks cannot be called more than once.");
73 for (T ele
: elements
) {
74 Iterable
<DatastoreCallbacksImpl
.Callback
> allCallbacksToRun
=
75 Iterables
.concat(callbacksByKind
.get(getKind(ele
)), noKindCallbacks
);
76 for (DatastoreCallbacksImpl
.Callback callback
: allCallbacksToRun
) {
84 * Abstract method that, given an element, knows how to extract its kind.
86 abstract String
getKind(T ele
);