Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / api / datastore / BaseCallbackContext.java
blob2192caf0e5446bde06f329971456b0434e5339b2
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;
12 /**
13 * Abstract base class with a common {@link CallbackContext} implementation.
16 abstract class BaseCallbackContext<T> implements CallbackContext<T> {
17 private final CurrentTransactionProvider currentTxnProvider;
19 /**
20 * All elements provided to the operation that triggered the callback.
22 private final List<T> elements;
24 /**
25 * The index into {@link #elements} of the "current" element.
27 private int currentIndex;
29 /**
30 * @param currentTxnProvider Provides the current transaction
31 * @param elements All elements involved in the operation that triggered the
32 * callback.
34 BaseCallbackContext(CurrentTransactionProvider currentTxnProvider, List<T> elements) {
35 this.currentTxnProvider = Preconditions.checkNotNull(currentTxnProvider);
36 this.elements = Collections.unmodifiableList(Preconditions.checkNotNull(elements));
39 @Override
40 public List<T> getElements() {
41 return elements;
44 @Override
45 public Transaction getCurrentTransaction() {
46 return currentTxnProvider.getCurrentTransaction(null);
49 @Override
50 public int getCurrentIndex() {
51 return currentIndex;
54 @Override
55 public T getCurrentElement() {
56 return elements.get(currentIndex);
59 /**
60 * Executes all appropriate callbacks for the elements in this context.
62 * @param callbacksByKind A Multimap containing lists of callbacks, organized by
63 * kind.
64 * @param noKindCallbacks Callbacks that apply to all elements, independent
65 * of kind.
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) {
77 callback.run(this);
79 currentIndex++;
83 /**
84 * Abstract method that, given an element, knows how to extract its kind.
86 abstract String getKind(T ele);