io.swagger.parser.SwaggerParser Java Examples

The following examples show how to use io.swagger.parser.SwaggerParser. 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: MainApiVerticle.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            SwaggerManager.getInstance().setSwagger(swagger);
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);

            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(config().getInteger("http.port", 8080));
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #2
Source File: SwaggerConverter.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: SOAPOperationBindingTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testVendorExtensions() throws Exception {
    String swaggerStr = SOAPOperationBindingUtils.getSoapOperationMappingForUrl(
            Thread.currentThread().getContextClassLoader().getResource("wsdls/simpleCustomerService.wsdl")
                    .toExternalForm());
    Swagger swagger = new SwaggerParser().parse(swaggerStr);
    Assert.assertNotNull(
            swagger.getPath("/getCustomer").getOperationMap().get(HttpMethod.GET).getVendorExtensions());
    Assert.assertNotNull(swagger.getPath("/getCustomer").getOperationMap().get(HttpMethod.GET).getVendorExtensions()
            .get("x-wso2-soap"));
    Map<String, Object> vendorExtensions = swagger.getPath("/getCustomer").getOperationMap().get(HttpMethod.GET)
            .getVendorExtensions();
    for (String s : vendorExtensions.keySet()) {
        if (s.equals("soap-action")) {
            Assert.assertEquals(vendorExtensions.get("soap-action"), "getCustomer");
        }
        if (s.equals("soap-operation")) {
            Assert.assertEquals(vendorExtensions.get("soap-operation"), "getCustomer");
        }
        if (s.equals("namespace")) {
            Assert.assertEquals(vendorExtensions.get("namespace"), "http://service.test.com/");
        }
    }
}
 
Example #4
Source File: MainApiVerticle.java    From swagger-aem with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
    FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("openapi.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver());

            deployVerticles(startFuture);

            vertx.createHttpServer()
                .requestHandler(swaggerRouter::accept) 
                .listen(serverPort, h -> {
                    if (h.succeeded()) {
                        startFuture.complete();
                    } else {
                        startFuture.fail(h.cause());
                    }
                });
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #5
Source File: SwaggerFilter.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
private byte[] writeDynamicResource(InputStream is) throws IOException {
  String str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
  Swagger swagger = new SwaggerParser().parse(str);
  // set the resource listing tag
  Tag dynamic = new Tag();
  dynamic.setName("dynamic");
  dynamic.setDescription("Dynamic Cypher resources");
  swagger.addTag(dynamic);
  // add resources to the path
  Map<String,Path> paths = swagger.getPaths();
  paths.putAll(configuration.getCypherResources());
  Map<String,Path> sorted = new LinkedHashMap<>();
  List<String> keys = new ArrayList<>();
  keys.addAll(paths.keySet());
  Collections.sort(keys);
  for (String key : keys) {
    sorted.put(key, paths.get(key));
  }
  swagger.setPaths(sorted);
  // return updated swagger JSON
  return Json.pretty(swagger).getBytes();
}
 
Example #6
Source File: MultiOpenApiParser.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private static Swagger tryGetOpenApi(File file, String userDefinedFilename)
    throws OpenApiConversionException {
  try {
    Swagger swagger = new SwaggerParser().read(file.getAbsolutePath());
    if (swagger == null) {
      throw new OpenApiConversionException(
          String.format(
              "OpenAPI spec in file {%s} is ill formed and cannot be parsed",
              userDefinedFilename));
    } else {
      return swagger;
    }
  } catch (RuntimeException ex) {
    throw new OpenApiConversionException(
        String.format(
            "OpenAPI spec in file {%s} is ill formed and cannot be parsed: %s",
            userDefinedFilename, ex.getMessage()));
  }
}
 
Example #7
Source File: DocumentController.java    From sc-generator with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/swaggerDocProxy/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Swagger swaggerDocProxy(@PathVariable(value = "id") Integer id,
                               @RequestParam(value = "trimSystemController", defaultValue = "true") boolean trimSystemController,
                               HttpServletRequest request) {
    Document document = documentService.findOne(id);
    if (document != null) {
        Swagger swagger = new SwaggerParser()
                .parse(document.getContent());
        if (trimSystemController) {
            swagger = Generator.convertSwagger(swagger);
        }
        swagger.setHost(request.getServerName() + ":" + request.getServerPort() + prefix + "/" + id);
        return swagger;
    }
    return null;
}
 
Example #8
Source File: SwaggerDiff.java    From swagger-diff with Apache License 2.0 6 votes vote down vote up
/**
 * @param oldSpec
 * @param newSpec
 * @param auths
 * @param version
 */
private SwaggerDiff(String oldSpec, String newSpec, List<AuthorizationValue> auths,
        String version) {
    if (SWAGGER_VERSION_V2.equals(version)) {
        SwaggerParser swaggerParser = new SwaggerParser();
        oldSpecSwagger = swaggerParser.read(oldSpec, auths, true);
        newSpecSwagger = swaggerParser.read(newSpec, auths, true);
    } else {
        SwaggerCompatConverter swaggerCompatConverter = new SwaggerCompatConverter();
        try {
            oldSpecSwagger = swaggerCompatConverter.read(oldSpec, auths);
            newSpecSwagger = swaggerCompatConverter.read(newSpec, auths);
        } catch (IOException e) {
            logger.error("cannot read api-doc from spec[version_v1.x]", e);
            return;
        }
    }
    if (null == oldSpecSwagger || null == newSpecSwagger) { throw new RuntimeException(
            "cannot read api-doc from spec."); }
}
 
Example #9
Source File: MainApiVerticle.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            SwaggerManager.getInstance().setSwagger(swagger);
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);

            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(config().getInteger("http.port", 8080));
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #10
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the v2 or v3 open API definition in yaml or json format into json format of the respective format.
 * v2/YAML -> v2/JSON
 * v3/YAML -> v3/JSON
 *
 * @param openAPIContent open API as a string content
 * @return openAPI definition as a JSON String
 */
public static String getOpenAPIAsJson(OpenAPI openAPI, String openAPIContent, Path openAPIPath) {
    String jsonOpenAPI = Json.pretty(openAPI);
    String openAPIVersion;
    Path fileName = openAPIPath.getFileName();

    if (fileName == null) {
        throw new CLIRuntimeException("Error: Couldn't resolve OpenAPI file name.");
    } else if (fileName.toString().endsWith("json")) {
        openAPIVersion = findSwaggerVersion(openAPIContent, false);
    } else {
        openAPIVersion = findSwaggerVersion(jsonOpenAPI, false);
    }

    switch (openAPIVersion) {
        case "2":
            Swagger swagger = new SwaggerParser().parse(openAPIContent);
            return Json.pretty(swagger);
        case "3":
            return jsonOpenAPI;

        default:
            throw new CLIRuntimeException("Error: Swagger version is not identified");
    }
}
 
Example #11
Source File: OpenApiSpec.java    From webtau with Apache License 2.0 6 votes vote down vote up
public OpenApiSpec(String specUrl) {
    isSpecDefined = !specUrl.isEmpty();

    this.specUrl = specUrl;
    SwaggerDeserializationResult swaggerParseResult =
            new SwaggerParser().readWithInfo(specUrl, null, true);

    api = swaggerParseResult.getSwagger();
    apiOperationResolver = api != null ? new ApiOperationResolver(api, null) : null;

    if (api == null && isSpecDefined) {
        throw new IllegalArgumentException(
                format("Unable to load API descriptor from provided %s:\n\t%s",
                        specUrl, swaggerParseResult.getMessages().toString().replace("\n", "\n\t")));
    }

    operationsAndResponses = isSpecDefined ? enumerateOperations() : Collections.emptyMap();
}
 
Example #12
Source File: MainApiVerticle.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
    FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("openapi.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver());

            deployVerticles(startFuture);

            vertx.createHttpServer()
                .requestHandler(swaggerRouter::accept) 
                .listen(serverPort, h -> {
                    if (h.succeeded()) {
                        startFuture.complete();
                    } else {
                        startFuture.fail(h.cause());
                    }
                });
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #13
Source File: MainApiVerticle.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
    FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("openapi.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver());

            deployVerticles(startFuture);

            vertx.createHttpServer()
                .requestHandler(swaggerRouter::accept) 
                .listen(serverPort, h -> {
                    if (h.succeeded()) {
                        startFuture.complete();
                    } else {
                        startFuture.fail(h.cause());
                    }
                });
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #14
Source File: MainApiVerticle.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            SwaggerManager.getInstance().setSwagger(swagger);
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);

            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(config().getInteger("http.port", 8080));
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #15
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleEnumValues() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-enum.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-enum.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #16
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void shouldFindDifferentEnumValues() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-enum-wrong.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-enum.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #17
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleExpectedPathsWithPrefix() {
    File implFirstSwaggerLocation = new File(
        SwaggerDocumentationDrivenAssertTest.class.getResource("/swagger_with_path_prefixes.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerDocumentationDrivenAssertTest.class.getResource("/swagger.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()),
        "/assertj-swagger-path-prefix.properties")
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #18
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleDefinitionsUsingAllOf() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-test-flat.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-test-inheritance.json").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()),
        "/assertj-swagger-allOf.properties")
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #19
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleDefinitionsUsingAllOfIncludingCycles() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-test-flat.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-test-inheritance-cycles.json").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()),
        "/assertj-swagger-allOf.properties")
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #20
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleDefinitionsUsingAllOfForComposition() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-composition-flat.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-allOf-composition.json").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #21
Source File: OAS2ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas2" + File.separator + "oas2Resources.json";
    String oas2Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    SwaggerParser swaggerParser = new SwaggerParser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas2Parser, oas2Resources);
    Swagger swaggerObj = swaggerParser.parse(definition);
    boolean isExtensionNotFound =
            swaggerObj.getVendorExtensions() == null || swaggerObj.getVendorExtensions().isEmpty();
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, swaggerObj.getPaths().size());

    Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Path> pathEntry = itr.next();
        Path path = pathEntry.getValue();
        for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
            Operation operation = operationEntry.getValue();
            Assert.assertFalse(operation.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = swaggerObj.getPath("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    OAuth2Definition oAuth2Definition = (OAuth2Definition) swaggerObj.getSecurityDefinitions().get("default");
    Assert.assertTrue(oAuth2Definition.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", oAuth2Definition.getScopes().get("newScope"));

    Assert.assertTrue(oAuth2Definition.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding = (Map<String, String>) oAuth2Definition.getVendorExtensions()
            .get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
 
Example #22
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void shouldFindDifferentRequiredFieldsForObjectDefinition() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-missing-required-field-object.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #23
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleByteArrayValues() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-bytearray.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-bytearray.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #24
Source File: SwaggerDocumentationDrivenAssertTest.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void shouldFindDifferentByteArrayValues() {
    File implFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-bytearray-wrong.json").getPath());
    File designFirstSwaggerLocation = new File(
        SwaggerConsumerDrivenAssertTest.class.getResource("/swagger-bytearray.yaml").getPath());

    Validate.notNull(implFirstSwaggerLocation.getAbsolutePath(), "actualLocation must not be null!");
    new SwaggerAssert(new SwaggerParser().read(implFirstSwaggerLocation.getAbsolutePath()))
        .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
 
Example #25
Source File: Swagger2MarkupConverter.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the SwaggerParser to read the Swagger source.
 *
 * @param swaggerLocation the location of the Swagger source
 * @return the Swagger model
 */
private Swagger readSwagger(String swaggerLocation) {
    Swagger swagger = new SwaggerParser().read(swaggerLocation);
    if (swagger == null) {
        throw new IllegalArgumentException("Failed to read the Swagger source");
    }
    return swagger;
}
 
Example #26
Source File: Swagger2MarkupConverter.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Swagger2MarkupConverter.Builder from a given Swagger YAML or JSON reader.
 *
 * @param swaggerReader the Swagger YAML or JSON reader.
 * @return a Swagger2MarkupConverter
 */
public static Builder from(Reader swaggerReader) {
    Validate.notNull(swaggerReader, "swaggerReader must not be null");
    Swagger swagger;
    try {
        swagger = new SwaggerParser().parse(IOUtils.toString(swaggerReader));
    } catch (IOException e) {
        throw new RuntimeException("Swagger source can not be parsed", e);
    }
    if (swagger == null)
        throw new IllegalArgumentException("Swagger source is in a wrong format");

    return new Builder(swagger);
}
 
Example #27
Source File: TemplateTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> readSwaggerModelInfo(String swaggerYamlFile, CodegenConfig config) throws IOException {

    Map<String, Object> templateData = new HashMap<>();
    String swaggerString = readResourceInClasspath(swaggerYamlFile);
    Swagger swagger = new SwaggerParser().parse(swaggerString);

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult result = new OpenAPIParser().readContents(swaggerString, null, options);
    OpenAPI openAPI = result.getOpenAPI();

    Components components = openAPI.getComponents();

    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions == null) {
      return templateData;
    }
    List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
    for (String key : components.getSchemas().keySet()) {
      Schema mm = components.getSchemas().get(key);
      CodegenModel cm = config.fromModel(key, mm);
      Map<String, String> item = new HashMap<String, String>();
      item.put("import", config.toModelImport(cm.classname));
      imports.add(item);
    }
    templateData.put("imports", imports);
    return templateData;
  }
 
Example #28
Source File: SwaggerDiff.java    From swagger-diff with Apache License 2.0 5 votes vote down vote up
private SwaggerDiff(JsonNode oldSpec, JsonNode newSpec) {
    SwaggerParser swaggerParser = new SwaggerParser();
    oldSpecSwagger = swaggerParser.read(oldSpec, true);
    newSpecSwagger = swaggerParser.read(newSpec, true);
    if (null == oldSpecSwagger || null == newSpecSwagger) { throw new RuntimeException(
        "cannot read api-doc from spec."); }
}
 
Example #29
Source File: SwaggerDiff.java    From swagger-diff with Apache License 2.0 5 votes vote down vote up
/**
 * @param rawOldSpec
 * @param rawNewSpec
 */
private SwaggerDiff(String rawOldSpec, String rawNewSpec) {
    SwaggerParser swaggerParser = new SwaggerParser();
    oldSpecSwagger = swaggerParser.parse(rawOldSpec);
    newSpecSwagger = swaggerParser.parse(rawNewSpec);

    if (null == oldSpecSwagger || null == newSpecSwagger) {
        throw new RuntimeException("cannot read api-doc from spec.");
    }
}
 
Example #30
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}