blob: 3026a90cea75ff3d15a0e53ebe14293c785a4d5a (
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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.curator.transaction;
import com.yahoo.transaction.AbstractTransaction;
import com.yahoo.vespa.curator.Curator;
import org.apache.curator.framework.api.transaction.CuratorTransactionFinal;
import java.util.List;
import java.util.stream.Collectors;
/**
* Transaction implementation against ZooKeeper.
*
* @author Ulf Lilleengen
*/
public class CuratorTransaction extends AbstractTransaction {
private final Curator curator;
private boolean prepared = false;
public CuratorTransaction(Curator curator) {
this.curator = curator;
}
/** Returns an empty curator transaction */
public static CuratorTransaction empty(Curator curator) {
return new CuratorTransaction(curator);
}
/** Returns a curator transaction having a single operation */
public static CuratorTransaction from(CuratorOperation operation, Curator curator) {
CuratorTransaction transaction = new CuratorTransaction(curator);
transaction.add(operation);
return transaction;
}
/** Returns a curator transaction having a list of operations */
public static CuratorTransaction from(List<CuratorOperation> operations, Curator curator) {
CuratorTransaction transaction = new CuratorTransaction(curator);
for (Operation operation : operations)
transaction.add(operation);
return transaction;
}
@Override
public void prepare() {
TransactionChanges changes = new TransactionChanges();
for (Operation operation : operations())
((CuratorOperation)operation).check(curator, changes);
prepared = true;
}
/** Commits this transaction. If it is not already prepared this will prepare it first */
@Override
public void commit() {
try {
if ( ! prepared)
prepare();
org.apache.curator.framework.api.transaction.CuratorTransaction transaction = curator.framework().inTransaction();
for (Operation operation : operations()) {
transaction = ((CuratorOperation)operation).and(transaction);
}
((CuratorTransactionFinal) transaction).commit();
} catch (Exception e) {
throw new IllegalStateException("Failed to commit " + toString(), e);
}
}
@Override
public String toString() {
return operations().stream().map(Object::toString).collect(Collectors.joining(","));
}
}
|