aboutsummaryrefslogtreecommitdiffstats
path: root/config/src/test/java/com/yahoo/config/subscription/AppService.java
blob: e56724cfd6fa9ac7ab3d9b7f17182040dce1e6cf (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription;

import com.yahoo.foo.AppConfig;
import com.yahoo.vespa.config.TimingValues;

/**
 * @author hmusum
 *
 * Application that subscribes to config defined in app.def and
 * generated code in AppConfig.java.
 */
class AppService {

    private int timesConfigured = 0;

    private AppConfig config = null;
    private final ConfigSubscriber subscriber;

    private boolean stopThread = false;

    AppService(String configId, ConfigSourceSet csource) {
        this(configId, csource, null);
    }

    int timesConfigured() { return timesConfigured; }

    private AppService(String configId, ConfigSourceSet csource, TimingValues timingValues) {
        if (csource == null) throw new IllegalArgumentException("Config source cannot be null");
        subscriber = new ConfigSubscriber(csource);
        ConfigHandle<AppConfig> temp;
        if (timingValues == null) {
            temp = subscriber.subscribe(AppConfig.class, configId);
        } else {
            temp = subscriber.subscribe(AppConfig.class, configId, csource, timingValues);
        }
        ConfigHandle<AppConfig> handle = temp;
        Thread configThread = new Thread(() -> {
            while (!stopThread) {
                boolean changed = subscriber.nextConfig(500, false);
                if (changed) {
                    configure(handle.getConfig());
                    timesConfigured++;
                }
            }
        });
        subscriber.nextConfig(5000, false);
        timesConfigured++;
        configure(handle.getConfig());
        configThread.setDaemon(true);
        configThread.start();
    }

    private void configure(AppConfig config) {
        this.config = config;
    }

    public void cancelSubscription() {
        subscriber.close();
        stopThread = true;
    }

    public AppConfig getConfig() {
        return config;
    }

    public boolean isConfigured() {
        return (timesConfigured > 0);
    }

}