aboutsummaryrefslogtreecommitdiffstats
path: root/config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceSerializer.java
blob: f8028190402e3174796464c317221c2fc7aa24ab (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
// 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.slime.Cursor;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * Serialize a {@link TraceNode} to {@link com.yahoo.slime.Slime}.
 *
 * @author Ulf Lilleengen
 */
public class SlimeTraceSerializer extends TraceVisitor {
    static final String TIMESTAMP = "timestamp";
    static final String PAYLOAD = "payload";
    static final String CHILDREN = "children";
    final Deque<Cursor> cursors = new ArrayDeque<>();

    public SlimeTraceSerializer(Cursor cursor) {
        cursors.push(cursor);
    }

    @Override
    public void visit(TraceNode node) {
        Cursor current = cursors.pop();
        current.setLong(TIMESTAMP, node.timestamp());
        encodePayload(current, node.payload());
        addChildrenCursors(current, node);
    }

    private void encodePayload(Cursor current, Object payload) {
        if (payload instanceof String) {
            current.setString(PAYLOAD, (String)payload);
        } else if (payload instanceof Long) {
            current.setLong(PAYLOAD, (Long) payload);
        } else if (payload instanceof Boolean) {
            current.setBool(PAYLOAD, (Boolean) payload);
        } else if (payload instanceof Double) {
            current.setDouble(PAYLOAD, (Double) payload);
        } else if (payload instanceof byte[]) {
            current.setData(PAYLOAD, (byte[]) payload);
        }
    }

    private void addChildrenCursors(Cursor current, TraceNode node) {
        Iterator<TraceNode> it = node.children().iterator();
        if (it.hasNext()) {
            Cursor childrenArray = current.setArray(CHILDREN);
            while (it.hasNext()) {
                cursors.push(childrenArray.addObject());
                it.next();
            }
        }
    }
}