aboutsummaryrefslogtreecommitdiffstats
path: root/clustercontroller-utils/src/main/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResult.java
blob: f62c97696ba8df5de1b5f20e0ec72d14b87c7673 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.http;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonHttpResult extends HttpResult {

    private static final ObjectMapper mapper = new ObjectMapper();

    private JsonNode json;
    private boolean failedParsing = false;


    public JsonHttpResult() {
        addHeader("Content-Type", "application/json");
    }

    public JsonHttpResult(HttpResult other) {
        super(other);

        if (other.getContent() == null) {
            setParsedJson(new ObjectNode(mapper.getNodeFactory()));
            return;
        }
        try{
            if (other.getContent() instanceof JsonNode jsonContent) {
                setParsedJson(jsonContent);
            } else {
                setParsedJson(mapper.readTree(other.getContent().toString()));
            }
        }
        catch (JsonProcessingException e) {
            failedParsing = true;
            setParsedJson(createErrorJson(e.getMessage(), other));
        }
    }

    private JsonNode createErrorJson(String error, HttpResult other) {
        ObjectNode root = new ObjectNode(mapper.getNodeFactory());
        root.put("error", "Invalid JSON in output: " + error);
        root.put("output", other.getContent().toString());
        return root;
    }

    public JsonHttpResult setJson(JsonNode o) {
        setContent(o);
        json = o;
        return this;
    }

    private void setParsedJson(JsonNode o) {
        json = o;
    }

    public JsonNode getJson() {
        return json;
    }

    @Override
    public void printContent(StringBuilder sb) {
        if (failedParsing || json == null) {
            super.printContent(sb);
        }
        else {
            sb.append("JSON: ");
            sb.append(json.toPrettyString());
        }
    }

}