Java Code Examples for org.eclipse.microprofile.openapi.models.media.Schema

The following examples show how to use org.eclipse.microprofile.openapi.models.media.Schema. 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: ParameterProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link Content} and use the scanned {@link javax.ws.rs.FormParam}s
 * as the properties. The media type will be defaulted to
 * 'application/x-www-form-urlencoded' or set to 'multipart/form-data' if a
 * RESTEasy {@link org.jboss.resteasy.annotations.providers.multipart.MultipartForm MultipartForm}
 * annotation was used to wrap the {@link javax.ws.rs.FormParam}s. The encoding values
 * for the {@link Content} will be set to the value of any
 * {@link org.jboss.resteasy.annotations.providers.multipart.PartType PartType}
 * annotations found for each parameter.
 *
 * @return generated form content
 */
private Content getFormBodyContent() {
    if (formParams.isEmpty()) {
        return null;
    }

    Content content = new ContentImpl();
    MediaType mediaType = new MediaTypeImpl();
    Schema schema = new SchemaImpl();
    Map<String, Encoding> encodings = new HashMap<>();
    schema.setType(SchemaType.OBJECT);

    mediaType.setSchema(schema);
    setSchemaProperties(schema, encodings, formParams);

    if (encodings.size() > 0) {
        mediaType.setEncoding(encodings);
    }

    String mediaTypeName = formMediaType != null ? formMediaType : APPLICATION_FORM_URLENCODED;
    content.addMediaType(mediaTypeName, mediaType);

    return content;
}
 
Example 2
Source Project: smallrye-open-api   Source File: DataObjectDeque.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create new entry and push to stack. Performs cycle detection.
 *
 * @param annotationTarget annotation target
 * @param parentPathEntry parent path entry
 * @param type the annotated type
 * @param schema the schema corresponding to this position
 */
public void push(AnnotationTarget annotationTarget,
        PathEntry parentPathEntry,
        Type type,
        Schema schema) {

    validateInput(parentPathEntry, type, schema);
    PathEntry entry = leafNode(parentPathEntry, annotationTarget, type, schema);
    ClassInfo klazzInfo = entry.getClazz();
    if (parentPathEntry.hasParent(entry)) {
        // Cycle detected, don't push path.
        DataObjectLogging.log.possibleCycle(klazzInfo);
        DataObjectLogging.log.path(entry.toStringWithGraph());
        if (schema.getDescription() == null) {
            schema.description("Cyclic reference to " + klazzInfo.name());
        }
    } else {
        // Push path to be inspected later.
        DataObjectLogging.log.addingChildNode(klazzInfo);
        path.push(entry);
    }
}
 
Example 3
Source Project: smallrye-open-api   Source File: BeanValidationScanner.java    License: Apache License 2.0 6 votes vote down vote up
void decimalMax(AnnotationTarget target, Schema schema) {
    AnnotationInstance constraint = getConstraint(target, BV_DECIMAL_MAX);

    if (constraint != null && schema.getMaximum() == null) {
        String decimalValue = stringValue(constraint, VALUE);
        try {
            BigDecimal decimal = new BigDecimal(decimalValue);
            schema.setMaximum(decimal);

            Optional<Boolean> inclusive = booleanValue(constraint, INCLUSIVE);

            if (schema.getExclusiveMaximum() == null && inclusive.isPresent() && !inclusive.get()) {
                schema.setExclusiveMaximum(Boolean.TRUE);
            }
        } catch (@SuppressWarnings("unused") NumberFormatException e) {
            DataObjectLogging.log.invalidAnnotationFormat(decimalValue);
        }
    }
}
 
Example 4
Source Project: microprofile-open-api   Source File: AirlinesOASFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public APIResponse filterAPIResponse(APIResponse apiResponse) {
    if("subscription successfully created".equals(apiResponse.getDescription())){
        apiResponse.setDescription("filterAPIResponse - subscription successfully created");
    }
    
    // testing child before parent filtering
    Content content = apiResponse.getContent();
    if (content != null) {
        if (content.hasMediaType("application/json")) {
            Schema schema = content.getMediaType("application/json").getSchema();
            if ("child - id of the new review".equals(schema.getDescription())) {
                schema.setDescription("parent - id of the new review");
            }
        }
    }
    
    return apiResponse;
}
 
Example 5
/**********************************************************************/

    @Test
    public void testArrayListNotNullAndNotEmptyAndMaxItems() {
        FieldInfo targetField = targetClass.field("arrayListNotNullAndNotEmptyAndMaxItems");
        Schema parentSchema = new SchemaImpl();
        String propertyKey = "TESTKEY";

        testTarget.notNull(targetField, schema, propertyKey, (target, name) -> {
            parentSchema.addRequired(name);
        });
        testTarget.sizeArray(targetField, schema);
        testTarget.notEmptyArray(targetField, schema);

        assertEquals(Boolean.FALSE, schema.getNullable());
        assertEquals(Integer.valueOf(1), schema.getMinItems());
        assertEquals(Integer.valueOf(20), schema.getMaxItems());
        assertEquals(Arrays.asList(propertyKey), parentSchema.getRequired());
    }
 
Example 6
Source Project: smallrye-open-api   Source File: SchemaFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Introspect into the given Class to generate a Schema model. The boolean indicates
 * whether this class type should be turned into a reference.
 *
 * @param index the index of classes being scanned
 * @param type the implementation type of the item to scan
 * @param schemaReferenceSupported
 */
static Schema readClassSchema(IndexView index, Type type, boolean schemaReferenceSupported) {
    if (type == null) {
        return null;
    }
    Schema schema;
    if (type.kind() == Type.Kind.ARRAY) {
        schema = new SchemaImpl().type(SchemaType.ARRAY);
        ArrayType array = type.asArrayType();
        int dimensions = array.dimensions();
        Type componentType = array.component();

        if (dimensions > 1) {
            // Recurse using a new array type with dimensions decremented
            schema.items(readClassSchema(index, ArrayType.create(componentType, dimensions - 1), schemaReferenceSupported));
        } else {
            // Recurse using the type of the array elements
            schema.items(readClassSchema(index, componentType, schemaReferenceSupported));
        }
    } else if (type.kind() == Type.Kind.PRIMITIVE) {
        schema = OpenApiDataObjectScanner.process(type.asPrimitiveType());
    } else {
        schema = introspectClassToSchema(index, type.asClassType(), schemaReferenceSupported);
    }
    return schema;
}
 
Example 7
Source Project: smallrye-open-api   Source File: TypeProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private Type resolveTypeVariable(Schema schema, Type fieldType) {
    // Type variable (e.g. A in Foo<A>)
    Type resolvedType = typeResolver.getResolvedType(fieldType);

    DataObjectLogging.log.resolvedType(fieldType, resolvedType);
    if (isTerminalType(resolvedType) || !index.containsClass(resolvedType)) {
        DataObjectLogging.log.terminalType(resolvedType);
        TypeUtil.applyTypeAttributes(resolvedType, schema);
    } else {
        DataObjectLogging.log.typeVarSubstitution(fieldType, resolvedType);
        if (index.containsClass(resolvedType)) {
            // Add resolved type to stack.
            objectStack.push(annotationTarget, parentPathEntry, resolvedType, schema);
        } else {
            DataObjectLogging.log.classNotAvailable(resolvedType);
        }
    }
    return resolvedType;
}
 
Example 8
Source Project: smallrye-open-api   Source File: SchemaFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads a Schema annotation into a model.
 *
 * @param index the index
 * @param annotation the annotation instance
 * @return Schema model
 */
public static Schema readSchema(IndexView index, AnnotationInstance annotation) {
    if (annotation == null) {
        return null;
    }
    IoLogging.log.singleAnnotation("@Schema");

    // Schemas can be hidden. Skip if that's the case.
    Optional<Boolean> isHidden = JandexUtil.booleanValue(annotation, SchemaConstant.PROP_HIDDEN);

    if (isHidden.isPresent() && isHidden.get()) {
        return null;
    }

    return readSchema(index, new SchemaImpl(), annotation, Collections.emptyMap());
}
 
Example 9
Source Project: smallrye-open-api   Source File: ParameterProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link Content} and use the scanned {@link javax.ws.rs.FormParam}s
 * as the properties. The media type will be defaulted to
 * 'application/x-www-form-urlencoded'
 *
 * @return generated form content
 */
private Content getFormBodyContent() {
    if (formParams.isEmpty()) {
        return null;
    }

    Content content = new ContentImpl();
    MediaType mediaType = new MediaTypeImpl();
    Schema schema = new SchemaImpl();
    Map<String, Encoding> encodings = new HashMap<>();
    schema.setType(SchemaType.OBJECT);

    mediaType.setSchema(schema);
    setSchemaProperties(schema, encodings, formParams);

    if (encodings.size() > 0) {
        mediaType.setEncoding(encodings);
    }

    // TODO: Do this for Spring ?
    //String mediaTypeName = formMediaType != null ? formMediaType : APPLICATION_FORM_URLENCODED;
    //content.addMediaType(mediaTypeName, mediaType);

    return content;
}
 
Example 10
Source Project: smallrye-open-api   Source File: BeanValidationScanner.java    License: Apache License 2.0 6 votes vote down vote up
void sizeArray(AnnotationTarget target, Schema schema) {
    AnnotationInstance constraint = getConstraint(target, BV_SIZE);

    if (constraint != null) {
        Integer min = intValue(constraint, "min");
        Integer max = intValue(constraint, "max");

        if (min != null && schema.getMinItems() == null) {
            schema.setMinItems(min);
        }

        if (max != null && schema.getMaxItems() == null) {
            schema.setMaxItems(max);
        }
    }
}
 
Example 11
Source Project: smallrye-open-api   Source File: BeanValidationScanner.java    License: Apache License 2.0 6 votes vote down vote up
void sizeString(AnnotationTarget target, Schema schema) {
    AnnotationInstance constraint = getConstraint(target, BV_SIZE);

    if (constraint != null) {
        Integer min = intValue(constraint, "min");
        Integer max = intValue(constraint, "max");

        if (min != null && schema.getMinLength() == null) {
            schema.setMinLength(min);
        }

        if (max != null && schema.getMaxLength() == null) {
            schema.setMaxLength(max);
        }
    }
}
 
Example 12
Source Project: smallrye-open-api   Source File: ModelUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the list of {@link Schema}s defined for the given {@link Parameter}.
 * A schema can be defined either via the parameter's "schema" property, or any
 * "content.*.schema" property.
 *
 * @param parameter Parameter
 * @return list of schemas, never null
 */
public static List<Schema> getParameterSchemas(Parameter parameter) {
    if (parameter.getSchema() != null) {
        return Arrays.asList(parameter.getSchema());
    }
    Map<String, MediaType> mediaTypes = getMediaTypesOrEmpty(parameter.getContent());
    if (!mediaTypes.isEmpty()) {
        List<Schema> schemas = new ArrayList<>(mediaTypes.size());

        for (MediaType mediaType : mediaTypes.values()) {
            if (mediaType.getSchema() != null) {
                schemas.add(mediaType.getSchema());
            }
        }
    }
    return Collections.emptyList();
}
 
Example 13
Source Project: smallrye-open-api   Source File: KitchenSinkTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testKitchenSinkWithRefs() throws IOException, JSONException {
    DotName name = componentize(KitchenSink.class.getName());
    Type type = ClassType.create(name, Type.Kind.CLASS);
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, type);
    OpenAPIImpl oai = new OpenAPIImpl();
    SchemaRegistry registry = SchemaRegistry.newInstance(nestingSupportConfig(), oai, index);

    Schema result = scanner.process();
    registry.register(type, result);

    printToConsole(oai);
    assertJsonEquals("refsEnabled.kitchenSink.expected.json", oai);
}
 
Example 14
private void testAssertion(Class<?> target, String expectedResourceName) throws IOException, JSONException {
    DotName name = componentize(target.getName());
    Type type = ClassType.create(name, Type.Kind.CLASS);
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, type);

    Schema result = scanner.process();
    registry.register(type, result);

    printToConsole(oai);
    assertJsonEquals(expectedResourceName, oai);
}
 
Example 15
private void testAssertion(Class<?> containerClass,
        String targetField,
        String expectedResourceName) throws IOException, JSONException {

    String containerName = containerClass.getName();
    Type parentType = getFieldFromKlazz(containerName, targetField).type();

    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, parentType);

    Schema result = scanner.process();
    registry.register(parentType, result);

    printToConsole(oai);
    assertJsonEquals(expectedResourceName, oai);
}
 
Example 16
Source Project: smallrye-open-api   Source File: IgnoreTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnore_jsonIgnorePropertiesOnField() throws IOException, JSONException {
    String name = IgnoreTestContainer.class.getName();
    FieldInfo fieldInfo = getFieldFromKlazz(name, "jipOnFieldTest");
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, fieldInfo, fieldInfo.type());

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "ignore.jsonIgnorePropertiesOnField.expected.json", result);
}
 
Example 17
Source Project: smallrye-open-api   Source File: SchemaFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Populates the schema using the {@link org.eclipse.microprofile.openapi.annotations.media.Schema @Schema}
 * on the provided class. If the schema has already been registered (in components), the existing
 * registration will be replaced.
 * 
 * @param index application class index
 * @param schema schema model to populate
 * @param annotation schema annotation to read
 * @param clazz the class annotated with {@link org.eclipse.microprofile.openapi.annotations.media.Schema @Schema}
 * @param defaults default values to be set on the schema when not present in the annotation
 * @return the schema, possibly replaced if <code>implementation</code> has been specified in the annotation
 */
static Schema readSchema(IndexView index,
        Schema schema,
        AnnotationInstance annotation,
        ClassInfo clazz,
        Map<String, Object> defaults) {

    if (annotation == null) {
        return schema;
    }

    // Schemas can be hidden. Skip if that's the case.
    Optional<Boolean> isHidden = JandexUtil.booleanValue(annotation, SchemaConstant.PROP_HIDDEN);

    if (isHidden.isPresent() && isHidden.get()) {
        return schema;
    }

    schema = readSchema(index, schema, annotation, defaults);
    ClassType clazzType = (ClassType) Type.create(clazz.name(), Type.Kind.CLASS);

    /*
     * The registry may already contain the type from earlier in the scan if the
     * type has been referenced as a field, etc. The schema here is "fuller" as it
     * now contains information gathered from the @Schema annotation on the class.
     * 
     * Ignore the reference returned by register, the caller expects the full schema.
     */
    schemaRegistration(index, clazzType, schema);

    return schema;
}
 
Example 18
Source Project: smallrye-open-api   Source File: IgnoreTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnore_jsonIgnoreType() throws IOException, JSONException {
    DotName name = DotName.createSimple(JsonIgnoreTypeExample.class.getName());
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index,
            ClassType.create(name, Type.Kind.CLASS));

    Schema result = scanner.process();

    printToConsole(name.local(), result);
    assertJsonEquals(name.local(), "ignore.jsonIgnoreType.expected.json", result);
}
 
Example 19
Source Project: smallrye-open-api   Source File: IgnoreTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnore_schemaHiddenField() throws IOException, JSONException {
    DotName name = DotName.createSimple(IgnoreSchemaOnFieldExample.class.getName());
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index,
            ClassType.create(name, Type.Kind.CLASS));

    Schema result = scanner.process();

    printToConsole(name.local(), result);
    assertJsonEquals(name.local(), "ignore.schemaHiddenField.expected.json", result);
}
 
Example 20
/**
 * Build the Schema
 *
 * @return the OAI schema
 */
Schema process() {
    ScannerLogging.log.startProcessing(rootClassType.name());

    // If top level item is simple
    if (TypeUtil.isTerminalType(rootClassType)) {
        SchemaImpl simpleSchema = new SchemaImpl();
        TypeUtil.applyTypeAttributes(rootClassType, simpleSchema);
        return simpleSchema;
    }

    if (isA(rootClassType, ENUM_TYPE) && index.containsClass(rootClassType)) {
        return SchemaFactory.enumToSchema(index, rootClassType);
    }

    // If top level item is not indexed
    if (rootClassInfo == null && objectStack.isEmpty()) {
        // If there's something on the objectStack stack then pre-scanning may have found something.
        return new SchemaImpl().type(SchemaType.OBJECT);
    }

    // Create root node.
    DataObjectDeque.PathEntry root = objectStack.rootNode(rootAnnotationTarget, rootClassInfo, rootClassType, rootSchema);

    // For certain special types (map, list, etc) we need to do some pre-processing.
    if (isSpecialType(rootClassType)) {
        resolveSpecial(root, rootClassType);
    } else {
        objectStack.push(root);
    }

    depthFirstGraphSearch();
    return rootSchema;
}
 
Example 21
Source Project: smallrye-open-api   Source File: SchemaReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link Schema} OpenAPI nodes.
 * 
 * @param node map of schema json nodes
 * @return Map of Schema model
 */
public static Optional<Map<String, Schema>> readSchemas(final JsonNode node) {
    if (node != null && node.isObject()) {
        Map<String, Schema> models = new LinkedHashMap<>();
        for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
            String fieldName = fieldNames.next();
            JsonNode childNode = node.get(fieldName);
            models.put(fieldName, readSchema(childNode));
        }
        return Optional.of(models);
    }
    return Optional.empty();
}
 
Example 22
private String createReference(Reference<?> r, String v) {
    final StringBuilder sb = new StringBuilder();
    if (r instanceof APIResponse) {
        sb.append("#/components/responses/");
    }
    else if (r instanceof Callback) {
        sb.append("#/components/callbacks/");
    }
    else if (r instanceof Example) {
        sb.append("#/components/examples/");
    }
    else if (r instanceof Header) {
        sb.append("#/components/headers/");
    }
    else if (r instanceof Link) {
        sb.append("#/components/links/");
    }
    else if (r instanceof Parameter) {
        sb.append("#/components/parameters/");
    }
    else if (r instanceof PathItem) {
        sb.append("http://www.abc.def.ghi/");
    }
    else if (r instanceof RequestBody) {
        sb.append("#/components/requestBodies/");
    }
    else if (r instanceof Schema) {
        sb.append("#/components/schemas/");
    }
    else if (r instanceof SecurityScheme) {
        sb.append("#/components/securitySchemes/");
    }
    sb.append(v);
    return sb.toString();
}
 
Example 23
Source Project: smallrye-open-api   Source File: BeanValidationScanner.java    License: Apache License 2.0 5 votes vote down vote up
private static void applyObjectConstraints(AnnotationTarget target,
        Schema schema,
        String propertyKey,
        RequirementHandler handler) {
    INSTANCE.notNull(target, schema, propertyKey, handler);
    INSTANCE.sizeObject(target, schema);
    INSTANCE.notEmptyObject(target, schema);
}
 
Example 24
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unresolvable type parameter.
 */
@Test
public void testCycle() throws IOException, JSONException {
    DotName buzz = createSimple(BuzzLinkedList.class.getName());
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, ClassType.create(buzz, Type.Kind.CLASS));

    Schema result = scanner.process();

    printToConsole(buzz.local(), result);
    assertJsonEquals(buzz.local(), "cycle.expected.json", result);
}
 
Example 25
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRequiredEnum() throws IOException, JSONException {
    DotName baz = createSimple(EnumRequiredContainer.class.getName());
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, ClassType.create(baz, Type.Kind.CLASS));

    Schema result = scanner.process();

    printToConsole(baz.local(), result);
    assertJsonEquals(baz.local(), "enumRequired.expected.json", result);
}
 
Example 26
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexNestedGenerics() throws IOException, JSONException {
    String name = GenericTypeTestContainer.class.getName();
    Type pType = getFieldFromKlazz(name, "complexNesting").type();
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, pType);

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "generic.complexNesting.expected.json", result);
}
 
Example 27
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexInheritanceGenerics() throws IOException, JSONException {
    String name = GenericTypeTestContainer.class.getName();
    Type pType = getFieldFromKlazz(name, "complexInheritance").type();
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, pType);

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "generic.complexInheritance.expected.json", result);
}
 
Example 28
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void genericFieldTest() throws IOException, JSONException {
    String name = GenericTypeTestContainer.class.getName();
    Type pType = getFieldFromKlazz(name, "genericContainer").type();
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, pType);

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "generic.fields.expected.json", result);
}
 
Example 29
Source Project: smallrye-open-api   Source File: ExpectationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void fieldNameOverrideTest() throws IOException, JSONException {
    String name = GenericTypeTestContainer.class.getName();
    Type pType = getFieldFromKlazz(name, "overriddenNames").type();
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, pType);

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "generic.fields.overriddenNames.expected.json", result);
}
 
Example 30
Source Project: smallrye-open-api   Source File: SpecialCaseTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCollection_SimpleTerminalType() throws IOException, JSONException {
    String name = SpecialCaseTestContainer.class.getName();
    Type pType = getFieldFromKlazz(name, "listOfString").type();
    OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, pType);

    Schema result = scanner.process();

    printToConsole(name, result);
    assertJsonEquals(name, "special.simple.expected.json", result);
}