com.zuunr.openapi.OpenApiSchemaConverter Maven / Gradle / Ivy
/*
* Copyright 2020 Zuunr AB
*
* 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.zuunr.openapi;
import com.zuunr.json.JsonObject;
import com.zuunr.json.JsonObjectBuilder;
import com.zuunr.json.JsonValue;
import java.util.Iterator;
/**
* @author Niklas Eldberger
*/
public class OpenApiSchemaConverter {
public JsonValue toJsonSchema(JsonObject openApiSchema) {
JsonObject jsonSchema = openApiSchema;
JsonObjectBuilder propertiesBuilder = JsonObject.EMPTY.builder();
JsonObject properties = openApiSchema.get("properties", JsonValue.NULL).getValue(JsonObject.class);
if (properties != null) {
Iterator valuesIter = properties.values().iterator();
for (JsonValue key : properties.keys()) {
propertiesBuilder.put(key.getString(), toJsonSchema(valuesIter.next().getValue(JsonObject.class)));
}
jsonSchema = jsonSchema.put("properties", properties);
}
jsonSchema = exclusiveMaximum(openApiSchema, jsonSchema);
jsonSchema = exclusiveMinimum(openApiSchema, jsonSchema);
return jsonSchema.jsonValue();
}
private JsonObject exclusiveMaximum(JsonObject openApiSchema, JsonObject jsonSchema) {
JsonValue exclusiveMaximum = openApiSchema.get("exclusiveMaximum");
if (exclusiveMaximum != null && exclusiveMaximum.is(Boolean.class) && exclusiveMaximum.getValue(Boolean.class)) {
JsonValue maximum = openApiSchema.get("maximum");
if (maximum == null) {
throw new OpenApiConversionException("maximum must not be null");
}
jsonSchema = jsonSchema.put("exclusiveMaximum", maximum);
jsonSchema = jsonSchema.remove("maximum");
}
return jsonSchema;
}
private JsonObject exclusiveMinimum(JsonObject openApiSchema, JsonObject jsonSchema) {
JsonValue exclusiveMinimum = openApiSchema.get("exclusiveMinimum");
if (exclusiveMinimum != null && exclusiveMinimum.is(Boolean.class) && exclusiveMinimum.getValue(Boolean.class)) {
JsonValue minimum = openApiSchema.get("minimum");
if (minimum == null) {
throw new OpenApiConversionException("minimum must not be null");
}
jsonSchema = jsonSchema.put("exclusiveMinimum", minimum);
jsonSchema = jsonSchema.remove("minimum");
}
return jsonSchema;
}
}