aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/result/PositionsData.java
blob: a07eaa2438dc99f4d72940dc72f5997944e8e254 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;

import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.Inspectable;
import com.yahoo.data.access.Type;
import com.yahoo.data.JsonProducer;
import com.yahoo.data.XmlProducer;
import com.yahoo.data.access.simple.JsonRender;

/**
 * A wrapper for structured data representing an array of position values.
 **/
public class PositionsData implements Inspectable, JsonProducer, XmlProducer {

    private final Inspector value;

    public PositionsData(Inspector value) {
        this.value = value;
        if (value.type() != Type.ARRAY) {
            throw new IllegalArgumentException("PositionsData expects an array of positions, got: "+value);
        }
    }

    @Override
    public Inspector inspect() {
        return value;
    }

    public String toString() {
        return toJson();
    }

    @Override
    public StringBuilder writeJson(StringBuilder target) {
        return JsonRender.render(value, target, true);
    }

    @Override
    public StringBuilder writeXML(StringBuilder target) {
        for (int i = 0; i < value.entryCount(); i++) {
            Inspector pos = value.entry(i);
            target.append("<position ");
            for (java.util.Map.Entry<String, Inspector> entry : pos.fields()) {
                Inspector v = entry.getValue();
                if (v.type() == Type.STRING) {
                    target.append(entry.getKey());
                    target.append("=\"");
                    target.append(entry.getValue().asString());
                    target.append("\" ");
                }
                if (v.type() == Type.LONG) {
                    target.append(entry.getKey());
                    target.append("=\"");
                    target.append(entry.getValue().asLong());
                    target.append("\" ");
                }
            }
            target.append("/>");
        }
        return target;
    }

}