aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/processing/rendering/ProcessingRenderer.java
blob: d6cf50aa5638e8e2545af2b737c7d8b569007423 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.processing.rendering;

import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.handler.ResponseHeaders;
import com.yahoo.processing.handler.ResponseStatus;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.processing.response.Data;
import com.yahoo.processing.response.DataList;
import com.yahoo.text.JSONWriter;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.IdentityHashMap;
import java.util.Map;

/**
 * The default renderer for processing responses. Renders a response in JSON.
 * This can be overridden to specify particular rendering of leaf Data elements.
 * This default implementation renders the toString of each element.
 *
 * @author bratseth
 */
public class ProcessingRenderer extends AsynchronousSectionedRenderer<Response> {

    private Map<Request,Request> renderedRequests = new IdentityHashMap<>();

    private JSONWriter jsonWriter;

    /** The current nesting level */
    private int level;

    @Override
    public void init() {
        super.init();
        level = 0;
    }

    @Override
    public final void beginResponse(OutputStream stream) throws IOException {
        jsonWriter = new JSONWriter(stream);
    }

    @Override
    public final void endResponse() throws IOException {
    }

    @Override
    public final void beginList(DataList<?> list) throws IOException {
        if (level>0)
            jsonWriter.beginArrayValue();

        jsonWriter.beginObject();

        if (level==0)
            renderTrace();

        if ( ! list.request().errors().isEmpty() && ! rendered(list.request())) {
            jsonWriter.beginField("errors");
            jsonWriter.beginArray();
            for (ErrorMessage error : list.request().errors()) {
                if (renderedRequests == null)
                    renderedRequests = new IdentityHashMap<>();
                renderedRequests.put(list.request(),list.request());
                jsonWriter.beginArrayValue();
                if (error.getCause() != null) { // render object
                    jsonWriter.beginObject();
                    jsonWriter.beginField("error").value(error.toString()).endField();
                    jsonWriter.beginField("stacktrace").value(stackTraceAsString(error.getCause())).endField();
                    jsonWriter.endObject();
                }
                else { // render string
                    jsonWriter.value(error.toString());
                }
                jsonWriter.endArrayValue();
            }
            jsonWriter.endArray();
            jsonWriter.endField();
        }

        jsonWriter.beginField("datalist");
        jsonWriter.beginArray();
        level++;
    }

    private String stackTraceAsString(Throwable e) {
        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        return writer.toString();
    }

    private boolean rendered(Request request) {
        return renderedRequests != null && renderedRequests.containsKey(request);
    }

    @Override
    public final void endList(DataList<?> list) throws IOException {
        jsonWriter.endArray();
        jsonWriter.endField();
        jsonWriter.endObject();
        if (level>0)
            jsonWriter.endArrayValue();
        level--;
    }

    @Override
    public final void data(Data data) throws IOException {
        if (! shouldRender(data)) return;
        jsonWriter.beginArrayValue();
        jsonWriter.beginObject();
        jsonWriter.beginField("data");
        renderValue(data,jsonWriter);
        jsonWriter.endField();
        jsonWriter.endObject();
        jsonWriter.endArrayValue();
    }

    /**
     * Renders the value of a data element.
     * This default implementation does writer.fieldValue(data.toString())
     * Override this to render data in application specific ways.
     */
    protected void renderValue(Data data,JSONWriter writer) throws IOException {
        writer.value(data.toString());
    }

    /**
     * Returns whether this data element should be rendered.
     * This can be overridden to add new kinds of data which should not be rendered.
     * This default implementation returns true unless the data is instanceof ResponseHeaders.
     *
     * @return true to render it, false to skip completely
     */
    protected boolean shouldRender(Data data) {
        if (data instanceof ResponseHeaders) return false;
        if (data instanceof ResponseStatus) return false;
        return true;
    }

    @Override
    public final String getEncoding() {
        return null;
    }

    @Override
    public final String getMimeType() {
        return "application/json";
    }

    private boolean renderTrace() throws IOException {
        if (getExecution().trace().getTraceLevel() == 0) return false;

        jsonWriter.beginField("trace");
        try {
            getExecution().trace().traceNode().accept(new TraceRenderingVisitor(jsonWriter));
        } catch (WrappedIOException e) {
            throw e.getCause();
        }
        jsonWriter.endField();
        return true;
    }

    private static class TraceRenderingVisitor extends TraceVisitor {

        private final JSONWriter jsonWriter;

        public TraceRenderingVisitor(JSONWriter jsonWriter) {
            this.jsonWriter = jsonWriter;
        }

        @Override
        public void entering(TraceNode node) {
            try {
                jsonWriter.beginArray();
            }
            catch (IOException e) {
                throw new WrappedIOException(e);
            }
        }

        @Override
        public void leaving(TraceNode node) {
            try {
                jsonWriter.endArray();
            }
            catch (IOException e) {
                throw new WrappedIOException(e);
            }
        }

        @Override
        public void visit(TraceNode node) {
            if ( ! (node.payload() instanceof String)) return; // skip other info than trace messages
            try {
                jsonWriter.beginArrayValue();
                if (node.timestamp() != 0) { // render object
                    jsonWriter.beginObject();
                    jsonWriter.beginField("timestamp").value(node.timestamp()).endField();
                    jsonWriter.beginField("message").value(node.payload().toString()).endField();
                    jsonWriter.endObject();
                }
                else { // render string
                    jsonWriter.value(node.payload().toString());
                }
                jsonWriter.endArrayValue();
            }
            catch (IOException e) {
                throw new WrappedIOException(e);
            }
        }

    }

    private static class WrappedIOException extends RuntimeException {
        private WrappedIOException(IOException cause) {
            super(cause);
        }

        @Override
        public IOException getCause() {
            return (IOException) super.getCause();
        }
    }

}