aboutsummaryrefslogtreecommitdiffstats
path: root/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorTransaction.java
blob: 1345cabcd403127d9c957cfb3400c46e01f032a5 (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
// Copyright 2016 Yahoo Inc. 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;

/**
 * Transaction implementation against ZooKeeper.
 *
 * @author lulf
 */
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;
    }

    @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(e);
        }
    }

}