    001// Licensed to the Apache Software Foundation (ASF) under one
    002// or more contributor license agreements.  See the NOTICE file
    003// distributed with this work for additional information
    004// regarding copyright ownership.  The ASF licenses this file
    005// to you under the Apache License, Version 2.0 (the
    006// "License"); you may not use this file except in compliance
    007// with the License.  You may obtain a copy of the License at
    008//
    009// http://www.apache.org/licenses/LICENSE-2.0
    010//
    011// Unless required by applicable law or agreed to in writing,
    012// software distributed under the License is distributed on an
    013// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    014// KIND, either express or implied.  See the License for the
    015// specific language governing permissions and limitations
    016// under the License.
    017package org.apache.tapestry5.rest.jackson.internal;
    018
    019import java.lang.reflect.Method;
    020import java.lang.reflect.Parameter;
    021import java.util.Set;
    022
    023import org.apache.tapestry5.json.JSONObject;
    024import org.apache.tapestry5.services.rest.MappedEntityManager;
    025import org.apache.tapestry5.services.rest.OpenApiTypeDescriber;
    026
    027import com.github.victools.jsonschema.generator.SchemaGenerator;
    028
    029/**
    030 * {@link OpenApiTypeDescriber} implementation using
    031 * <a href="https://victools.github.io/jsonschema-generator/#introduction">Java JSONSchema Generator</a>,
    032 * by default generating JSON Schema 2019-09.
    033 */
    034public class JacksonOpenApiTypeDescriber implements OpenApiTypeDescriber
    035{
    036
    037    final private SchemaGenerator schemaGenerator;
    038    final Set<Class<?>> entities;
    039    public JacksonOpenApiTypeDescriber(SchemaGenerator schemaGenerator, MappedEntityManager mappedEntityManager) {
    040        super();
    041        this.schemaGenerator = schemaGenerator;
    042        entities = mappedEntityManager.getEntities();
    043    }
    044
    045    @Override
    046    public void describe(JSONObject description, Parameter parameter)
    047    {
    048    }
    049
    050    @Override
    051    public void describeReturnType(JSONObject description, Method method)
    052    {
    053    }
    054
    055    @Override
    056    public void describeSchema(Class<?> entity, JSONObject schemas)
    057    {
    058        if (entities.contains(entity))
    059        {
    060            final JSONObject schema = new JSONObject(
    061                    schemaGenerator.generateSchema(entity).toString());
    062            schema.remove("$schema");
    063            schemas.put(getSchemaName(entity), schema);
    064        }
    065    }
    066
    067    private String getSchemaName(final Class<?> returnType) {
    068        return returnType.getSimpleName();
    069    }
    070
    071}