001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.isis.viewer.restfulobjects.rendering.service.swagger.internal; 020 021import javax.inject.Inject; 022import javax.inject.Named; 023 024import com.fasterxml.jackson.core.JsonProcessingException; 025 026import org.springframework.stereotype.Component; 027 028import org.apache.isis.applib.services.swagger.SwaggerService; 029import org.apache.isis.core.metamodel.specloader.SpecificationLoader; 030 031import io.swagger.models.Swagger; 032import io.swagger.util.Json; 033import io.swagger.util.Yaml; 034 035@Component 036@Named("isisMetaModel.SwaggerSpecGenerator") 037public class SwaggerSpecGenerator { 038 039 private final SpecificationLoader specificationLoader; 040 private final Tagger tagger; 041 private final ClassExcluder classExcluder; 042 private final ValuePropertyFactory valuePropertyFactory; 043 044 @Inject 045 public SwaggerSpecGenerator( 046 final SpecificationLoader specificationLoader, 047 final Tagger tagger, 048 final ClassExcluder classExcluder, 049 final ValuePropertyFactory valuePropertyFactory) { 050 this.specificationLoader = specificationLoader; 051 this.tagger = tagger; 052 this.classExcluder = classExcluder; 053 this.valuePropertyFactory = valuePropertyFactory; 054 } 055 056 public String generate( 057 final String basePath, 058 final SwaggerService.Visibility visibility, 059 final SwaggerService.Format format) { 060 061 final Generation generation = newGeneration(basePath, visibility); 062 final Swagger swagger = generation.generate(); 063 064 switch (format) { 065 case JSON: 066 return Json.pretty(swagger); 067 case YAML: 068 try { 069 return Yaml.pretty().writeValueAsString(swagger); 070 } catch (JsonProcessingException e) { 071 throw new RuntimeException(e); 072 } 073 default: 074 throw new IllegalArgumentException("Unrecognized format: " + format); 075 } 076 } 077 078 protected Generation newGeneration(final String basePath, final SwaggerService.Visibility visibility) { 079 return new Generation( 080 basePath, visibility, 081 specificationLoader, 082 tagger, 083 classExcluder, 084 valuePropertyFactory); 085 } 086 087}