aboutsummaryrefslogtreecommitdiffstats
path: root/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorCreateOperation.java
blob: 633fd9a7a20be3c7545b3ce9bf261d8adb76178a (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
// 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.path.Path;
import com.yahoo.vespa.curator.Curator;
import org.apache.curator.framework.api.transaction.CuratorTransaction;

import java.util.Optional;

/**
 * ZooKeeper create operation.
 *
 * @author Ulf Lilleengen
 * @author bratseth
 */
class CuratorCreateOperation implements CuratorOperation {

    private final String path;
    private final Optional<byte[]> data;

    CuratorCreateOperation(String path, Optional<byte[]> data) {
        this.path = path;
        this.data = data;
    }

    @Override
    public void check(Curator curator, TransactionChanges changes) {
        int lastSlash = path.lastIndexOf("/");
        if (lastSlash < 0) return; // root; ok
        String parent = path.substring(0, lastSlash);
        if ( ! parent.isEmpty() && ! curator.exists(Path.fromString(parent)) && ! changes.create(parent))
            throw new IllegalStateException("Cannot perform " + this + ": Parent '" + parent + "' does not exist");
        changes.addCreate(path);
    }

    @Override
    public CuratorTransaction and(CuratorTransaction transaction) throws Exception {
        if (data.isPresent()) {
            return transaction.create().forPath(path, data.get()).and();
        } else {
            return transaction.create().forPath(path).and();
        }
    }

    @Override
    public String toString() {
        return "CREATE " + path;
    }

}