Java Code Examples for org.eclipse.microprofile.openapi.models.OpenAPI

The following examples show how to use org.eclipse.microprofile.openapi.models.OpenAPI. These examples are extracted from open source projects. 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 Project: smallrye-open-api   Source File: JaxRsAnnotationScanner.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Processing a single JAX-RS resource class (annotated with @Path).
 * 
 * @param openApi
 * @param resourceClass
 * @param locatorPathParameters
 */
private void processResourceClass(final AnnotationScannerContext context,
        OpenAPI openApi,
        ClassInfo resourceClass,
        List<Parameter> locatorPathParameters) {
    JaxRsLogging.log.processingClass(resourceClass.simpleName());

    // Process @SecurityScheme annotations.
    processSecuritySchemeAnnotation(resourceClass, openApi);

    // Process Java security
    processJavaSecurity(resourceClass, openApi);

    // Now find and process the operation methods
    processResourceMethods(context, resourceClass, openApi, locatorPathParameters);
}
 
Example 2
private OpenAPI scanMicroProfileOpenApiAnnotations() {

        // Initialize a new OAI document.  Even if nothing is found, this will be returned.
        OpenAPI openApi = new OpenAPIImpl();
        openApi.setOpenapi(OpenApiConstants.OPEN_API_VERSION);

        // Creating a new instance of a registry which will be set on the thread context.
        SchemaRegistry schemaRegistry = SchemaRegistry.newInstance(annotationScannerContext.getConfig(), openApi,
                annotationScannerContext.getIndex());

        // Register custom schemas if available
        getCustomSchemaRegistry(annotationScannerContext.getConfig()).registerCustomSchemas(schemaRegistry);

        // Find all OpenAPIDefinition annotations at the package level
        ScannerLogging.log.scanning("OpenAPI");
        processPackageOpenAPIDefinitions(annotationScannerContext, openApi);

        return openApi;
    }
 
Example 3
@Test
public void testMethodRolesAllowedGeneratedScheme() throws IOException {
    Index index = indexOf(RolesAllowedApp.class, RolesAllowedResource2.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    SecurityRequirement requirement = result.getPaths().getPathItem("/v2/secured").getGET().getSecurity().get(0);
    assertNotNull(requirement);
    assertEquals(2, requirement.getScheme("rolesScheme").size());
    assertEquals("admin", requirement.getScheme("rolesScheme").get(0));
    assertEquals("users", requirement.getScheme("rolesScheme").get(1));
    assertArrayEquals(new String[] { "admin", "users" },
            result.getComponents()
                    .getSecuritySchemes()
                    .get("rolesScheme")
                    .getFlows()
                    .getClientCredentials()
                    .getScopes()
                    .keySet()
                    .toArray());
}
 
Example 4
@Test
public void testDeclaredRolesMethodRolesAllowedGeneratedScheme() throws IOException {
    Index index = indexOf(RolesAllowedApp.class, RolesDeclaredResource.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    SecurityRequirement requirement = result.getPaths().getPathItem("/v1/secured").getGET().getSecurity().get(0);
    assertNotNull(requirement);
    assertEquals(1, requirement.getScheme("rolesScheme").size());
    assertEquals("admin", requirement.getScheme("rolesScheme").get(0));
    assertArrayEquals(new String[] { "admin", "users" },
            result.getComponents()
                    .getSecuritySchemes()
                    .get("rolesScheme")
                    .getFlows()
                    .getClientCredentials()
                    .getScopes()
                    .keySet()
                    .toArray());
}
 
Example 5
@Test
public void testSchemesWithoutRoles() throws IOException {
    Index index = indexOf(UndeclaredFlowsNoRolesAllowedApp.class, NoRolesResource.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    SecurityRequirement requirement = result.getPaths().getPathItem("/v1/secured").getGET().getSecurity().get(0);
    assertNotNull(requirement);
    assertEquals(1, requirement.getScheme("oidc").size());
    assertEquals("admin", requirement.getScheme("oidc").get(0));
    assertNull(result.getComponents()
            .getSecuritySchemes()
            .get("oidc")
            .getFlows());
}
 
Example 6
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private OpenAPI generateAnnotationModel(IndexView indexView, Capabilities capabilities) {
    Config config = ConfigProvider.getConfig();
    OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);

    String defaultPath = config.getValue("quarkus.http.root-path", String.class);

    List<AnnotationScannerExtension> extensions = new ArrayList<>();
    // Add RestEasy if jaxrs
    if (capabilities.isCapabilityPresent(Capabilities.RESTEASY)) {
        extensions.add(new RESTEasyExtension(indexView));
    }
    // Add path if not null
    if (defaultPath != null) {
        extensions.add(new CustomPathExtension(defaultPath));
    }
    return new OpenApiAnnotationScanner(openApiConfig, indexView, extensions).scan();
}
 
Example 7
Source Project: smallrye-open-api   Source File: OpenApiParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses the resource found at the given URL. This method accepts resources
 * either in JSON or YAML format. It will parse the input and, assuming it is
 * valid, return an instance of {@link OpenAPI}.
 * 
 * @param url URL to OpenAPI document
 * @return OpenAPIImpl parsed from URL
 * @throws IOException URL parameter is not found
 */
public static final OpenAPI parse(URL url) throws IOException {
    try {
        String fname = url.getFile();
        if (fname == null) {
            throw IoMessages.msg.noFileName(url.toURI().toString());
        }
        int lidx = fname.lastIndexOf('.');
        if (lidx == -1 || lidx >= fname.length()) {
            throw IoMessages.msg.invalidFileName(url.toURI().toString());
        }
        String ext = fname.substring(lidx + 1);
        boolean isJson = ext.equalsIgnoreCase("json");
        boolean isYaml = ext.equalsIgnoreCase("yaml") || ext.equalsIgnoreCase("yml");
        if (!isJson && !isYaml) {
            throw IoMessages.msg.invalidFileExtension(url.toURI().toString());
        }

        try (InputStream stream = url.openStream()) {
            return parse(stream, isJson ? Format.JSON : Format.YAML);
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}
 
Example 8
Source Project: smallrye-open-api   Source File: DefinitionReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads a OpenAPIDefinition annotation.
 * 
 * @param context the scanning context
 * @param openApi OpenAPIImpl
 * @param annotationInstance {@literal @}OpenAPIDefinition annotation
 */
public static void processDefinition(final AnnotationScannerContext context,
        final OpenAPI openApi,
        final AnnotationInstance annotationInstance) {
    IoLogging.log.annotation("@OpenAPIDefinition");

    openApi.setInfo(InfoReader.readInfo(annotationInstance.value(DefinitionConstant.PROP_INFO)));
    openApi.setTags(TagReader.readTags(annotationInstance.value(DefinitionConstant.PROP_TAGS)).orElse(null));
    openApi.setServers(
            ServerReader.readServers(annotationInstance.value(DefinitionConstant.PROP_SERVERS)).orElse(null));
    openApi.setSecurity(SecurityRequirementReader
            .readSecurityRequirements(annotationInstance.value(DefinitionConstant.PROP_SECURITY)).orElse(null));
    openApi.setExternalDocs(
            ExternalDocsReader
                    .readExternalDocs(annotationInstance.value(ExternalDocsConstant.PROP_EXTERNAL_DOCS)));
    openApi.setComponents(ComponentsReader.readComponents(context,
            annotationInstance.value(DefinitionConstant.PROP_COMPONENTS)));
}
 
Example 9
Source Project: quarkus   Source File: OpenApiDocumentProducer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
            }
        }
    }

}
 
Example 10
Source Project: smallrye-open-api   Source File: ResourceParameterTests.java    License: Apache License 2.0 6 votes vote down vote up
/*************************************************************************/

    /*
     * Test cases derived from original example in SmallRye OpenAPI issue #260.
     *
     * https://github.com/smallrye/smallrye-open-api/issues/260
     *
     */
    @Test
    public void testGenericSetResponseWithSetIndexed() throws IOException, JSONException {
        Index i = indexOf(FruitResource.class, Fruit.class, Seed.class, Set.class);
        OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(emptyConfig(), i);
        OpenAPI result = scanner.scan();
        printToConsole(result);
        assertJsonEquals("responses.generic-collection.set-indexed.json", result);
    }
 
Example 11
Source Project: smallrye-open-api   Source File: ResourceParameterTests.java    License: Apache License 2.0 6 votes vote down vote up
/*************************************************************************/

    /*
     * Test case derived from original example in SmallRye OpenAPI issue #239.
     *
     * https://github.com/smallrye/smallrye-open-api/issues/239
     *
     */
    @Test
    public void testBeanParamMultipartFormInheritance() throws IOException, JSONException {
        Index i = indexOf(BeanParamMultipartFormInheritanceResource.class,
                MultipartFormVerify.class,
                MultipartFormUploadIconForm.class,
                BeanParamBase.class,
                BeanParamImpl.class,
                BeanParamAddon.class);
        OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(emptyConfig(), i);
        OpenAPI result = scanner.scan();
        printToConsole(result);
        assertJsonEquals("params.beanparam-multipartform-inherited.json", result);
    }
 
Example 12
Source Project: tomee   Source File: TomEEOpenAPIExtension.java    License: Apache License 2.0 6 votes vote down vote up
public OpenAPI getOrCreateOpenAPI(final Application application) {
    if (classes != null) {
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        return openapis.computeIfAbsent(application,
                app -> createOpenApi(application.getClass(), classes.stream().map(c -> {
                    try {
                        return loader.loadClass(c);
                    } catch (final ClassNotFoundException e) {
                        throw new IllegalArgumentException(e);
                    }
                })));
    }
    if (packages == null && (!application.getSingletons().isEmpty() || !application.getClasses().isEmpty())) {
        return openapis.computeIfAbsent(application,
                app -> createOpenApi(application.getClass(), Stream.concat(endpoints.stream().map(Bean::getBeanClass),
                        Stream.concat(app.getClasses().stream(), app.getSingletons().stream().map(Object::getClass)))));
    }
    return openapis.computeIfAbsent(application,
            app -> createOpenApi(application.getClass(), endpoints.stream().map(Bean::getBeanClass)));
}
 
Example 13
@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);
}
 
Example 14
@Test
public void testCustomAnnotationScannerExtension() {
    Index index = IndexScannerTestBase.indexOf(ExtensionParsingTestResource.class);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(IndexScannerTestBase.emptyConfig(), index,
            Arrays.asList(new AnnotationScannerExtension() {
                @Override
                public Object parseExtension(String name, String value) {
                    /*
                     * "parsing" consists of creating a singleton map with the
                     * extension name as the key and the unparsed value as the value
                     */
                    return Collections.singletonMap(name, value);
                }
            }));

    OpenAPI result = scanner.scan();
    org.eclipse.microprofile.openapi.models.callbacks.Callback cb;
    cb = result.getPaths().getPathItem("/ext-custom").getPOST().getCallbacks().get("extendedCallback");
    Map<String, Object> ext = cb.getPathItem("http://localhost:8080/resources/ext-callback").getGET().getExtensions();
    assertEquals(4, ext.size());
    assertEquals(Collections.singletonMap("x-object", "{ \"key\":\"value\" }"), ext.get("x-object"));
    assertEquals("{ \"key\":\"value\" }", ext.get("x-object-unparsed"));
    assertEquals(Collections.singletonMap("x-array", "[ \"val1\",\"val2\" ]"), ext.get("x-array"));
    assertEquals("true", ext.get("x-booltrue"));
}
 
Example 15
/**
 * Scans all <code>@OpenAPIDefinition</code> annotations present on <code>package-info</code>
 * classes known to the scanner's index.
 * 
 * @param oai the current OpenAPI result
 * @return the created OpenAPI
 */
private OpenAPI processPackageOpenAPIDefinitions(final AnnotationScannerContext context, OpenAPI oai) {
    List<AnnotationInstance> packageDefs = context.getIndex()
            .getAnnotations(DefinitionConstant.DOTNAME_OPEN_API_DEFINITION)
            .stream()
            .filter(annotation -> annotation.target().kind() == AnnotationTarget.Kind.CLASS)
            .filter(annotation -> annotation.target().asClass().name().withoutPackagePrefix().equals("package-info"))
            .collect(Collectors.toList());

    for (AnnotationInstance packageDef : packageDefs) {
        OpenAPI packageOai = new OpenAPIImpl();
        DefinitionReader.processDefinition(context, packageOai, packageDef);
        oai = MergeUtil.merge(oai, packageOai);
    }
    return oai;
}
 
Example 16
Source Project: smallrye-open-api   Source File: SpringAnnotationScanner.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find and process all Spring Controllers
 * TODO: Also support org.springframework.stereotype.Controller annotations ?
 *
 * @param context the scanning context
 * @param openApi the openAPI model
 */
private void processControllerClasses(final AnnotationScannerContext context, OpenAPI openApi) {
    // Get all Spring controllers and convert them to OpenAPI models (and merge them into a single one)
    Collection<AnnotationInstance> controllerAnnotations = context.getIndex()
            .getAnnotations(SpringConstants.REST_CONTROLLER);
    List<ClassInfo> applications = new ArrayList<>();
    for (AnnotationInstance annotationInstance : controllerAnnotations) {
        if (annotationInstance.target().kind().equals(AnnotationTarget.Kind.CLASS)) {
            ClassInfo classInfo = annotationInstance.target().asClass();
            applications.add(classInfo);
        } else {
            SpringLogging.log.ignoringAnnotation(SpringConstants.REST_CONTROLLER.withoutPackagePrefix());
        }
    }

    // this can be a useful extension point to set/override the application path
    processScannerExtensions(context, applications);

    for (ClassInfo controller : applications) {
        OpenAPI applicationOpenApi = processControllerClass(context, controller);
        openApi = MergeUtil.merge(openApi, applicationOpenApi);
    }
}
 
Example 17
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 18
Source Project: smallrye-open-api   Source File: MergeUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Performs a single full merge test. Two documents are loaded (as resources) and then
 * merged. The expected merge result is then loaded and compared with the actual result.
 * 
 * @param resource1
 * @param resource2
 * @param expected
 * @throws IOException
 * @throws ParseException
 * @throws JSONException
 */
private static void doTest(String resource1, String resource2, String expected)
        throws IOException, ParseException, JSONException {
    URL resource1Url = MergeUtilTest.class.getResource(resource1);
    URL resource2Url = MergeUtilTest.class.getResource(resource2);
    URL expectedUrl = MergeUtilTest.class.getResource(expected);

    String expectedContent = loadResource(expectedUrl);

    OpenAPI resource1Model = OpenApiParser.parse(resource1Url);
    OpenAPI resource2Model = OpenApiParser.parse(resource2Url);

    OpenAPI actualModel = MergeUtil.merge(resource1Model, resource2Model);

    String actual = OpenApiSerializer.serialize(actualModel, Format.JSON);

    assertJsonEquals(expectedContent, actual);
}
 
Example 19
Source Project: smallrye-open-api   Source File: DefinitionReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads a OpenAPIDefinition Json node.
 * 
 * @param openApi the OpenAPI model
 * @param node the Json node
 */
public static void processDefinition(final OpenAPI openApi,
        final JsonNode node) {
    IoLogging.log.jsonNode("OpenAPIDefinition");

    openApi.setOpenapi(JsonUtil.stringProperty(node, DefinitionConstant.PROP_OPENAPI));
    openApi.setInfo(InfoReader.readInfo(node.get(DefinitionConstant.PROP_INFO)));
    openApi.setTags(TagReader.readTags(node.get(DefinitionConstant.PROP_TAGS)).orElse(null));
    openApi.setServers(ServerReader.readServers(node.get(DefinitionConstant.PROP_SERVERS)).orElse(null));
    openApi.setSecurity(SecurityRequirementReader
            .readSecurityRequirements(node.get(DefinitionConstant.PROP_SECURITY)).orElse(null));
    openApi.setExternalDocs(
            ExternalDocsReader.readExternalDocs(node.get(ExternalDocsConstant.PROP_EXTERNAL_DOCS)));
    openApi.setComponents(
            ComponentsReader.readComponents(node.get(DefinitionConstant.PROP_COMPONENTS)));
    openApi.setPaths(PathsReader.readPaths(node.get(DefinitionConstant.PROP_PATHS)));
    ExtensionReader.readExtensions(node, openApi);
}
 
Example 20
Source Project: smallrye-open-api   Source File: FilterUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates and returns the filter to use for the test.
 */
private OASFilter filter() {
    return new OASFilter() {
        /**
         * @see org.eclipse.microprofile.openapi.OASFilter#filterOpenAPI(org.eclipse.microprofile.openapi.models.OpenAPI)
         */
        @Override
        public void filterOpenAPI(OpenAPI openAPI) {
            openAPI.getInfo().setLicense(null);
            openAPI.getInfo().setTitle("Updated API Title");
        }

        /**
         * @see org.eclipse.microprofile.openapi.OASFilter#filterPathItem(org.eclipse.microprofile.openapi.models.PathItem)
         */
        @Override
        public PathItem filterPathItem(PathItem pathItem) {
            if (pathItem.getRef() != null) {
                return null;
            } else {
                return pathItem;
            }
        }
    };
}
 
Example 21
Source Project: smallrye-open-api   Source File: ModelUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds a {@link Tag} to the {@link OpenAPI} model. If a tag having the same
 * name already exists in the model, the tags' attributes are merged, with the
 * new tag's attributes overriding the value of any attributes specified on
 * both.
 * 
 * @param openApi the OpenAPI model
 * @param tag a new {@link Tag} to add
 */
public static void addTag(OpenAPI openApi, Tag tag) {
    List<Tag> tags = openApi.getTags();

    if (tags == null || tags.isEmpty()) {
        openApi.addTag(tag);
        return;
    }

    Tag current = tags.stream().filter(t -> t.getName().equals(tag.getName())).findFirst().orElse(null);
    int currentIndex = tags.indexOf(current);

    if (current != null) {
        Tag replacement = MergeUtil.mergeObjects(current, tag);
        tags = new ArrayList<>(tags);
        tags.set(currentIndex, replacement);
        openApi.setTags(tags);
    } else {
        openApi.addTag(tag);
    }
}
 
Example 22
/**
 * Scan the deployment for relevant annotations. Returns an OpenAPI data model that was
 * built from those found annotations.
 * 
 * @return OpenAPI generated from scanning annotations
 */
public OpenAPI scan() {
    // First scan the MicroProfile OpenAPI Annotations. Maybe later we can load this with SPI as well, and allow other Annotation sets.
    OpenAPI openApi = scanMicroProfileOpenApiAnnotations();

    // Now load all entry points with SPI and scan those
    List<AnnotationScanner> annotationScanners = annotationScannerFactory.getAnnotationScanners();
    for (AnnotationScanner annotationScanner : annotationScanners) {
        ScannerLogging.log.scanning(annotationScanner.getName());
        CurrentScannerInfo.register(annotationScanner);
        openApi = annotationScanner.scan(annotationScannerContext, openApi);
    }
    return openApi;
}
 
Example 23
Source Project: smallrye-open-api   Source File: JaxRsAnnotationScanner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find and process all JAX-RS applications
 * 
 * @param context the scanning context
 * @param openApi the openAPI model
 */
private void processApplicationClasses(final AnnotationScannerContext context, OpenAPI openApi) {
    // Get all JaxRs applications and convert them to OpenAPI models (and merge them into a single one)
    Collection<ClassInfo> applications = context.getIndex().getAllKnownSubclasses(JaxRsConstants.APPLICATION);

    // this can be a useful extension point to set/override the application path
    processScannerExtensions(context, applications);

    for (ClassInfo classInfo : applications) {
        OpenAPI applicationOpenApi = processApplicationClass(context, classInfo);
        openApi = MergeUtil.merge(openApi, applicationOpenApi);
    }
}
 
Example 24
Source Project: smallrye-open-api   Source File: JaxRsAnnotationScanner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes a JAX-RS {@link Application} and creates an {@link OpenAPI} model. Performs
 * annotation scanning and other processing. Returns a model unique to that single JAX-RS
 * app.
 * 
 * @param applicationClass
 */
private OpenAPI processApplicationClass(final AnnotationScannerContext context, ClassInfo applicationClass) {
    OpenAPI openApi = new OpenAPIImpl();
    openApi.setOpenapi(OpenApiConstants.OPEN_API_VERSION);

    // Get the @ApplicationPath info and save it for later (also support @Path which seems nonstandard but common).
    AnnotationInstance applicationPathAnnotation = JandexUtil.getClassAnnotation(applicationClass,
            JaxRsConstants.APPLICATION_PATH);
    if (applicationPathAnnotation == null || context.getConfig().applicationPathDisable()) {
        applicationPathAnnotation = JandexUtil.getClassAnnotation(applicationClass, JaxRsConstants.PATH);
    }
    // TODO: Add support for Application selection when there are more than one
    if (applicationPathAnnotation != null) {
        this.currentAppPath = applicationPathAnnotation.value().asString();
    } else {
        this.currentAppPath = "/";
    }

    // Process @OpenAPIDefinition annotation
    processDefinitionAnnotation(context, applicationClass, openApi);

    // Process @SecurityScheme annotations
    processSecuritySchemeAnnotation(applicationClass, openApi);

    // Process @Server annotations
    processServerAnnotation(applicationClass, openApi);

    return openApi;
}
 
Example 25
Source Project: smallrye-open-api   Source File: JaxRsAnnotationScanner.java    License: Apache License 2.0 5 votes vote down vote up
private void processResourceClasses(final AnnotationScannerContext context, OpenAPI openApi) {
    // Now find all jax-rs endpoints
    Collection<ClassInfo> resourceClasses = getJaxRsResourceClasses(context.getIndex());
    for (ClassInfo resourceClass : resourceClasses) {
        processResourceClass(context, openApi, resourceClass, null);
    }
}
 
Example 26
@Test
public void testPermitAllWithoutGeneratedScheme() throws IOException {
    Index index = indexOf(RolesAllowedApp.class, RolesAllowedResource1.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    assertNull(result.getPaths().getPathItem("/v1/open").getGET().getSecurity());
}
 
Example 27
@Test
public void testNoEligibleScheme() throws IOException {
    Index index = indexOf(RolesNotAllowedApp.class, RolesAllowedResource1.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    List<SecurityRequirement> requirements = result.getPaths().getPathItem("/v1/locked").getGET().getSecurity();
    assertNull(requirements);
}
 
Example 28
Source Project: smallrye-open-api   Source File: ApiResponseTests.java    License: Apache License 2.0 5 votes vote down vote up
private static void test(String expectedResource, Class<?>... classes) throws IOException, JSONException {
    Index index = indexOf(classes);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(emptyConfig(), index);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    assertJsonEquals(expectedResource, result);
}
 
Example 29
/**
 * This test a basic, no OpenApi annotations, hello world GET service
 * 
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testBasicJaxRsGetDefinitionScanning() throws IOException, JSONException {
    Index i = indexOf(GreetingGetResource.class, Greeting.class);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(emptyConfig(), i);

    OpenAPI result = scanner.scan();

    printToConsole(result);
    assertJsonEquals("resource.testBasicJaxRsGetDefinitionScanning.json", result);
}
 
Example 30
Source Project: smallrye-open-api   Source File: AnnotationScanner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process tags.
 * Tag and Tags annotations combines with the resource tags we've already found (passed in)
 * 
 * @param method the REST method
 * @param openApi the OpenApi model
 * @param resourceTags tags passed in
 * @param operation the current operation
 */
default void processOperationTags(final MethodInfo method, OpenAPI openApi, Set<String> resourceTags,
        final Operation operation) {
    // 
    Set<String> tags = processTags(method, openApi, true);
    if (tags == null) {
        if (!resourceTags.isEmpty()) {
            operation.setTags(new ArrayList<>(resourceTags));
        }
    } else if (!tags.isEmpty()) {
        operation.setTags(new ArrayList<>(tags));
    }
}