summaryrefslogtreecommitdiff
path: root/src/main/java/com/networknt/schema/EnumValidator.java
blob: 582666db20a3f0598db6b350147faa9cc49566e5 (plain)
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
/*
 * Copyright (c) 2016 Network New Technologies Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.networknt.schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.DecimalNode;
import com.fasterxml.jackson.databind.node.NullNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * {@link JsonValidator} for enum.
 */
public class EnumValidator extends BaseJsonValidator implements JsonValidator {
    private static final Logger logger = LoggerFactory.getLogger(EnumValidator.class);

    private final Set<JsonNode> nodes;
    private final String error;

    public EnumValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
        super(schemaLocation, evaluationPath, schemaNode, parentSchema, ValidatorTypeCode.ENUM, validationContext);
        if (schemaNode != null && schemaNode.isArray()) {
            nodes = new HashSet<JsonNode>();
            StringBuilder sb = new StringBuilder();

            sb.append('[');
            String separator = "";

            for (JsonNode n : schemaNode) {
                if (n.isNumber()) {
                    // convert to DecimalNode for number comparison
                    nodes.add(processNumberNode(n));
                } else if (n.isArray()) {
                    ArrayNode a = processArrayNode((ArrayNode) n);
                    nodes.add(a);
                } else {
                    nodes.add(n);
                }

                sb.append(separator);
                sb.append(n.asText());
                separator = ", ";
            }

            // check if the parent schema declares the fields as nullable
            if (validationContext.getConfig().isHandleNullableField()) {
                JsonNode nullable = parentSchema.getSchemaNode().get("nullable");
                if (nullable != null && nullable.asBoolean()) {
                    nodes.add(NullNode.getInstance());
                    separator = ", ";
                    sb.append(separator);
                    sb.append("null");
                }
            }
            sb.append(']');

            error = sb.toString();
        } else {
            nodes = Collections.emptySet();
            error = "[none]";
        }
    }

    public Set<ValidationMessage> validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) {
        debug(logger, node, rootNode, instanceLocation);

        if (node.isNumber()) {
            node = processNumberNode(node);
        } else if (node.isArray()) {
            node = processArrayNode((ArrayNode) node);
        }
        if (!nodes.contains(node) && !( this.validationContext.getConfig().isTypeLoose() && isTypeLooseContainsInEnum(node))) {
            return Collections.singleton(message().instanceNode(node).instanceLocation(instanceLocation)
                    .locale(executionContext.getExecutionConfig().getLocale())
                    .failFast(executionContext.isFailFast()).arguments(error).build());
        }

        return Collections.emptySet();
    }

    /**
     * Check whether enum contains the value of the JsonNode if the typeLoose is enabled.
     *
     * @param node JsonNode to check
     */
    private boolean isTypeLooseContainsInEnum(JsonNode node) {
        if (TypeFactory.getValueNodeType(node, this.validationContext.getConfig()) == JsonType.STRING) {
            String nodeText = node.textValue();
            for (JsonNode n : nodes) {
                String value = n.asText();
                if (value != null && value.equals(nodeText)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Processes the number and ensures trailing zeros are stripped.
     * 
     * @param n the node
     * @return the node
     */
    protected JsonNode processNumberNode(JsonNode n) {
        return DecimalNode.valueOf(new BigDecimal(n.decimalValue().toPlainString()));
    }

    /**
     * Processes the array and ensures that numbers within have trailing zeroes stripped.
     * 
     * @param node the node
     * @return the node
     */
    protected ArrayNode processArrayNode(ArrayNode node) {
        if (!hasNumber(node)) {
            return node;
        }
        ArrayNode a = (ArrayNode) node.deepCopy();
        for (int x = 0; x < a.size(); x++) {
            JsonNode v = a.get(x);
            if (v.isNumber()) {
                v = processNumberNode(v);
                a.set(x, v);
            }
        }
        return a;
    }

    /**
     * Determines if the array node contains a number.
     * 
     * @param node the node
     * @return the node
     */
    protected boolean hasNumber(ArrayNode node) {
        for (int x = 0; x < node.size(); x++) {
            JsonNode v = node.get(x);
            if (v.isNumber()) {
                return true;
            }
        }
        return false;
    }
}