下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Swagger 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
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;
}
@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());
}
}
/**
*
* @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;
}
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());
}
/**
* 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);
}
}
@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"));
}
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;
}
@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());
}
}
}
@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();
}
}
@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));
}
/**
* 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;
}
}
@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"));
}
@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"));
}
@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;
}
private Optional<Operation> getOperation(final Swagger swagger, final HttpMethod httpMethod, final String path) {
return Optional.ofNullable(swagger.getPaths())
.orElseGet(Collections::emptyMap)
.entrySet().stream()
.filter(e -> path.equals(e.getKey()))
.findFirst()
.map(Entry::getValue)
.map(Path::getOperationMap)
.map(m -> m.get(httpMethod));
}
private Swagger addSecurityDefinitions(final Swagger swagger, ApiSource apiSource) throws GenerateException {
Swagger result = swagger;
if (apiSource.getSecurityDefinitions() == null) {
return result;
}
Map<String, SecuritySchemeDefinition> definitions = new TreeMap<String, SecuritySchemeDefinition>();
for (SecurityDefinition sd : apiSource.getSecurityDefinitions()) {
for (Map.Entry<String, SecuritySchemeDefinition> entry : sd.generateSecuritySchemeDefinitions().entrySet()) {
definitions.put(entry.getKey(), entry.getValue());
}
}
result.setSecurityDefinitions(definitions);
return result;
}
/**
* Scans a set of classes for Swagger annotations.
*
* @param swagger
* is the Swagger instance
* @param classes
* are a set of classes to scan
*/
public static void read(Swagger swagger, Set<Class<?>> classes) {
final Reader reader = new Reader(swagger);
for (Class<?> cls : classes) {
final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false,
new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(),
new ArrayList<Parameter>());
reader.read(context);
}
}
public static void main(String[] args) {
String rootPath = args[0];
try {
//Create destination dir
new File(rootPath + JSON_DESTINATION).mkdirs();
//Core
Swagger swagger = parseSwaggerDef(new File(rootPath + CORE_DEFINITION), CORE_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + CORE_JSON_DEFINITION), swagger);
//Authentication
swagger = parseSwaggerDef(new File(rootPath + AUTH_DEFINITION), AUTH_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + AUTH_JSON_DEFINITION), swagger);
//Workflow
swagger = parseSwaggerDef(new File(rootPath + WORKFLOW_DEFINITION), WORKFLOW_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + WORKFLOW_JSON_DEFINITION), swagger);
//Search
swagger = parseSwaggerDef(new File(rootPath + SEARCH_DEFINITION), SEARCH_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + SEARCH_JSON_DEFINITION), swagger);
//Search SQL
swagger = parseSwaggerDef(new File(rootPath + SEARCH_SQL_DEFINITION), SEARCH_SQL_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + SEARCH_SQL_JSON_DEFINITION), swagger);
//Discovery
swagger = parseSwaggerDef(new File(rootPath + DISCOVERY_DEFINITION), DISCOVERY_DEFINITION_TITLE);
Json.mapper().writeValue(new File(rootPath + DISCOVERY_JSON_DEFINITION), swagger);
} catch (IOException e) {
System.err.println("Failed to create a json definitions: " + e.getLocalizedMessage());
System.exit(1);
}
}
/**
* Scans a set of classes for Swagger annotations.
*
* @param swagger is the Swagger instance
* @param classes are a set of classes to scan
*/
public static void read(Swagger swagger, List<Class> classes) {
final Reader reader = new Reader(swagger);
for (Class cls : classes) {
ReaderContext context = new ReaderContext(cls, "", null, false);
reader.read(context);
}
}
/**
* Scans a single class for Swagger annotations - does not invoke
* ReaderListeners
*/
public Swagger read(Class<?> cls) {
SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
if (swaggerDefinition != null) {
readSwaggerConfig(cls, swaggerDefinition);
}
return read(cls, new LinkedHashMap<String, Tag>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
}
private static Map<String, Property> generateResponseHeader(Swagger swagger,
List<ResponseHeaderConfig> responseHeaders) {
Map<String, Property> headers = new HashMap<>();
for (ResponseHeaderConfig config : responseHeaders) {
Property property = generateResponseHeaderProperty(swagger, config);
headers.put(config.getName(), property);
}
return headers;
}
/**
* Scans a set of classes for Swagger annotations.
*
* @param swagger is the Swagger instance
* @param classes are a set of classes to scan
*/
public static void read(Swagger swagger, Set<Class<?>> classes) {
final Reader reader = new Reader(swagger);
for (Class<?> cls : classes) {
final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false,
new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(),
new ArrayList<Parameter>());
reader.read(context);
}
}
/**
* Update OAS definition for store
*
* @param product APIProduct
* @param oasDefinition OAS definition
* @param hostsWithSchemes host addresses with protocol mapping
* @return OAS definition
* @throws APIManagementException throws if an error occurred
*/
@Override
public String getOASDefinitionForStore(APIProduct product, String oasDefinition,
Map<String, String> hostsWithSchemes) throws APIManagementException {
Swagger swagger = getSwagger(oasDefinition);
updateOperations(swagger);
updateEndpoints(product, hostsWithSchemes, swagger);
return updateSwaggerSecurityDefinitionForStore(swagger, new SwaggerData(product), hostsWithSchemes);
}
/**
* Updates External documentation in Swagger
*
* @param swagger the API doc
* @param apiDocInfo the service information
*/
protected void updateExternalDoc(Swagger swagger, ApiDocInfo apiDocInfo) {
if (apiDocInfo.getApiInfo() == null)
return;
String externalDoc = apiDocInfo.getApiInfo().getDocumentationUrl();
if (externalDoc != null) {
swagger.setExternalDocs(new ExternalDocs(EXTERNAL_DOCUMENTATION, externalDoc));
}
}
public static OperationsHolder extractOperation(Swagger swagger) {
OperationsHolder operations = new OperationsHolder();
swagger.getPaths().keySet().forEach(path
-> swagger.getPaths().get(path).getOperationMap().forEach((httpMethod, operation)
-> operations.addOperation(new OperationKey().setPath(path).setHttpMethod(httpMethod), operation)
));
return operations;
}
@Override
public void writeTo(Swagger data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
Map<String, Path> map = data.getPaths();
Set<String> keyset = new HashSet<>(map.keySet());
for (String key : keyset) {
if(key.startsWith("/api")){
continue;
}
Path path = map.get(key);
map.remove(key);
map.put("/api" + key, path);
}
super.writeTo(data, type, genericType, annotations, mediaType, headers, out);
}
/**
* Get parsed Swagger object
*
* @param oasDefinition OAS definition
* @return Swagger
* @throws APIManagementException
*/
Swagger getSwagger(String oasDefinition) {
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
if (CollectionUtils.isNotEmpty(parseAttemptForV2.getMessages())) {
log.debug("Errors found when parsing OAS definition");
}
return parseAttemptForV2.getSwagger();
}
@Test
public void emptyOperationId() {
Swagger swagger = SwaggerUtils.parseSwagger(this.getClass().getResource("/schemas/boolean.yaml"));
swagger.getPaths().values().stream()
.findFirst().get()
.getPost().setOperationId("");
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("OperationId can not be empty, path=/testboolean, httpMethod=POST.");
new SwaggerOperations(swagger);
}
public static String pretty(Swagger swagger) {
try {
return writer.writeValueAsString(swagger);
} catch (JsonProcessingException e) {
throw new Error(e);
}
}