aboutsummaryrefslogtreecommitdiffstats
path: root/config/src/main/java/com/yahoo/vespa/config/protocol/DefContent.java
blob: 6b3c1f0040db4de104d107928152bdcc17abe5ed (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.protocol;

import com.yahoo.config.ConfigInstance;
import com.yahoo.config.ConfigurationRuntimeException;
import com.yahoo.slime.*;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author Ulf Lilleengen
*/
public class DefContent {
    private final List<String> data;

    private DefContent(List<String> data) {
        this.data = data;
    }

    public String[] asStringArray() {
        return data.toArray(new String[data.size()]);
    }

    public List<String> asList() {
        return data;
    }

    public String asString() {
        return com.yahoo.text.StringUtilities.implode(asStringArray(), "\n");
    }

    static DefContent fromSlime(Inspector data) {
        final List<String> lst = new ArrayList<>();
        data.traverse((ArrayTraverser) (idx, inspector) -> lst.add(inspector.asString()));
        return new DefContent(lst);
    }

    public static DefContent fromClass(Class<? extends ConfigInstance> clazz) {
        return fromArray(defSchema(clazz));
    }

    public static DefContent fromList(List<String> def) {
        return new DefContent(def);
    }

    public static DefContent fromArray(String[] schema) {
        return fromList(Arrays.asList(schema));
    }

    /**
     * The def file payload of the actual class of the given config.
     *
     * @param configClass the class of a generated config instance
     * @return a String array with the config definition (one line per element)
     */
    private static String[] defSchema(Class<? extends ConfigInstance> configClass) {
        if (configClass==null) return new String[0];
        try {
            Field f = configClass.getField("CONFIG_DEF_SCHEMA");
            return (String[]) f.get(configClass);
        } catch (NoSuchFieldException e) {
            return new String[0];
        } catch (Exception e) {
            throw new ConfigurationRuntimeException(e);
        }
    }

    public void serialize(final Cursor cursor) {
        for (String line : data) {
            cursor.addString(line);
        }
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }
}