Java Code Examples for io.swagger.v3.oas.models.media.Schema#setType()

The following examples show how to use io.swagger.v3.oas.models.media.Schema#setType() . 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: ComponentSchemaTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
public Schema transformSimpleSchema(Class<?> clazz, Map<String, InheritanceInfo> inheritanceMap) {
      if (clazz.isEnum()) {
          return schemaGeneratorHelper.createEnumSchema(clazz.getEnumConstants());
      }
      List<String> requiredFields = new ArrayList<>();

      Schema<?> schema = new Schema<>();
      schema.setType("object");
      schema.setProperties(getClassProperties(clazz, requiredFields));
schemaGeneratorHelper.enrichWithTypeAnnotations(schema, clazz.getDeclaredAnnotations());

      updateRequiredFields(schema, requiredFields);

      if (inheritanceMap.containsKey(clazz.getName())) {
          Discriminator discriminator = createDiscriminator(inheritanceMap.get(clazz.getName()));
          schema.setDiscriminator(discriminator);
          enrichWithDiscriminatorProperty(schema, discriminator);
      }
      if (clazz.getSuperclass() != null) {
          return traverseAndAddProperties(schema, inheritanceMap, clazz.getSuperclass(), clazz);
      }
      return schema;
  }
 
Example 2
Source File: SwaggerAnnotationUtils.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
public static Schema getSchemaFromAnnotation(io.swagger.v3.oas.annotations.media.Schema schema) {
  if (schema == null) {
    return null;
  }
  Schema schemaObj = new Schema();
  schemaObj.setName(schema.name());
  schemaObj.setDescription(schema.description());
  schemaObj.setType(schema.type());
  schemaObj.setTitle(schema.title());
  schemaObj.setNullable(schema.nullable());
  schemaObj.setDefault(schema.defaultValue());
  schemaObj.setFormat(schema.format());
  schemaObj.setDeprecated(schema.deprecated());
  Map<String, Object> extensionsFromAnnotation = getExtensionsFromAnnotation(schema.extensions());
  schemaObj.extensions(extensionsFromAnnotation);
  return schemaObj;
}
 
Example 3
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve schema from type schema.
 *
 * @param schemaImplementation the schema implementation
 * @param components the components
 * @param jsonView the json view
 * @param annotations the annotations
 * @return the schema
 */
public static Schema resolveSchemaFromType(Class<?> schemaImplementation, Components components,
		JsonView jsonView, Annotation[] annotations) {
	Schema schemaObject = extractSchema(components, schemaImplementation, jsonView, annotations);
	if (schemaObject != null && StringUtils.isBlank(schemaObject.get$ref())
			&& StringUtils.isBlank(schemaObject.getType()) && !(schemaObject instanceof ComposedSchema)) {
		// default to string
		schemaObject.setType("string");
	}
	return schemaObject;
}
 
Example 4
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);

    //post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);

    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);

    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);

    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);

    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);

    //add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);

    openAPI.setPaths(paths);
}
 
Example 5
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private Schema convertFileSchema(Schema schema) {
    if ("file".equals(schema.getType())) {
        schema.setType("string");
        schema.setFormat("binary");
    }

    return schema;
}
 
Example 6
Source File: BodyGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static void resolveNotSchema(Schema<?> schema) {
    if (schema.getNot().getType().equals("string")) {
        schema.setType("integer");
    } else {
        schema.setType("string");
    }
}
 
Example 7
Source File: BodyGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public String generate(Schema<?> schema) {
    if (schema == null) {
        return "";
    }

    boolean isArray = schema instanceof ArraySchema;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Generate body for object " + schema.getName());
    }

    if (isArray) {
        return generateFromArraySchema((ArraySchema) schema);
    }

    @SuppressWarnings("rawtypes")
    Map<String, Schema> properties = schema.getProperties();
    if (properties != null) {
        return generateFromObjectSchema(properties);
    } else if (schema.getAdditionalProperties() instanceof Schema) {
        return generate((Schema<?>) schema.getAdditionalProperties());
    }

    if (schema instanceof ComposedSchema) {
        return generateJsonPrimitiveValue(resolveComposedSchema((ComposedSchema) schema));
    }
    if (schema.getNot() != null) {
        resolveNotSchema(schema);
    }

    // primitive type, or schema without properties
    if (schema.getType() == null || schema.getType().equals("object")) {
        schema.setType("string");
    }

    return generateJsonPrimitiveValue(schema);
}
 
Example 8
Source File: SchemaBuilder.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns a new schema of the given type.
 */
private static Schema<?> createSchema( String type)
  {
  Schema<?> schema =
    "array".equals( type)
    ? new ArraySchema()
    : new Schema<Object>();

  schema.setType( type);

  return schema;
  }
 
Example 9
Source File: Reader.java    From proteus with Apache License 2.0 5 votes vote down vote up
public Reader()
	{
// Json.mapper().addMixIn(ServerRequest.class, ServerRequestMixIn.class);

		this.openAPI = new OpenAPI();
		paths = new Paths();
		openApiTags = new LinkedHashSet<>();
		components = new Components();
		stringSchema = new Schema();
		stringSchema.setType("string");

	}
 
Example 10
Source File: JavaTimeOperationCustomizer.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {
	if (handlerMethod.getReturnType().getParameterType().isAssignableFrom(Duration.class)) {
		for (Map.Entry<String, io.swagger.v3.oas.models.responses.ApiResponse> entry:  operation.getResponses().entrySet()) {
			io.swagger.v3.oas.models.responses.ApiResponse response = entry.getValue();
			Content content = response.getContent();
			if (content.containsKey(MediaType.APPLICATION_JSON_VALUE)) {
				Schema schema = content.get(MediaType.APPLICATION_JSON_VALUE).getSchema();
				schema.getProperties().clear();
				schema.setType("string");
			}
		}
	}
	return operation;
}
 
Example 11
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private Map<String, Header> createHeaderResponse(com.github.jrcodeza.Header[] headers) {
	Map<String, Header> responseHeaders = new HashMap<>();
	for (com.github.jrcodeza.Header headerAnnotation : headers) {
		Schema<?> schema = new Schema<>();
		schema.setType("string");

		Header oasHeader = new Header();
		oasHeader.setDescription(headerAnnotation.description());
		oasHeader.setSchema(schema);
		responseHeaders.put(headerAnnotation.name(), oasHeader);
	}
	return responseHeaders;
}
 
Example 12
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 5 votes vote down vote up
protected Schema createNumberSchema(String type, String format, Annotation[] annotations) {
    Schema<?> schema = new Schema<>();
    schema.setType(type);
    schema.setFormat(format);
    asList(annotations).forEach(annotation -> applyNumberAnnotation(schema, annotation));
    return schema;
}
 
Example 13
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 5 votes vote down vote up
@SuppressWarnings("squid:S1192") // better in-place defined for better readability
protected Schema createStringSchema(String format, Annotation[] annotations) {
    Schema<?> schema = new Schema<>();
    schema.setType("string");
    if (StringUtils.isNotBlank(format)) {
        schema.setFormat(format);
    }
    if (annotations != null) {
        asList(annotations).forEach(annotation -> applyStringAnnotations(schema, annotation));
    }
    return schema;
}
 
Example 14
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 5 votes vote down vote up
public MediaType createMediaType(Class<?> requestBodyParameter,
                                 String parameterName,
                                 List<Class<?>> genericParams) {
    Schema<?> rootMediaSchema = new Schema<>();
    if (isFile(requestBodyParameter)) {
        Schema<?> fileSchema = new Schema<>();
        fileSchema.setType("string");
        fileSchema.setFormat("binary");

        if (parameterName == null) {
            rootMediaSchema = fileSchema;
        } else {
            Map<String, Schema> properties = new HashMap<>();
            properties.put(parameterName, fileSchema);
            rootMediaSchema.setType("object");
            rootMediaSchema.setProperties(properties);
        }
    } else if (isList(requestBodyParameter, genericParams)) {
        rootMediaSchema = parseArraySignature(getFirstOrNull(genericParams), null, new Annotation[]{});
    } else if (!StringUtils.equalsIgnoreCase(requestBodyParameter.getSimpleName(), "void")) {
        if (isInPackagesToBeScanned(requestBodyParameter, modelPackages)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + requestBodyParameter.getSimpleName());
        } else if (requestBodyParameter.isAssignableFrom(ResponseEntity.class) && !CollectionUtils.isEmpty(genericParams)
                && !genericParams.get(0).isAssignableFrom(Void.class)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + genericParams.get(0).getSimpleName());
        } else {
            return null;
        }
    } else {
        return null;
    }

    MediaType mediaType = new MediaType();
    mediaType.setSchema(rootMediaSchema);
    return mediaType;
}
 
Example 15
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Schema mergeSchema(Schema thisSchema, Schema thatSchema) {
  if (thatSchema == null) {
    return thisSchema;
  }
  // Overwriting `implementation` is explicitly disallowed
  // Overwriting `not` is explicitly disallowed
  // Overwriting `oneOf` is explicitly disallowed
  // Overwriting `anyOf` is explicitly disallowed
  // Overwriting `allOf` is explicitly disallowed
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getTitle() != null) {
    thisSchema.setTitle(thatSchema.getTitle());
  }
  // Overwriting `multipleOf` is explicitly disallowed
  if (thatSchema.getMaximum() != null) {
    thisSchema.setMaximum(thatSchema.getMaximum());
  }
  if (thatSchema.getExclusiveMaximum() != null) {
    thisSchema.setExclusiveMaximum(thatSchema.getExclusiveMaximum());
  }

  if (thatSchema.getMinimum() != null) {
    thisSchema.setMinimum(thatSchema.getMinimum());
  }
  if (thatSchema.getExclusiveMinimum() != null) {
    thisSchema.setExclusiveMinimum(thatSchema.getExclusiveMinimum());
  }
  if (thatSchema.getMaxLength() != null) {
    thisSchema.setMaxLength(thatSchema.getMaxLength());
  }
  if (thatSchema.getMinLength() != null) {
    thisSchema.setMinLength(thatSchema.getMinLength());
  }
  if (thatSchema.getPattern() != null) {
    thisSchema.setPattern(thatSchema.getPattern());
  }
  if (thatSchema.getMaxProperties() != null) {
    thisSchema.setMaxProperties(thatSchema.getMaxProperties());
  }
  if (thatSchema.getMinProperties() != null) {
    thisSchema.setMinProperties(thatSchema.getMinProperties());
  }
  // RequiredProperties
  if (thatSchema.getRequired() != null) {
    thisSchema.setRequired(thatSchema.getRequired());
  }
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getDescription() != null) {
    thisSchema.setDescription(thatSchema.getDescription());
  }
  if (thatSchema.getFormat() != null) {
    thisSchema.setFormat(thatSchema.getFormat());
  }
  // Overwriting `ref` is explicitly disallowed
  if (thatSchema.getNullable() != null) {
    thisSchema.setNullable(thatSchema.getNullable());
  }
  // Overwriting `AccessMode` is explicitly disallowed
  if (thatSchema.getExample() != null) {
    thisSchema.setExample(thatSchema.getExample());
  }
  if (thatSchema.getExternalDocs() != null) {
    thisSchema.setExternalDocs(thatSchema.getExternalDocs());
  }
  if (thatSchema.getDeprecated() != null) {
    thisSchema.setDeprecated(thatSchema.getDeprecated());
  }
  if (thatSchema.getType() != null) {
    thisSchema.setType(thatSchema.getType());
  }
  if (thatSchema.getEnum() != null) {
    thisSchema.setEnum(thatSchema.getEnum());
  }
  if (thatSchema.getDefault() != null) {
    thisSchema.setDefault(thatSchema.getDefault());
  }
  // Overwriting `discriminator` is explicitly disallowed
  // Overwriting `hidden` is explicitly disallowed
  // Overwriting `subTypes` is explicitly disallowed
  if (thatSchema.getExtensions() != null) {
    thisSchema.setExtensions(thatSchema.getExtensions());
  }
  return thisSchema;
}
 
Example 16
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 4 votes vote down vote up
@SuppressWarnings("squid:S1192") // better in-place defined for better readability
protected Schema createBooleanSchema() {
    Schema<?> schema = new Schema<>();
    schema.setType("boolean");
    return schema;
}
 
Example 17
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 4 votes vote down vote up
private Schema<?> createObjectSchema() {
    Schema<?> schema = new Schema<>();
    schema.setType("object");
    return schema;
}
 
Example 18
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public Schema createModelFromProperty(Schema schema, String path) {
    String description = schema.getDescription();
    String example = null;
    List<String> requiredList = schema.getRequired();


    Object obj = schema.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    String name = schema.getName();
    XML xml = schema.getXml();
    Map<String, Schema> properties = schema.getProperties();


    if (schema instanceof ComposedSchema && this.flattenComposedSchemas){
        ComposedSchema composedModel = (ComposedSchema) schema;

        composedModel.setDescription(description);
        composedModel.setExample(example);
        composedModel.setName(name);
        composedModel.setXml(xml);
        composedModel.setType(schema.getType());
        composedModel.setRequired(requiredList);

        return composedModel;


    } else {
        Schema model = new Schema();//TODO Verify this!
        model.setDescription(description);
        model.setExample(example);
        model.setName(name);
        model.setXml(xml);
        model.setType(schema.getType());
        model.setRequired(requiredList);

        if (properties != null) {
            flattenProperties(properties, path);
            model.setProperties(properties);
        }

        return model;
    }
}