Skip to main content
summaryrefslogtreecommitdiffstats
blob: bbb1592ed88fb62db5af7098d390b83268994ade (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*****************************************************************************
 * Copyright (c) 2015, 2018 Christian W. Damus and others.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.infra.core.utils;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.Transaction;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.TransactionalEditingDomainEvent;
import org.eclipse.emf.transaction.TransactionalEditingDomainListener;
import org.eclipse.emf.transaction.impl.EMFCommandTransaction;
import org.eclipse.emf.transaction.impl.InternalTransactionalCommandStack;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.papyrus.infra.core.Activator;

import com.google.common.collect.Maps;

/**
 * An {@link Executor} that executes {@link Runnable}s at the pre-commit phase of the active
 * write transaction of a {@link TransactionalEditingDomain} or at some other time if no
 * write transaction is active.
 */
class TransactionPrecommitExecutor implements Executor, TransactionalEditingDomainListener {
	private final TransactionalEditingDomain editingDomain;
	private final Executor fallback;

	private final AtomicBoolean writeActive = new AtomicBoolean();
	private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
	private final IExecutorPolicy policy;
	private final Map<?, ?> options;

	private final AtomicBoolean disposed = new AtomicBoolean();

	TransactionPrecommitExecutor(TransactionalEditingDomain domain, Executor fallback, IExecutorPolicy policy, Map<?, ?> options) {
		super();

		this.editingDomain = domain;
		this.fallback = fallback;
		this.policy = (policy == null) ? IExecutorPolicy.NULL : policy;
		this.options = ((options != null) && options.isEmpty()) ? null : options;

		TransactionUtil.getAdapter(domain, TransactionalEditingDomain.Lifecycle.class).addTransactionalEditingDomainListener(this);
	}

	/**
	 * Disposes me. This entails at least desisting in listening to lifecycle changes in
	 * my editing domain.
	 */
	public void dispose() {
		if (disposed.compareAndSet(false, true)) {
			TransactionalEditingDomain.Lifecycle lifecycle = TransactionUtil.getAdapter(editingDomain, TransactionalEditingDomain.Lifecycle.class);
			if (lifecycle != null) {
				lifecycle.removeTransactionalEditingDomainListener(this);
			}
		}
	}

	@Override
	public void execute(Runnable command) {
		if (disposed.get()) {
			return;
		}

		if (writeActive.get() && selectSelf(command)) {
			queue.offer(command);
		} else {
			fallback.execute(command);
		}
	}

	private boolean selectSelf(Runnable task) {
		return IExecutorPolicy.Ranking.select(policy, task, this, fallback) == this;
	}

	//
	// Editing Domain Lifecycle handling
	//

	@Override
	public void editingDomainDisposing(TransactionalEditingDomainEvent event) {
		queue.clear();
	}

	//
	// Transaction lifecycle handling
	//

	@Override
	public void transactionStarted(TransactionalEditingDomainEvent event) {
		// We should only attempt to record triggers in a transaction that has triggers enabled.
		// In particular, unprotected writes are in an otherwise read-only context and should be
		// treated as such
		final Transaction transaction = event.getTransaction();
		writeActive.set(!transaction.isReadOnly() && hasTriggersEnabled(transaction));
	}

	private boolean hasTriggersEnabled(Transaction transaction) {
		final Map<?, ?> options = transaction.getOptions();
		return !Boolean.TRUE.equals(options.get(Transaction.OPTION_UNPROTECTED))
				&& !Boolean.TRUE.equals(options.get(Transaction.OPTION_NO_TRIGGERS))
				&& !Boolean.TRUE.equals(options.get(Transaction.OPTION_IS_UNDO_REDO_TRANSACTION));
	}

	@Override
	public void transactionClosed(TransactionalEditingDomainEvent event) {
		writeActive.set(false);

		if (queue.peek() != null) {
			// Punt the remaining tasks
			for (Runnable next = queue.poll(); next != null; next = queue.poll()) {
				fallback.execute(next);
			}
		}
	}

	@Override
	public void transactionStarting(TransactionalEditingDomainEvent event) {
		// Pass
	}

	@Override
	public void transactionInterrupted(TransactionalEditingDomainEvent event) {
		// Pass
	}

	@Override
	public void transactionClosing(TransactionalEditingDomainEvent event) {
		if (queue.peek() != null) {
			// Inject tasks into the transaction as a trigger command
			Command trigger = new RecordingCommand(event.getSource(), "Deferred Tasks") {

				@Override
				protected void doExecute() {
					for (Runnable next = queue.poll(); next != null; next = queue.poll()) {
						try {
							next.run();
						} catch (Exception e) {
							Activator.log.error("Uncaught exception in transaction pre-commit task.", e); //$NON-NLS-1$
						}
					}
				}
			};

			final Transaction transaction = event.getTransaction();
			final Command triggeringCommand;
			if (transaction instanceof EMFCommandTransaction) {
				triggeringCommand = ((EMFCommandTransaction) transaction).getCommand();
			} else {
				triggeringCommand = null;
			}

			final InternalTransactionalCommandStack stack = (InternalTransactionalCommandStack) event.getSource().getCommandStack();
			try {
				Map<?, ?> options = transaction.getOptions();
				Map<Object, Object> mergedOptions = null;

				if (this.options != null) {
					options = (mergedOptions == null) ? (mergedOptions = Maps.newHashMap(options)) : mergedOptions;
					mergedOptions.putAll(this.options);
				}
				if (transaction.isReadOnly()) {
					// Must use an unprotected write transaction
					options = (mergedOptions == null) ? (mergedOptions = Maps.newHashMap(options)) : mergedOptions;
					mergedOptions.put(Transaction.OPTION_UNPROTECTED, true);
				}

				stack.executeTriggers(triggeringCommand, Collections.singletonList(trigger), options);
			} catch (Exception e) {
				Activator.log.error("Failed to execute transaction pre-commit tasks.", e); //$NON-NLS-1$
			}
		}
	}

}

Back to the top