Java源码示例:io.smallrye.openapi.api.OpenApiDocument

示例1
@Test
public void testTagScanning_OrderGivenStaticFile() throws IOException, JSONException {
    Index i = indexOf(TagTestResource1.class, TagTestResource2.class);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(nestingSupportConfig(), i);
    OpenAPI scanResult = scanner.scan();
    OpenAPI staticResult = OpenApiParser.parse(new ByteArrayInputStream(
            "{\"info\" : {\"title\" : \"Tag order in static file\",\"version\" : \"1.0.0-static\"},\"tags\": [{\"name\":\"tag3\"},{\"name\":\"tag1\"}]}"
                    .getBytes()),
            Format.JSON);
    OpenApiDocument doc = OpenApiDocument.INSTANCE;
    doc.config(nestingSupportConfig());
    doc.modelFromStaticFile(staticResult);
    doc.modelFromAnnotations(scanResult);
    doc.initialize();
    OpenAPI result = doc.get();
    printToConsole(result);
    assertJsonEquals("resource.tags.ordergiven.staticfile.json", result);
}
 
示例2
public OpenApiDocument loadDocument(OpenAPI staticModel, OpenAPI annotationModel) {
    Config config = ConfigProvider.getConfig();
    OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);

    OpenAPI readerModel = OpenApiProcessor.modelFromReader(openApiConfig,
            Thread.currentThread().getContextClassLoader());

    OpenApiDocument document = createDocument(openApiConfig);
    if (annotationModel != null) {
        document.modelFromAnnotations(annotationModel);
    }
    document.modelFromReader(readerModel);
    document.modelFromStaticFile(staticModel);
    document.filter(filter(openApiConfig));
    document.initialize();
    return document;
}
 
示例3
/**
 * We load the document from the generated JSON file, which should have all the annotations
 *
 * Most apps will likely just want to serve the OpenAPI doc, rather than inject it, which is why we generated the
 * static file and parse it if required. The more Quarkus-like approach of serializing the doc to bytecode
 * can result in a lot of bytecode, which will likely just be turned straight into a static file anyway.
 */
@PostConstruct
void create() throws IOException {
    try (InputStream is = getClass().getClassLoader()
            .getResourceAsStream(OpenApiHandler.BASE_NAME + Format.JSON)) {
        if (is != null) {
            try (OpenApiStaticFile staticFile = new OpenApiStaticFile(is, Format.JSON)) {
                Config config = ConfigProvider.getConfig();
                OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);

                OpenAPI readerModel = OpenApiProcessor.modelFromReader(openApiConfig,
                        Thread.currentThread().getContextClassLoader());
                document = OpenApiDocument.INSTANCE;
                document.reset();
                document.config(openApiConfig);

                document.modelFromReader(readerModel);
                document.modelFromStaticFile(io.smallrye.openapi.runtime.OpenApiProcessor.modelFromStaticFile(staticFile));
                document.filter(OpenApiProcessor.getFilter(openApiConfig, Thread.currentThread().getContextClassLoader()));
                document.initialize();
            }
        }
    }

}
 
示例4
/**
 * Process the deployment in order to produce an OpenAPI document.
 *
 * @see org.wildfly.swarm.spi.api.DeploymentProcessor#process()
 */
@Override
public void process() throws Exception {
    // if the deployment is Implicit, we don't want to process it
    if (deploymentContext != null && deploymentContext.isImplicit()) {
        return;
    }
    try {
        // First register OpenApiServletContextListener which triggers the final init
        WARArchive warArchive = archive.as(WARArchive.class);
        warArchive.findWebXmlAsset().addListener(LISTENER_CLASS);
    } catch (Exception e) {
        throw new RuntimeException("Failed to register OpenAPI listener", e);
    }

    OpenApiStaticFile staticFile = ArchiveUtil.archiveToStaticFile(archive);

    // Set models from annotations and static file
    OpenApiDocument openApiDocument = OpenApiDocument.INSTANCE;
    openApiDocument.config(config);
    openApiDocument.modelFromStaticFile(OpenApiProcessor.modelFromStaticFile(staticFile));
    openApiDocument.modelFromAnnotations(OpenApiProcessor.modelFromAnnotations(config, index));
}
 
示例5
/**
 * Common test method.
 * @throws Exception
 */
protected void doTest(
        Class modelReaderClass,
        String staticResource,
        boolean disableAnnotationScanning,
        Class filterClass,
        String expectedResource) throws Exception {

    System.setProperty(OASConfig.SCAN_DISABLE, "" + disableAnnotationScanning);
    System.setProperty(OASConfig.MODEL_READER, modelReaderClass != null ? modelReaderClass.getName() : "");
    System.setProperty(OASConfig.FILTER, filterClass != null ? filterClass.getName() : "");

    TestConfig cfg = new TestConfig();
    OpenApiConfig oaiConfig = new OpenApiConfigImpl(cfg);
    Archive archive = archive(staticResource);
    OpenApiDocument.INSTANCE.reset();
    OpenApiDeploymentProcessor processor = new OpenApiDeploymentProcessor(oaiConfig, archive);
    processor.process();
    new OpenApiServletContextListener(cfg).contextInitialized(null);

    String actual = OpenApiSerializer.serialize(OpenApiDocument.INSTANCE.get(), Format.JSON);
    String expected = loadResource(getClass().getResource(expectedResource));

    assertJsonEquals(expected, actual);
}
 
示例6
/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(final ProxiedTckTest child, final RunNotifier notifier) {
    OpenApiDocument.INSTANCE.set(TckTestRunner.OPEN_API_DOCS.get(child.getTest().getClass()));

    Description description = describeChild(child);
    if (isIgnored(child)) {
        notifier.fireTestIgnored(description);
    } else {
        Statement statement = new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    Method testMethod = child.getTestMethod();
                    testMethod.invoke(child.getDelegate(), child.getArguments());
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    Test testAnno = child.getTestMethod().getAnnotation(Test.class);
                    Class[] expectedExceptions = testAnno.expectedExceptions();
                    if (expectedExceptions != null && expectedExceptions.length > 0) {
                        Class expectedException = expectedExceptions[0];
                        Assert.assertEquals(expectedException, cause.getClass());
                    } else {
                        throw cause;
                    }
                }
            }
        };
        runLeaf(statement, description, notifier);
    }

}
 
示例7
@BuildStep
public void build(ApplicationArchivesBuildItem archivesBuildItem,
        BuildProducer<FeatureBuildItem> feature,
        BuildProducer<GeneratedResourceBuildItem> resourceBuildItemBuildProducer,
        BuildProducer<NativeImageResourceBuildItem> nativeImageResources,
        OpenApiFilteredIndexViewBuildItem openApiFilteredIndexViewBuildItem,
        Capabilities capabilities) throws Exception {
    FilteredIndexView index = openApiFilteredIndexViewBuildItem.getIndex();

    feature.produce(new FeatureBuildItem(Feature.SMALLRYE_OPENAPI));
    OpenAPI staticModel = generateStaticModel(archivesBuildItem);

    OpenAPI annotationModel;

    if (shouldScanAnnotations(capabilities)) {
        annotationModel = generateAnnotationModel(index, capabilities);
    } else {
        annotationModel = null;
    }
    OpenApiDocument finalDocument = loadDocument(staticModel, annotationModel);
    for (Format format : Format.values()) {
        String name = OpenApiHandler.BASE_NAME + format;
        resourceBuildItemBuildProducer.produce(new GeneratedResourceBuildItem(name,
                OpenApiSerializer.serialize(finalDocument.get(), format).getBytes(StandardCharsets.UTF_8)));
        nativeImageResources.produce(new NativeImageResourceBuildItem(name));
    }
}
 
示例8
@Override
public void contextInitialized(ServletContextEvent sce) {
    // Instantiate OASModelReader and OASFilter
    OpenApiDocument openApiDocument = OpenApiDocument.INSTANCE;
    openApiDocument.modelFromReader(modelFromReader());
    openApiDocument.filter(getFilter());
    // Now we're ready to initialize the final model
    openApiDocument.initialize();
}
 
示例9
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (OAI.equalsIgnoreCase(exchange.getRequestPath()) && OpenApiDocument.INSTANCE.isSet()) {
        if (exchange.getRequestMethod().equals(Methods.GET)) {
            sendOai(exchange);
        } else if (exchange.getRequestMethod().equals(Methods.OPTIONS))  {
            sendPreflight(exchange);
        } else {
            next.handleRequest(exchange);
        }
    } else {
        next.handleRequest(exchange);
    }
}
 
示例10
private String getModel(Format format) {
    try {
        return OpenApiSerializer.serialize(OpenApiDocument.INSTANCE.get(), format);
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize OpenAPI in " + format, e);
    }
}
 
示例11
/**
 * Constructor.
 * 
 * @param testClass
 * @throws InitializationError
 */
public TckTestRunner(Class<?> testClass) throws InitializationError {
    super(testClass);
    this.testClass = testClass;
    this.tckTestClass = determineTckTestClass(testClass);

    // The Archive (shrinkwrap deployment)
    Archive archive = archive();
    // MPConfig
    OpenApiConfig config = ArchiveUtil.archiveToConfig(archive);

    try {
        IndexView index = ArchiveUtil.archiveToIndex(config, archive);
        OpenApiStaticFile staticFile = ArchiveUtil.archiveToStaticFile(archive);

        // Reset and then initialize the OpenApiDocument for this test.
        OpenApiDocument.INSTANCE.reset();
        OpenApiDocument.INSTANCE.config(config);
        OpenApiDocument.INSTANCE.modelFromStaticFile(OpenApiProcessor.modelFromStaticFile(staticFile));
        OpenApiDocument.INSTANCE.modelFromAnnotations(OpenApiProcessor.modelFromAnnotations(config, index));
        OpenApiDocument.INSTANCE.modelFromReader(OpenApiProcessor.modelFromReader(config, getContextClassLoader()));
        OpenApiDocument.INSTANCE.filter(OpenApiProcessor.getFilter(config, getContextClassLoader()));
        OpenApiDocument.INSTANCE.initialize();

        Assert.assertNotNull("Generated OAI document must not be null.", OpenApiDocument.INSTANCE.get());

        OPEN_API_DOCS.put(testClass, OpenApiDocument.INSTANCE.get());

        // Output the /openapi content to a file for debugging purposes
        File parent = new File("target", "TckTestRunner");
        if (!parent.exists()) {
            parent.mkdir();
        }
        File file = new File(parent, testClass.getName() + ".json");
        String content = OpenApiSerializer.serialize(OpenApiDocument.INSTANCE.get(), Format.JSON);
        try (FileWriter writer = new FileWriter(file)) {
            IOUtils.write(content, writer);
        }
    } catch (Exception e) {
        throw new InitializationError(e);
    }
}
 
示例12
private OpenApiDocument createDocument(OpenApiConfig openApiConfig) {
    OpenApiDocument document = OpenApiDocument.INSTANCE;
    document.reset();
    document.config(openApiConfig);
    return document;
}
 
示例13
@Produces
@Dependent
OpenApiDocument openApiDocument() {
    return this.document;
}