001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2016 ForgeRock AS.
015 */
016
017package org.forgerock.api.jackson;
018
019import static org.forgerock.api.jackson.JacksonUtils.OBJECT_MAPPER;
020import static org.forgerock.json.JsonValue.json;
021
022import java.io.IOException;
023import java.util.HashMap;
024import java.util.Iterator;
025import java.util.Map;
026import java.util.Set;
027import java.util.regex.Pattern;
028
029import javax.validation.ValidationException;
030
031import org.forgerock.api.enums.ReadPolicy;
032import org.forgerock.api.enums.WritePolicy;
033import org.forgerock.json.JsonValue;
034
035import com.fasterxml.jackson.annotation.JsonProperty;
036import com.fasterxml.jackson.databind.JavaType;
037import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
038import com.fasterxml.jackson.module.jsonSchema.types.ObjectSchema;
039
040/**
041 * An extension to the Jackson {@code ObjectSchema} that includes the custom CREST JSON Schema attributes.
042 */
043public class CrestObjectSchema extends ObjectSchema implements CrestReadWritePoliciesSchema, OrderedFieldSchema,
044        ValidatableSchema, RequiredFieldsSchema, WithExampleSchema<Map<String, Object>> {
045    private static final JavaType EXAMPLE_VALUE_TYPE = OBJECT_MAPPER.getTypeFactory()
046            .constructParametrizedType(HashMap.class, Map.class, String.class, Object.class);
047    private WritePolicy writePolicy;
048    private ReadPolicy readPolicy;
049    private Boolean errorOnWritePolicyFailure;
050    private Boolean returnOnDemand;
051    private Integer propertyOrder;
052    private Set<String> requiredFields;
053    private Map<String, Object> example;
054
055    @Override
056    public WritePolicy getWritePolicy() {
057        return writePolicy;
058    }
059
060    @Override
061    public void setWritePolicy(WritePolicy policy) {
062        this.writePolicy = policy;
063    }
064
065    @Override
066    public ReadPolicy getReadPolicy() {
067        return readPolicy;
068    }
069
070    @Override
071    public void setReadPolicy(ReadPolicy readPolicy) {
072        this.readPolicy = readPolicy;
073    }
074
075    @Override
076    public Boolean getErrorOnWritePolicyFailure() {
077        return errorOnWritePolicyFailure;
078    }
079
080    @Override
081    public void setErrorOnWritePolicyFailure(Boolean errorOnWritePolicyFailure) {
082        this.errorOnWritePolicyFailure = errorOnWritePolicyFailure;
083    }
084
085    @Override
086    public Boolean getReturnOnDemand() {
087        return returnOnDemand;
088    }
089
090    @Override
091    public void setReturnOnDemand(Boolean returnOnDemand) {
092        this.returnOnDemand = returnOnDemand;
093    }
094
095    @Override
096    public Integer getPropertyOrder() {
097        return propertyOrder;
098    }
099
100    @Override
101    public void setPropertyOrder(Integer order) {
102        this.propertyOrder = order;
103    }
104
105    @Override
106    public void validate(JsonValue object) throws ValidationException {
107        if (!object.isMap()) {
108            throw new ValidationException("Object expected, but got: " + object.getObject());
109        }
110        Map<String, Object> propertyValues = new HashMap<>((Map<String, Object>) object.getObject());
111        Iterator<Map.Entry<String, Object>> propertyIterator = propertyValues.entrySet().iterator();
112        Map<Pattern, JsonSchema> patternProperties = new HashMap<>();
113        if (getPatternProperties() != null) {
114            for (Map.Entry<String, JsonSchema> pattern : getPatternProperties().entrySet()) {
115                patternProperties.put(Pattern.compile(pattern.getKey()), pattern.getValue());
116            }
117        }
118        while (propertyIterator.hasNext()) {
119            Map.Entry<String, Object> property = propertyIterator.next();
120            boolean validated = false;
121            if (getProperties().containsKey(property.getKey())) {
122                final JsonSchema schema = getProperties().get(property.getKey());
123                if (schema instanceof ValidatableSchema && !"reference".equals(property.getKey())) {
124                    ((ValidatableSchema) schema).validate(json(property.getValue()));
125                }
126                validated = true;
127            }
128            for (Map.Entry<Pattern, JsonSchema> pattern : patternProperties.entrySet()) {
129                if (pattern.getKey().matcher(property.getKey()).matches()) {
130                    if (pattern.getValue() instanceof ValidatableSchema) {
131                        ((ValidatableSchema) pattern.getValue()).validate(json(property.getValue()));
132                    }
133                    validated = true;
134                }
135            }
136            if (validated) {
137                propertyIterator.remove();
138            }
139        }
140        AdditionalProperties additionalProperties = getAdditionalProperties();
141        if (additionalProperties != null) {
142            if (additionalProperties instanceof NoAdditionalProperties && !propertyValues.isEmpty()) {
143                throw new ValidationException("Did not expect additional properties, but got " + propertyValues);
144            }
145            SchemaAdditionalProperties schemaAdditionalProperties = (SchemaAdditionalProperties) additionalProperties;
146            if (schemaAdditionalProperties.getJsonSchema() instanceof ValidatableSchema) {
147                final ValidatableSchema schema = (ValidatableSchema) schemaAdditionalProperties.getJsonSchema();
148                for (Object value : propertyValues.values()) {
149                    schema.validate(json(value));
150                }
151            }
152        }
153    }
154
155    /**
156     * Gets read-only property. This method overrides the superclass' definition of "readOnly" being all lower-case,
157     * via the {@code JsonProperty} annotation.
158     *
159     * @return {@code true} if property is read-only, otherwise {@code false} or {@code null}
160     */
161    @JsonProperty("readOnly")
162    @Override
163    public Boolean getReadonly() {
164        return super.getReadonly();
165    }
166
167    // This method overrides the superclass' definition of "required" via JsonProperty annotation
168    @JsonProperty("required")
169    @Override
170    public Set<String> getRequiredFields() {
171        return requiredFields;
172    }
173
174    @Override
175    public void setRequiredFields(Set<String> requiredFields) {
176        this.requiredFields = requiredFields;
177    }
178
179    @Override
180    public Map<String, Object> getExample() {
181        Map<String, Object> example = this.example;
182        if (example == null) {
183            example = new HashMap<>();
184            for (Map.Entry<String, JsonSchema> property : getProperties().entrySet()) {
185                if (property.getValue() instanceof WithExampleSchema) {
186                    Object propertyExample = ((WithExampleSchema) property.getValue()).getExample();
187                    if (propertyExample != null) {
188                        example.put(property.getKey(), propertyExample);
189                    }
190                }
191            }
192            if (example.isEmpty()) {
193                example = null;
194            }
195        }
196        return example;
197    }
198
199    @Override
200    public void setExample(String example) throws IOException {
201        this.example = OBJECT_MAPPER.readValue(example, EXAMPLE_VALUE_TYPE);
202    }
203}