Java Code Examples for io.swagger.models.Swagger#setInfo()

The following examples show how to use io.swagger.models.Swagger#setInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SwaggerHandlerImplTest.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
private void init() {
  mockMap.put("xxxx", apiListing);
  mockDoc = new Documentation("xx", "/xx", null, mockMap,
      null, Collections.emptySet(), Collections.emptySet(), null, Collections.emptySet(), Collections.emptyList());
  mockSwagger = new Swagger();
  mockSwagger.setInfo(new Info());
  Map<String, Model> defMap = new HashMap<>();
  defMap.put("xx", new ModelImpl());
  mockSwagger.setDefinitions(defMap);
  Map<String, Path> pathMap = new HashMap<>();
  pathMap.put("xx", new Path());
  mockSwagger.setPaths(pathMap);
  new Expectations() {
    {
      documentationCache.documentationByGroup(anyString);
      result = mockDoc;

      DefinitionCache.getClassNameBySchema(anyString);
      result = "app";

      mapper.mapDocumentation((Documentation) any);
      result = mockSwagger;
    }
  };
}
 
Example 2
Source File: SwaggerService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
public Swagger exportApiToSwaggerJSON(Api api) {
    Swagger swagger = new Swagger();

    swagger.setSwagger("2.0");
    swagger.setBasePath(api.getBasePath());

    swagger.setInfo(getInfoByApi(api));
    Optional<Environment> optionalEnvironment = api.getEnvironments().stream().findFirst();
    optionalEnvironment.ifPresent(environment -> swagger.setHost(environment.getInboundURL()));
    swagger.setTags(getTagsByApi(api));
    swagger.setPaths(getPathsByApi(api));
    swagger.setDefinitions(new HashMap<>());
    swagger.setConsumes(new ArrayList<>());

    return swagger;
}
 
Example 3
Source File: SpringTimeSwaggerDocsController.java    From springtime with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	swagger = new Swagger();
	Info info = new Info();
	info.setTitle("GreetingService");
	swagger.setInfo(info);

	Map<String, Object> beans = applicationContext.getBeansWithAnnotation(SpringTimeService.class);
	Set<Class<?>> classes = new HashSet<Class<?>>();
	for (Object bean : beans.values()) {
		classes.add(bean.getClass());
	}

	Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(null));
	swagger = reader.read(classes);
}
 
Example 4
Source File: Java2SwaggerMojo.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void configureSwagger() {
    swagger = new Swagger();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    Info info = new Info();
    Contact swaggerContact = new Contact();
    License swaggerLicense = new License();
    swaggerLicense.name(this.license)
        .url(this.licenseUrl);
    swaggerContact.name(this.contact);
    info.version(this.version)
        .description(this.description)
        .contact(swaggerContact)
        .license(swaggerLicense)
        .title(this.title);
    swagger.setInfo(info);
    if (this.schemes != null) {
        for (String scheme : this.schemes) {
            swagger.scheme(Scheme.forValue(scheme));
        }
    }
    swagger.setHost(this.host);
    swagger.setBasePath(this.basePath);
}
 
Example 5
Source File: SwaggerUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This method will create the info section of the swagger document.
 *
 * @param dataServiceName name of the data-service.
 * @param transports      enabled transports.
 * @param serverConfig    Server config object.
 * @param swaggerDoc      Swagger document object.
 * @throws AxisFault Exception occured while getting the host address from transports.
 */
private static void addSwaggerInfoSection(String dataServiceName, List<String> transports,
                                          MIServerConfig serverConfig, Swagger swaggerDoc) throws AxisFault {

    swaggerDoc.basePath("/" + SwaggerProcessorConstants.SERVICES_PREFIX + "/" + dataServiceName);

    if (transports.contains("https")) {
        swaggerDoc.addScheme(Scheme.HTTPS);
        swaggerDoc.addScheme(Scheme.HTTP);
        swaggerDoc.setHost(serverConfig.getHost("https"));
    } else {
        swaggerDoc.addScheme(Scheme.HTTP);
        swaggerDoc.setHost(serverConfig.getHost("http"));
    }

    Info info = new Info();
    info.title(dataServiceName);
    info.setVersion("1.0");
    info.description("API Definition of dataservice : " + dataServiceName);
    swaggerDoc.setInfo(info);

    swaggerDoc.addConsumes("application/json");
    swaggerDoc.addConsumes("application/xml");

    swaggerDoc.addProduces("application/json");
    swaggerDoc.addProduces("application/xml");
}
 
Example 6
Source File: OpenAPIV2Generator.java    From spring-openapi with MIT License 5 votes vote down vote up
public Swagger generate(OpenApiV2GeneratorConfig config) {
	logger.info("Starting OpenAPI v2 generation");
	environment = config.getEnvironment();
	Swagger openAPI = new Swagger();
	openAPI.setDefinitions(createDefinitions());
	openAPI.setPaths(createPaths(config));
	openAPI.setInfo(info);
	openAPI.setBasePath(config.getBasePath());
	openAPI.setHost(config.getHost());
	logger.info("OpenAPI v2 generation done!");
	return openAPI;
}
 
Example 7
Source File: UpdateManager.java    From cellery-distribution with Apache License 2.0 5 votes vote down vote up
/**
 * Creates Swagger file for the API given by controller
 *
 * @param api API sent by controller
 */
private static void createSwagger(API api) {
    Swagger swagger = new Swagger();
    swagger.setInfo(createSwaggerInfo(api));
    swagger.basePath("/" + api.getContext());
    swagger.setPaths(createAPIResources(api));
    String swaggerString = Json.pretty(swagger);
    writeSwagger(swaggerString, removeSpecialChars(api.getBackend() + api.getContext()));
}
 
Example 8
Source File: GenerateService.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public String generate(String protocol) {
    if (protocol == null) {
        protocol = defaultProtocol;
    }
    Swagger swagger = new Swagger();

    swagger.setInfo(getInfo());
    swagger.setBasePath(basePath);

    Map<Class<?>, Object> interfaceMapRef = new HashMap<>();
    List<ProviderBootstrap> providerBootstraps = RpcRuntimeContext.getProviderConfigs();
    for (ProviderBootstrap providerBootstrap : providerBootstraps) {
        ProviderConfig providerConfig = providerBootstrap.getProviderConfig();
        List<ServerConfig> server = providerConfig.getServer();
        for (ServerConfig serverConfig : server) {
            if (serverConfig.getProtocol().equals(protocol)) {
                interfaceMapRef.put(providerConfig.getProxyClass(), providerConfig.getRef());
                break;
            }
        }
    }

    Reader.read(swagger, interfaceMapRef, "");
    String result = null;
    try {
        result = Json.mapper().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    return result;
}
 
Example 9
Source File: JbootSwaggerManager.java    From jboot with Apache License 2.0 5 votes vote down vote up
public void init() {
    if (!config.isConfigOk()) {
        return;
    }

    swagger = new Swagger();
    swagger.setHost(config.getHost());
    swagger.setBasePath("/");
    swagger.addScheme(HTTP);
    swagger.addScheme(HTTPS);


    Info swaggerInfo = new Info();
    swaggerInfo.setDescription(config.getDescription());
    swaggerInfo.setVersion(config.getVersion());
    swaggerInfo.setTitle(config.getTitle());
    swaggerInfo.setTermsOfService(config.getTermsOfService());

    Contact contact = new Contact();
    contact.setName(config.getContactName());
    contact.setEmail(config.getContactEmail());
    contact.setUrl(config.getContactUrl());
    swaggerInfo.setContact(contact);

    License license = new License();
    license.setName(config.getLicenseName());
    license.setUrl(config.getLicenseUrl());
    swaggerInfo.setLicense(license);


    swagger.setInfo(swaggerInfo);

    List<Class> classes = ClassScanner.scanClassByAnnotation(RequestMapping.class, false);

    Reader.read(swagger, classes);

}
 
Example 10
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method generates API definition to the given api
 *
 * @param swaggerData api
 * @return API definition in string format
 * @throws APIManagementException
 */
@Override
public String generateAPIDefinition(SwaggerData swaggerData) throws APIManagementException {
    Swagger swagger = new Swagger();

    //Create info object
    Info info = new Info();
    info.setTitle(swaggerData.getTitle());
    if (swaggerData.getDescription() != null) {
        info.setDescription(swaggerData.getDescription());
    }

    Contact contact = new Contact();
    //Create contact object and map business owner info
    if (swaggerData.getContactName() != null) {
        contact.setName(swaggerData.getContactName());
    }
    if (swaggerData.getContactEmail() != null) {
        contact.setEmail(swaggerData.getContactEmail());
    }
    if (swaggerData.getContactName() != null || swaggerData.getContactEmail() != null) {
        //put contact object to info object
        info.setContact(contact);
    }

    info.setVersion(swaggerData.getVersion());
    swagger.setInfo(info);
    updateSwaggerSecurityDefinition(swagger, swaggerData, "https://test.com");
    updateLegacyScopesFromSwagger(swagger, swaggerData);
    for (SwaggerData.Resource resource : swaggerData.getResources()) {
        addOrUpdatePathToSwagger(swagger, resource);
    }

    return getSwaggerJsonString(swagger);
}
 
Example 11
Source File: AbstractDocumentSource.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public AbstractDocumentSource(Log log, ApiSource apiSource, String encoding) throws MojoFailureException {
    LOG = log;
    this.outputPath = apiSource.getOutputPath();
    this.templatePath = apiSource.getTemplatePath();
    this.swaggerPath = apiSource.getSwaggerDirectory();
    this.modelSubstitute = apiSource.getModelSubstitute();
    this.jsonExampleValues = apiSource.isJsonExampleValues();

    swagger = new Swagger();
    if (apiSource.getSchemes() != null) {
        for (String scheme : apiSource.getSchemes()) {
            swagger.scheme(Scheme.forValue(scheme));
        }
    }

    // read description from file
    if (apiSource.getDescriptionFile() != null) {
        InputStream is = null;
        try {
            is = new FileInputStream(apiSource.getDescriptionFile());
            apiSource.getInfo().setDescription(IOUtils.toString(is));
        } catch (IOException e) {
            throw new MojoFailureException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    swagger.setHost(apiSource.getHost());
    swagger.setInfo(apiSource.getInfo());
    swagger.setBasePath(apiSource.getBasePath());
    swagger.setExternalDocs(apiSource.getExternalDocs());

    this.apiSource = apiSource;
    if (encoding != null) {
        this.encoding = encoding;
    }
}
 
Example 12
Source File: SwaggerFactory.java    From dorado with Apache License 2.0 4 votes vote down vote up
public static Swagger getSwagger() {
	if (!swaggerEnable)
		return new Swagger();

	if (swagger != null)
		return swagger;

	Reader reader = new Reader(new Swagger());

	String[] packages = null;
	Class<?> mainClass = Dorado.mainClass;
	EnableSwagger enableSwagger = mainClass.getAnnotation(EnableSwagger.class);

	if (enableSwagger != null) {
		packages = enableSwagger.value();
	}

	if (packages == null || packages.length == 0) {
		packages = Dorado.serverConfig.scanPackages();
	}

	if (packages == null || packages.length == 0) {
		packages = new String[] { mainClass.getPackage().getName() };
	}

	if (packages == null || packages.length == 0) {
		throw new IllegalArgumentException("缺少scanPackages设置");
	}

	Set<Class<?>> classes = new HashSet<>();
	for (String pkg : packages) {
		try {
			classes.addAll(PackageScanner.scan(pkg));
		} catch (Exception ex) {
			// ignore this ex
		}
	}

	Swagger _swagger = reader.read(classes);
	_swagger.setSchemes(Arrays.asList(Scheme.HTTP, Scheme.HTTPS));

	ApiKey apiKey = apiContext.getApiKey();
	if (apiKey != null) {
		ApiKeyAuthDefinition apiKeyAuth = new ApiKeyAuthDefinition(apiKey.getName(),
				In.forValue(apiKey.getIn() == null ? "header" : apiKey.getIn()));
		_swagger.securityDefinition("auth", apiKeyAuth);

		List<SecurityRequirement> securityRequirements = new ArrayList<>();
		SecurityRequirement sr = new SecurityRequirement();
		sr.requirement("auth");
		securityRequirements.add(sr);
		_swagger.setSecurity(securityRequirements);
	}
	if (apiContext.getInfo() != null)
		_swagger.setInfo(apiContext.getInfo());

	swagger = _swagger;
	return _swagger;
}
 
Example 13
Source File: SwaggerGenMojo.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a new Swagger metadata.
 *
 * @return the Swagger metadata.
 * @throws MojoExecutionException if any problems were encountered.
 */
private Swagger getSwagger() throws MojoExecutionException
{
    getLog().debug("Creating Swagger Metadata");
    // Set up initial Swagger metadata.
    Swagger swagger = new Swagger();
    swagger.setInfo(new Info().title(title).version(version));
    swagger.setBasePath(basePath);

    // Set the schemes.
    if (!CollectionUtils.isEmpty(schemeParameters))
    {
        List<Scheme> schemes = new ArrayList<>();
        for (String schemeParameter : schemeParameters)
        {
            Scheme scheme = Scheme.forValue(schemeParameter);
            if (scheme == null)
            {
                throw new MojoExecutionException("Invalid scheme specified: " + schemeParameter);
            }
            schemes.add(scheme);
        }
        swagger.setSchemes(schemes);
    }

    // Add authorization support if specified.
    if (authType != null)
    {
        // Find the definition for the user specified type.
        SecuritySchemeDefinition securitySchemeDefinition = null;
        for (SecuritySchemeDefinition possibleDefinition : SECURITY_SCHEME_DEFINITIONS)
        {
            if (possibleDefinition.getType().equalsIgnoreCase(authType))
            {
                securitySchemeDefinition = possibleDefinition;
                break;
            }
        }

        // If we found a match, set it on the swagger object.
        if (securitySchemeDefinition != null)
        {
            // Come up with an authentication name for easy identification (e.g. basicAuthentication, etc.).
            String securityName = securitySchemeDefinition.getType() + "Authentication";

            // Add the security definition.
            swagger.addSecurityDefinition(securityName, securitySchemeDefinition);

            // Add the security for everything based on the name of the definition.
            SecurityRequirement securityRequirement = new SecurityRequirement();
            securityRequirement.requirement(securityName);
            swagger.addSecurity(securityRequirement);
        }
    }

    // Use default paths and definitions.
    swagger.setPaths(new TreeMap<>());
    swagger.setDefinitions(new TreeMap<>());
    return swagger;
}