io.swagger.models.Swagger Java Examples
The following examples show how to use
io.swagger.models.Swagger.
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: EntrypointsSwaggerV2Transformer.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public void transform(SwaggerV2Descriptor descriptor) { if (asBoolean(SwaggerProperties.ENTRYPOINTS_AS_SERVERS) && entrypoints != null && ! entrypoints.isEmpty()) { Swagger swagger = descriptor.getSpecification(); // Swagger vs2 supports only a single server ApiEntrypointEntity first = entrypoints.iterator().next(); URI target = URI.create(first.getTarget()); swagger.setSchemes(Collections.singletonList(Scheme.forValue(target.getScheme()))); swagger.setHost(target.getHost()); if (getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH) == null || getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH).isEmpty() || asBoolean(SwaggerProperties.ENTRYPOINT_AS_BASEPATH)) { swagger.setBasePath(target.getPath()); } } }
Example #2
Source File: SwaggerGenMojo.java From herd with Apache License 2.0 | 6 votes |
/** * Creates the YAML file in the output location based on the Swagger metadata. * * @param swagger the Swagger metadata. * * @throws MojoExecutionException if any error was encountered while writing the YAML information to the file. */ private void createYamlFile(Swagger swagger) throws MojoExecutionException { String yamlOutputLocation = outputDirectory + "/" + outputFilename; try { getLog().debug("Creating output YAML file \"" + yamlOutputLocation + "\""); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); objectMapper.setPropertyNamingStrategy(new SwaggerNamingStrategy()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.writeValue(new File(yamlOutputLocation), swagger); } catch (IOException e) { throw new MojoExecutionException("Error creating output YAML file \"" + yamlOutputLocation + "\". Reason: " + e.getMessage(), e); } }
Example #3
Source File: DataProviders.java From binder-swagger-java with BSD 2-Clause "Simplified" License | 6 votes |
protected DataProvider collectRefProperty(Swagger swagger, RefProperty schema, boolean clean) { Model model = swagger.getDefinitions() != null ? swagger.getDefinitions().get(schema.getSimpleRef()) : null; if (model == null) throw new IllegalArgumentException("CAN'T find model for " + schema.getSimpleRef()); if (model instanceof ArrayModel) { DataProvider itemProvider = collect(swagger, ((ArrayModel) model).getItems(), clean); return new ListDataProvider(itemProvider, schema.getSimpleRef()); } else if (model instanceof ModelImpl) { Map<String, DataProvider> fields = (model.getProperties() != null ? model.getProperties() : Collections.<String, Property>emptyMap()).entrySet().stream() .map(e -> entry(e.getKey(), collect(swagger, e.getValue(), clean))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return new ObjectDataProvider(fields, schema.getSimpleRef()); } throw new IllegalArgumentException("Unsupported model type: " + model.getClass()); }
Example #4
Source File: PlantUMLCodegen.java From swagger2puml with Apache License 2.0 | 6 votes |
/** * * @param swagger * @return */ private List<InterfaceDiagram> processSwaggerPaths(Swagger swagger) { LOGGER.entering(LOGGER.getName(), "processSwaggerPaths"); List<InterfaceDiagram> interfaceDiagrams = new ArrayList<InterfaceDiagram>(); Map<String, Path> paths = swagger.getPaths(); for (Map.Entry<String, Path> entry : paths.entrySet()) { Path pathObject = entry.getValue(); LOGGER.info("Processing Path --> " + entry.getKey()); List<Operation> operations = pathObject.getOperations(); String uri = entry.getKey(); for (Operation operation : operations) { interfaceDiagrams.add(getInterfaceDiagram(operation, uri)); } } LOGGER.exiting(LOGGER.getName(), "processSwaggerPaths"); return interfaceDiagrams; }
Example #5
Source File: DefinitionGeneratorTest.java From herd with Apache License 2.0 | 6 votes |
@Test public void test_3() throws Exception { Swagger swagger = new Swagger(); swagger.setDefinitions(new HashMap<>()); Set<String> exampleClassNames = new HashSet<>(); Set<Class<?>> modelClasses = new HashSet<>(Arrays.asList(WildcardParameterizedListCase.class)); try { new DefinitionGenerator(LOG, swagger, exampleClassNames, modelClasses, null); fail(); } catch (Exception e) { assertEquals(MojoExecutionException.class, e.getClass()); assertEquals("Field \"list\" has a parameterized type which is not a class.", e.getMessage()); } }
Example #6
Source File: TestJaxrsV1V1.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void should_mapper_consumer_multi_args_to_swagger_multi_args_with_diff_order() { SwaggerEnvironment environment = new SwaggerEnvironment(); Swagger swagger = SwaggerGenerator.generate(JaxrsAddV1.class); SwaggerConsumer swaggerConsumer = environment.createConsumer(ConsumerAddV1_diff_order.class, swagger); ArgumentsMapper mapper = swaggerConsumer.findOperation("add").getArgumentsMapper(); Map<String, Object> arguments = new HashMap<>(); arguments.put("x", 1); arguments.put("y", 2); SwaggerInvocation invocation = new SwaggerInvocation(); Map<String, Object> result = mapper.invocationArgumentToSwaggerArguments(invocation, arguments); Assert.assertEquals(2, result.size()); Assert.assertEquals(1, (int) result.get("x")); Assert.assertEquals(2, (int) result.get("y")); }
Example #7
Source File: SwaggerConverter.java From zap-extensions with Apache License 2.0 | 6 votes |
private OpenAPI getOpenAPI() throws SwaggerException { ParseOptions options = new ParseOptions(); options.setResolve(true); options.setResolveFully(true); OpenAPI openAPI = new OpenAPIV3Parser().readContents(this.defn, null, options).getOpenAPI(); if (openAPI == null) { // try v2 Swagger swagger = new SwaggerParser().parse(this.defn); if (swagger == null) { convertV1ToV2(); } // parse v2 openAPI = parseV2(options); } return openAPI; }
Example #8
Source File: TestJaxrsV2V1.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void add_addBody() { SwaggerEnvironment environment = new SwaggerEnvironment(); Swagger swagger = SwaggerGenerator.generate(JaxrsAddBodyV1.class); SwaggerConsumer swaggerConsumer = environment.createConsumer(ConsumerAddV2.class, swagger); ArgumentsMapper mapper = swaggerConsumer.findOperation("add").getArgumentsMapper(); Map<String, Object> arguments = new HashMap<>(); arguments.put("x", 1); arguments.put("y", 2); arguments.put("x-z", 3); SwaggerInvocation invocation = new SwaggerInvocation(); Map<String, Object> result = mapper.invocationArgumentToSwaggerArguments(invocation, arguments); Assert.assertEquals(1, result.size()); result = (Map<String, Object>) result.get("addBody"); Assert.assertEquals(2, result.size()); Assert.assertEquals(1, (int) result.get("x")); Assert.assertEquals(2, (int) result.get("y")); }
Example #9
Source File: TestSpringmvcV2V2.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void add_addBody() { SwaggerEnvironment environment = new SwaggerEnvironment(); Swagger swagger = SwaggerGenerator.generate(SpringmvcAddBodyV2.class); SwaggerConsumer swaggerConsumer = environment.createConsumer(ConsumerAddV2.class, swagger); ArgumentsMapper mapper = swaggerConsumer.findOperation("add").getArgumentsMapper(); Map<String, Object> arguments = new HashMap<>(); arguments.put("x", 1); arguments.put("y", 2); arguments.put("z", 3); SwaggerInvocation invocation = new SwaggerInvocation(); Map<String, Object> result = mapper.invocationArgumentToSwaggerArguments(invocation, arguments); Assert.assertEquals(1, result.size()); result = (Map<String, Object>) result.get("addBody"); Assert.assertEquals(3, result.size()); Assert.assertEquals(1, (int) result.get("x")); Assert.assertEquals(2, (int) result.get("y")); Assert.assertEquals(3, (int) result.get("x-z")); }
Example #10
Source File: SOAPOperationBindingTestCase.java From carbon-apimgt with Apache License 2.0 | 6 votes |
@Test public void testCompareGeneratedSwagger() throws Exception { String swaggerString = "{\n" + " \"swagger\": \"2.0\",\n" + " \"paths\": {\n" + " \"/getCustomer\": {\n" + " \"get\": {\n" + " \"operationId\": \"getCustomer\",\n" + " \"parameters\": [],\n" + " \"responses\": {\n" + " \"default\": {\n" + " \"description\": \"\",\n" + " \"schema\": {\n" + " \"$ref\": \"#/definitions/getCustomerOutput\"\n" + " }\n" + " }\n" + " },\n" + " \"x-wso2-soap\": {\n" + " \"soap-action\": \"getCustomer\",\n" + " \"soap-operation\": \"getCustomer\",\n" + " \"namespace\": \"http://service.jcombat.com/\"\n" + " }\n" + " }\n" + " }\n" + " },\n" + " \"info\": {\n" + " \"title\": \"\",\n" + " \"version\": \"\"\n" + " },\n" + " \"definitions\": {\n" + " \"getCustomerOutput\": {\n" + " \"type\": \"object\"\n" + " }\n" + " }\n" + "}"; String generatedSwagger = SOAPOperationBindingUtils.getSoapOperationMappingForUrl( Thread.currentThread().getContextClassLoader().getResource("wsdls/simpleCustomerService.wsdl") .toExternalForm()); Swagger swagger = new SwaggerParser().parse(generatedSwagger); Swagger actualSwagger = new SwaggerParser().parse(swaggerString); Assert.assertTrue(actualSwagger.getPaths().size() == swagger.getPaths().size()); Assert.assertTrue(actualSwagger.getDefinitions().size() == swagger.getDefinitions().size()); }
Example #11
Source File: CollapseTypes.java From yang2swagger with Eclipse Public License 1.0 | 6 votes |
@Override protected Map<String, String> prepareForReplacement(Swagger swagger) { Map<String, Set<String>> sameGroups = swagger.getDefinitions().entrySet().stream() .filter(e -> e.getValue() instanceof ComposedModel) .filter(e -> referenceOnly.test((ComposedModel) e.getValue())) .map(e -> new AbstractMap.SimpleEntry<>(toSignature.apply((ComposedModel) e.getValue()), e.getKey())) .collect(groupingBy(AbstractMap.SimpleEntry::getKey, mapping(AbstractMap.SimpleEntry::getValue, toSet()))); return sameGroups.values().stream() .filter(v -> v.size() > 1) .flatMap(v -> { final String type = v.stream().min(Comparator.comparingInt(String::length)).get(); return v.stream().filter(s -> !s.equals(type)).map(s -> new AbstractMap.SimpleEntry<>(s, type)); }).collect(toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); }
Example #12
Source File: OAS2Parser.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Retrieves the "Auth2" security scheme key * * @param swagger Swgger object * @return "Auth2" security scheme key */ private String getOAuth2SecuritySchemeKey(Swagger swagger) { final String oauth2Type = new OAuth2Definition().getType(); Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions(); boolean hasDefaultKey = false; boolean hasRESTAPIScopeKey = false; if (securityDefinitions != null) { for (Map.Entry<String, SecuritySchemeDefinition> definitionEntry : securityDefinitions.entrySet()) { if (oauth2Type.equals(definitionEntry.getValue().getType())) { //sets hasDefaultKey to true if at least once SWAGGER_APIM_DEFAULT_SECURITY becomes the key hasDefaultKey = hasDefaultKey || SWAGGER_APIM_DEFAULT_SECURITY.equals(definitionEntry.getKey()); //sets hasRESTAPIScopeKey to true if at least once SWAGGER_APIM_RESTAPI_SECURITY becomes the key hasRESTAPIScopeKey = hasRESTAPIScopeKey || SWAGGER_APIM_RESTAPI_SECURITY.equals(definitionEntry.getKey()); } } } if (hasDefaultKey) { return SWAGGER_APIM_DEFAULT_SECURITY; } else if (hasRESTAPIScopeKey) { return SWAGGER_APIM_RESTAPI_SECURITY; } else { return null; } }
Example #13
Source File: MicroserviceMeta.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
public SchemaMeta registerSchemaMeta(String schemaId, Swagger swagger) { SchemaMeta schemaMeta = new SchemaMeta(this, schemaId, swagger); if (schemaMetas.putIfAbsent(schemaMeta.getSchemaId(), schemaMeta) != null) { throw new IllegalStateException(String.format( "failed to register SchemaMeta caused by duplicated schemaId, appId=%s, microserviceName=%s, schemaId=%s.", appId, microserviceName, schemaMeta.getSchemaId())); } Class<?> intf = SwaggerUtils.getInterface(schemaMeta.getSwagger()); if (intf != null) { intfSchemaMetas .computeIfAbsent(intf, k -> Collections.synchronizedList(new ArrayList<>())) .add(schemaMeta); } schemaMeta.getOperations().values().stream() .forEach(operationMeta -> operationMetas.put(operationMeta.getMicroserviceQualifiedName(), operationMeta)); return schemaMeta; }
Example #14
Source File: ApexClientCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
@Override public void preprocessSwagger(Swagger swagger) { Info info = swagger.getInfo(); String calloutLabel = info.getTitle(); additionalProperties.put("calloutLabel", calloutLabel); String sanitized = sanitizeName(calloutLabel); additionalProperties.put("calloutName", sanitized); supportingFiles.add(new SupportingFile("namedCredential.mustache", srcPath + "/namedCredentials", sanitized + ".namedCredential" )); if (additionalProperties.get(BUILD_METHOD).equals("sfdx")) { generateSfdxSupportingFiles(); } else if (additionalProperties.get(BUILD_METHOD).equals("ant")) { generateAntSupportingFiles(); } }
Example #15
Source File: ContextMenuFactory.java From swurg with Apache License 2.0 | 6 votes |
@Override public List<JMenuItem> createMenuItems(IContextMenuInvocation invocation) { List<JMenuItem> jMenuItems = new ArrayList<>(); JMenuItem send_to_swagger_parser = new JMenuItem(String.format("Send to %s", EXTENSION)); send_to_swagger_parser.addActionListener(e -> { for (IHttpRequestResponse selectedMessage : invocation.getSelectedMessages()) { IRequestInfo requestInfo = this.callbacks.getHelpers().analyzeRequest(selectedMessage); String resource = requestInfo.getUrl().toString(); try { Swagger swagger = new Loader().process(resource); this.tab.populateTable(swagger); this.tab.printStatus(COPYRIGHT, Color.BLACK); } catch (IllegalArgumentException | NullPointerException e1) { this.tab.printStatus(e1.getMessage(), Color.RED); } } }); jMenuItems.add(send_to_swagger_parser); return jMenuItems; }
Example #16
Source File: ScopedProtobufSchemaManager.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
/** * get the ProtoMapper from Swagger */ public ProtoMapper getOrCreateProtoMapper(SchemaMeta schemaMeta) { return mapperCache.computeIfAbsent(schemaMeta.getSchemaId(), key -> { Swagger swagger = schemaMeta.getSwagger(); SwaggerToProtoGenerator generator = new SwaggerToProtoGenerator(schemaMeta.getMicroserviceQualifiedName(), swagger); Proto proto = generator.convert(); ProtoMapperFactory protoMapperFactory = new ProtoMapperFactory(); return protoMapperFactory.create(proto); }); }
Example #17
Source File: EndpointBuilder.java From api-compiler with Apache License 2.0 | 5 votes |
@Override public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) { VendorExtensionProtoConverter extensionConverter = new VendorExtensionProtoConverter(swagger.getVendorExtensions(), diagCollector); if (extensionConverter.hasExtension(ExtensionNames.ENDPOINTS_EXTENSION_NAME)) { serviceBuilder.addAllEndpoints( extensionConverter.convertExtensionToProtos( Endpoint.getDefaultInstance(), ExtensionNames.ENDPOINTS_EXTENSION_NAME)); validEndpointExtension(serviceBuilder, swagger.getHost()); } }
Example #18
Source File: ProtoApiFromOpenApi.java From api-compiler with Apache License 2.0 | 5 votes |
private boolean isDeprecated(Swagger swagger) { if (swagger.getVendorExtensions() != null && swagger.getVendorExtensions().containsKey(ExtensionNames.X_GOOGLE_DEPRECATED)) { return VendorExtensionUtils.getExtensionValue( swagger.getVendorExtensions(), Boolean.class, diagCollector, ExtensionNames.X_GOOGLE_DEPRECATED); } return false; }
Example #19
Source File: SwaggerLoader.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@VisibleForTesting public Swagger loadFromMemory(String appId, String shortName, String schemaId) { return Optional.ofNullable(apps.get(appId)) .map(microservices -> microservices.get(shortName)) .map(schemas -> schemas.get(schemaId)) .orElse(null); }
Example #20
Source File: DataProviders.java From binder-swagger-java with BSD 2-Clause "Simplified" License | 5 votes |
protected DataProvider collectByteProperty(Swagger swagger, Property schema, boolean clean) { if (schema instanceof ByteArrayProperty) return new ConstDataProvider("[ByteArray]"); else if (schema instanceof BinaryProperty) return new ConstDataProvider("[Binary]"); throw new IllegalArgumentException("Unsupported property type: " + schema.getClass()); }
Example #21
Source File: SwaggerGenerator.java From endpoints-java with Apache License 2.0 | 5 votes |
private Map<String, Model> getOrCreateDefinitionMap(Swagger swagger) { Map<String, Model> definitions = swagger.getDefinitions(); if (definitions == null) { definitions = new LinkedHashMap<>(); swagger.setDefinitions(definitions); } return definitions; }
Example #22
Source File: SwaggerGenerator.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void generateSwaggerJson() throws Exception { Set<Class<?>> classes = new HashSet<>(endpointConfig.getClasses()); classes.add(EnvironmentApi.class); Swagger swagger = new Reader(SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT).configure(new Swagger())) .read(classes); Path path = Paths.get("./build/swagger/environment.json"); Files.createDirectories(path.getParent()); Files.writeString(path, Json.pretty(swagger)); }
Example #23
Source File: SwaggerGenerator.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void generateSwaggerJson() throws Exception { Set<Class<?>> classes = new HashSet<>(endpointConfig.getClasses()); classes.add(SdxApi.class); Swagger swagger = new Reader(SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT).configure(new Swagger())) .read(classes); Path path = Paths.get("./build/swagger/datalake.json"); Files.createDirectories(path.getParent()); Files.writeString(path, Json.pretty(swagger)); }
Example #24
Source File: AnnotationUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
public static Property generateResponseHeaderProperty(Swagger swagger, ResponseHeaderConfig config) throws Error { Property property = generateResponseProperty(swagger, config); if (property == null) { throw new Error("invalid responseHeader, " + config); } return property; }
Example #25
Source File: JaxrsReaderTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
private void assertSwaggerPath(Operation expectedOperation, Swagger result, String expectedPath) { assertNotNull(result, "No Swagger object created"); assertFalse(result.getPaths().isEmpty(), "Should contain operation paths"); assertTrue(result.getPaths().containsKey(expectedPath), "Expected path missing"); io.swagger.models.Path path = result.getPaths().get(expectedPath); assertFalse(path.getOperations().isEmpty(), "Should be a get operation"); assertEquals(expectedOperation, path.getGet(), "Should contain operation"); }
Example #26
Source File: Knife4jController.java From yshopmall with Apache License 2.0 | 5 votes |
private void extend(Swagger swagger) { // 响应返回参数增强 for (Map.Entry<String, Model> entry : swagger.getDefinitions().entrySet()) { Model model = entry.getValue(); String key = entry.getKey(); if (key.contains("ApiResult") && !SwaggerUtil.getRealType(key).contains("ApiResult")) { Map<String, Property> props = model.getProperties(); Property dataProp = props.get("data"); Property newProp = SwaggerUtil.getNewProp(dataProp, SwaggerUtil.getRealType(key), swagger.getDefinitions()); props.put("data", newProp); } } }
Example #27
Source File: JaxrsReaderTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void createNewSwaggerInstanceIfNoneProvided() { JaxrsReader nullReader = new JaxrsReader(null, log); Tag expectedTag = new Tag(); expectedTag.name("atag"); Swagger result = nullReader.read(AnApi.class); assertSwaggerResponseContents(expectedTag, result); }
Example #28
Source File: JaxrsReaderTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void ignoreCommonParameters() { reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class)); Swagger result = reader.read(CommonParametersApiWithPathAnnotation.class); assertNull(result.getParameter("headerParam")); assertNull(result.getParameter("queryParam")); reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class)); result = reader.read(CommonParametersApiWithMethod.class); assertNull(result.getParameter("headerParam")); assertNull(result.getParameter("queryParam")); }
Example #29
Source File: QuotaBuilder.java From api-compiler with Apache License 2.0 | 5 votes |
@Override public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) { VendorExtensionProtoConverter extensionConverter = new VendorExtensionProtoConverter(swagger.getVendorExtensions(), diagCollector); if (extensionConverter.hasExtension(ExtensionNames.MANAGEMENT_SWAGGER_EXTENSION)) { ServiceManagementExtension serviceManagementExtension = readExtension(swagger); Quota quota = parseQuota(serviceManagementExtension, extensionConverter); if (!quota.equals(Quota.getDefaultInstance())) { serviceBuilder.setQuota(quota); } serviceBuilder.addAllMetrics(parseMetrics(serviceManagementExtension, extensionConverter)); } }
Example #30
Source File: UnitTestSwaggerUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
public static String pretty(Swagger swagger) { try { return writer.writeValueAsString(swagger); } catch (JsonProcessingException e) { throw new Error(e); } }