Java Code Examples for io.swagger.v3.oas.models.parameters.Parameter

The following examples show how to use io.swagger.v3.oas.models.parameters.Parameter. 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
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  Parameter oasObject) {

  if (StringUtils.isNotBlank(oasObject.get$ref())) {
    return emptyList();
  }

  if (!"cookie".equalsIgnoreCase(oasObject.getIn())) {
    return emptyList();
  }

  if (!isMatchCase(expectedCase, oasObject.getName())) {
    return singletonList(new OasViolation(location.property("name"), ERROR + expectedCase));
  }
  return emptyList();
}
 
Example 2
Source Project: swagger-parser   Source File: OpenAPIResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve top-level responses")
public void testSharedResponses() {
    final OpenAPI swagger = new OpenAPI();
    List<Parameter> parameters = new ArrayList<>();
    parameters.add(0,new Parameter().$ref("username"));
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(parameters)
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse().$ref("#/components/responses/foo")))));

    swagger.components(new Components().addResponses("foo", new ApiResponse().description("ok!")));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    ApiResponse response = resolved.getPaths().get("/fun").getGet().getResponses().get("200");
    assertTrue(response.getDescription().equals("ok!"));
    assertTrue(response instanceof ApiResponse);
}
 
Example 3
Source Project: swagger-inflector   Source File: StringTypeValidator.java    License: Apache License 2.0 6 votes vote down vote up
public void validate(Object argument, Parameter parameter, Iterator<Validator> chain) throws ValidationException {
    if(argument != null && parameter.getSchema() != null ) {
        Set<String> allowable = validateAllowedValues(argument, parameter.getSchema());
        if(allowable!= null){
            throw new ValidationException()
                .message(new ValidationMessage()
                        .code(ValidationError.UNACCEPTABLE_VALUE)
                        .message(parameter.getIn() + " parameter `" + parameter.getName() + "` value `" + argument + "` is not in the allowable values `" + allowable + "`"));
        }

        if(validateFormat(argument,parameter.getSchema())){
            throw new ValidationException()
                .message(new ValidationMessage()
                        .code(ValidationError.INVALID_FORMAT)
                        .message(parameter.getIn() + " parameter `" + parameter.getName() + " value `" + argument + "` is not a valid " + parameter.getSchema().getFormat()));
        }

    }
    if(chain.hasNext()) {
        chain.next().validate(argument, parameter, chain);
        return;
    }

    return;
}
 
Example 4
Source Project: swagger-parser   Source File: OpenAPIV3ParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCodegenPetstore() {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    final OpenAPI openAPI = parser.read("src/test/resources/petstore-codegen.yaml");
    Schema enumModel =  openAPI.getComponents().getSchemas().get("Enum_Test");
    assertNotNull(enumModel);
    Schema enumProperty = (Schema)enumModel.getProperties().get("enum_integer");
    assertNotNull(enumProperty);

    assertTrue(enumProperty instanceof IntegerSchema);
    IntegerSchema enumIntegerProperty = (IntegerSchema) enumProperty;
    List<Number> integers =  enumIntegerProperty.getEnum();
    assertEquals(integers.get(0), new Integer(1));
    assertEquals(integers.get(1), new Integer(-1));

    Operation getOrderOperation = openAPI.getPaths().get("/store/order/{orderId}").getGet();
    assertNotNull(getOrderOperation);
    Parameter orderId = getOrderOperation.getParameters().get(0);
    assertTrue(orderId instanceof PathParameter);
    PathParameter orderIdPathParam = (PathParameter) orderId;
    assertNotNull(orderIdPathParam.getSchema().getMinimum());

    BigDecimal minimum = orderIdPathParam.getSchema().getMinimum();
    assertEquals(minimum.toString(), "1");
}
 
Example 5
Source Project: swagger-parser   Source File: PathsProcessor.java    License: Apache License 2.0 6 votes vote down vote up
protected void updateLocalRefs(Parameter param, String pathRef) {
    if (param.get$ref() != null){
        if(isLocalRef(param.get$ref())) {
            param.set$ref(computeLocalRef(param.get$ref(), pathRef));
        }
    }
    if(param.getSchema() != null) {
        updateLocalRefs(param.getSchema(), pathRef);
    }
    if(param.getContent() != null) {
        Map<String, MediaType> content = param.getContent();
        for (String key: content.keySet()) {
            MediaType mediaType = content.get(key);
            if (mediaType.getSchema() != null) {
                updateLocalRefs(mediaType.getSchema(), pathRef);
            }
        }
    }

}
 
Example 6
@Override
protected List<OasDiffViolation> validateCompare(OasDiffValidationContext context,
  OasObjectPropertyLocation leftLocation, Parameter leftOasObject, OasObjectPropertyLocation rightLocation,
  Parameter rightOasObject) {


  if (ChangeRangeCheckUtils.isNotViolated(
    defaultIfNull(leftOasObject.getAllowEmptyValue(), Boolean.FALSE),
    defaultIfNull(rightOasObject.getAllowEmptyValue(), Boolean.FALSE),
    singletonList(new Object[] { false, true }))) {
    return emptyList();
  }

  String message = new StringBuilder()
    .append(ParameterUtils.getKeyString(rightOasObject))
    .append(':')
    .append(DiffViolationMessages.FALSE_TO_TRUE)
    .toString();

  return singletonList(new OasDiffViolation(
    leftLocation.property("allowEmptyValue"),
    rightLocation.property("allowEmptyValue"),
    message
  ));

}
 
Example 7
@Override
protected List<OasDiffViolation> validateCompare(OasDiffValidationContext context,
  OasObjectPropertyLocation leftLocation, Parameter leftOasObject, OasObjectPropertyLocation rightLocation,
  Parameter rightOasObject) {

  if (ChangeRangeCheckUtils.isNotViolated(
    defaultIfNull(leftOasObject.getRequired(), Boolean.FALSE),
    defaultIfNull(rightOasObject.getRequired(), Boolean.FALSE),
    singletonList(new Object[] { true, false }))) {
    return emptyList();
  }

  String message = new StringBuilder()
    .append(ParameterUtils.getKeyString(rightOasObject))
    .append(':')
    .append(DiffViolationMessages.TRUE_TO_FALSE)
    .toString();

  return singletonList(new OasDiffViolation(
    leftLocation.property("required"),
    rightLocation.property("required"),
    message
  ));

}
 
Example 8
Source Project: swagger-parser   Source File: CallbackProcessor.java    License: Apache License 2.0 6 votes vote down vote up
public void processCallback(Callback callback) {
    if (callback.get$ref() != null){
        processReferenceCallback(callback);
    }
    //Resolver PathItem
    for(String name : callback.keySet()){
        PathItem pathItem = callback.get(name);
        final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap();

        for (PathItem.HttpMethod httpMethod : operationMap.keySet()) {
            Operation operation = operationMap.get(httpMethod);
            operationProcessor.processOperation(operation);
        }

        List<Parameter> parameters = pathItem.getParameters();
        if (parameters != null) {
            for (Parameter parameter: parameters){
                parameterProcessor.processParameter(parameter);
            }
        }
    }
}
 
Example 9
Source Project: swagger-inflector   Source File: ReflectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
public JavaType getTypeFromParameter(Parameter parameter, Map<String, Schema> definitions) {
    if (parameter.getSchema() != null) {
        JavaType parameterType =  getTypeFromProperty(parameter.getSchema().getType(),parameter.getSchema().getFormat(), parameter.getSchema(), definitions);
        if (parameterType != null){
            return parameterType;
        }
    }

    else if (parameter.getContent() != null) {
        Map<String,MediaType> content   = parameter.getContent();
        for (String mediaType : content.keySet()){
            if (content.get(mediaType).getSchema() != null) {
                Schema model = content.get(mediaType).getSchema();
                return getTypeFromModel("", model, definitions);
            }
        }
    }
    return null;
}
 
Example 10
Source Project: springdoc-openapi   Source File: AbstractOpenApiResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fill parameters list.
 *
 * @param operation the operation
 * @param queryParams the query params
 * @param methodAttributes the method attributes
 */
private void fillParametersList(Operation operation, Map<String, String> queryParams, MethodAttributes methodAttributes) {
	List<Parameter> parametersList = operation.getParameters();
	if (parametersList == null)
		parametersList = new ArrayList<>();
	Collection<Parameter> headersMap = AbstractRequestBuilder.getHeaders(methodAttributes, new LinkedHashMap<>());
	parametersList.addAll(headersMap);
	if (!CollectionUtils.isEmpty(queryParams)) {
		for (Map.Entry<String, String> entry : queryParams.entrySet()) {
			io.swagger.v3.oas.models.parameters.Parameter parameter = new io.swagger.v3.oas.models.parameters.Parameter();
			parameter.setName(entry.getKey());
			parameter.setSchema(new StringSchema()._default(entry.getValue()));
			parameter.setRequired(true);
			parameter.setIn(ParameterIn.QUERY.toString());
			GenericParameterBuilder.mergeParameter(parametersList, parameter);
		}
		operation.setParameters(parametersList);
	}
}
 
Example 11
Source Project: proteus   Source File: Reader.java    License: Apache License 2.0 6 votes vote down vote up
protected Optional<List<Parameter>> getParametersListFromAnnotation(io.swagger.v3.oas.annotations.Parameter[] parameters, Consumes classConsumes, Consumes methodConsumes,
																	Operation operation, JsonView jsonViewAnnotation)
{
	if (parameters == null)
	{
		return Optional.empty();
	}
	List<Parameter> parametersObject = new ArrayList<>();
	for (io.swagger.v3.oas.annotations.Parameter parameter : parameters)
	{

		ResolvedParameter resolvedParameter = getParameters(
															ParameterProcessor.getParameterType(parameter), Collections.singletonList(parameter), operation, classConsumes,
															methodConsumes, jsonViewAnnotation);
		parametersObject.addAll(resolvedParameter.parameters);
	}
	if (parametersObject.size() == 0)
	{
		return Optional.empty();
	}
	return Optional.of(parametersObject);
}
 
Example 12
Source Project: springdoc-openapi   Source File: AbstractRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build param parameter.
 *
 * @param parameterInfo the parameter info
 * @param components the components
 * @param requestInfo the request info
 * @param jsonView the json view
 * @return the parameter
 */
private Parameter buildParam(ParameterInfo parameterInfo, Components components, RequestInfo requestInfo,
		JsonView jsonView) {
	Parameter parameter;
	String pName = parameterInfo.getpName();
	String name = StringUtils.isBlank(requestInfo.value()) ? pName : requestInfo.value();
	parameterInfo.setpName(name);

	if (!ValueConstants.DEFAULT_NONE.equals(requestInfo.defaultValue()))
		parameter = this.buildParam(requestInfo.type(), components, parameterInfo, false,
				requestInfo.defaultValue(), jsonView);
	else
		parameter = this.buildParam(requestInfo.type(), components, parameterInfo, requestInfo.required(), null,
				jsonView);
	return parameter;
}
 
Example 13
Source Project: openapi-diff   Source File: HtmlRender.java    License: Apache License 2.0 6 votes vote down vote up
private ContainerTag li_changedParam(ChangedParameter changeParam) {
  if (changeParam.isDeprecated()) {
    return li_deprecatedParam(changeParam);
  }
  boolean changeRequired = changeParam.isChangeRequired();
  boolean changeDescription = changeParam.getDescription().isDifferent();
  Parameter rightParam = changeParam.getNewParameter();
  Parameter leftParam = changeParam.getNewParameter();
  ContainerTag li = li().withText(changeParam.getName() + " in " + changeParam.getIn());
  if (changeRequired) {
    li.withText(" change into " + (rightParam.getRequired() ? "required" : "not required"));
  }
  if (changeDescription) {
    li.withText(" Notes ")
        .with(del(leftParam.getDescription()).withClass("comment"))
        .withText(" change into ")
        .with(span(rightParam.getDescription()).withClass("comment"));
  }
  return li;
}
 
Example 14
Source Project: springdoc-openapi   Source File: GenericParameterBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets examples.
 *
 * @param parameterDoc the parameter doc
 * @param parameter the parameter
 */
private void setExamples(io.swagger.v3.oas.annotations.Parameter parameterDoc, Parameter parameter) {
	Map<String, Example> exampleMap = new HashMap<>();
	if (parameterDoc.examples().length == 1 && StringUtils.isBlank(parameterDoc.examples()[0].name())) {
		Optional<Example> exampleOptional = AnnotationsUtils.getExample(parameterDoc.examples()[0]);
		exampleOptional.ifPresent(parameter::setExample);
	}
	else {
		for (ExampleObject exampleObject : parameterDoc.examples()) {
			AnnotationsUtils.getExample(exampleObject)
					.ifPresent(example -> exampleMap.put(exampleObject.name(), example));
		}
	}
	if (exampleMap.size() > 0) {
		parameter.setExamples(exampleMap);
	}
}
 
Example 15
Source Project: springdoc-openapi   Source File: DataRestRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add parameters.
 *
 * @param openAPI the open api
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param methodParameter the method parameter
 * @param parameterInfo the parameter info
 * @param parameter the parameter
 */
private void addParameters(OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, MethodParameter methodParameter, ParameterInfo parameterInfo, Parameter parameter) {
	List<Annotation> parameterAnnotations = Arrays.asList(methodParameter.getParameterAnnotations());
	if (requestBuilder.isValidParameter(parameter)) {
		requestBuilder.applyBeanValidatorAnnotations(parameter, parameterAnnotations);
		operation.addParametersItem(parameter);
	}
	else if (!RequestMethod.GET.equals(requestMethod)) {
		RequestBodyInfo requestBodyInfo = new RequestBodyInfo();
		if (operation.getRequestBody() != null)
			requestBodyInfo.setRequestBody(operation.getRequestBody());
		requestBodyBuilder.calculateRequestBodyInfo(openAPI.getComponents(), methodAttributes,
				parameterInfo, requestBodyInfo);
		requestBuilder.applyBeanValidatorAnnotations(requestBodyInfo.getRequestBody(), parameterAnnotations, methodParameter.isOptional());
		operation.setRequestBody(requestBodyInfo.getRequestBody());
	}
}
 
Example 16
Source Project: openapi-generator   Source File: ScalaGatlingCodegen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates all the necessary openapi vendor extensions and feeder files for gatling
 *
 * @param operation     OpoenAPI Operation
 * @param parameters    OpenAPI Parameters
 * @param parameterType OpenAPI Parameter Type
 */
private void prepareGatlingData(Operation operation, Set<Parameter> parameters, String parameterType) {
    if (parameters.size() > 0) {
        List<String> parameterNames = new ArrayList<>();
        List<Object> vendorList = new ArrayList<>();
        for (Parameter parameter : parameters) {
            Map<String, Object> extensionMap = new HashMap<>();
            extensionMap.put("gatlingParamName", parameter.getName());
            extensionMap.put("gatlingParamValue", "${" + parameter.getName() + "}");
            vendorList.add(extensionMap);
            parameterNames.add(parameter.getName());
        }
        operation.addExtension("x-gatling-" + parameterType.toLowerCase(Locale.ROOT) + "-params", vendorList);
        operation.addExtension("x-gatling-" + parameterType.toLowerCase(Locale.ROOT) + "-feeder", operation.getOperationId() + parameterType.toUpperCase(Locale.ROOT) + "Feeder");
        try {
            FileUtils.writeStringToFile(
                new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + parameterType.toLowerCase(Locale.ROOT) + "Params.csv"),
                StringUtils.join(parameterNames, ","),
                StandardCharsets.UTF_8
            );
        } catch (IOException ioe) {
            LOGGER.error("Could not create feeder file for operationId" + operation.getOperationId(), ioe);
        }
    }
}
 
Example 17
Source Project: zap-extensions   Source File: DataGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static String generateDefaultValue(Parameter parameter) {
    List<String> enumValues = null;
    if (parameter.getSchema() instanceof StringSchema) {
        enumValues = ((StringSchema) (parameter.getSchema())).getEnum();
    }

    if (parameter.getSchema().getDefault() != null) {
        String strValue = parameter.getSchema().getDefault().toString();
        if (!strValue.isEmpty()) {
            return strValue;
        }
    }
    if (enumValues != null && !enumValues.isEmpty()) {
        return enumValues.get(0);
    }
    if (parameter.getExample() != null) {
        return parameter.getExample().toString();
    }
    return "";
}
 
Example 18
@Test
public void testConvertStringArrayPipesWithEscapedValue() throws Exception {
    List<String> values = Arrays.asList("\"good | bad\"|bad");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.PIPEDELIMITED)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new StringSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(String.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<String> objs = (List<String>) o;

    assertTrue(objs.size() == 2);
    assertEquals(objs.get(0), "good | bad");
    assertEquals(objs.get(1), "bad");
}
 
Example 19
Source Project: crnk-framework   Source File: SortTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void parameterSortableAttributes() {
  MetaResource metaResource = getTestMetaResource();
  MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0);
  MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1);
  metaResourceField.setSortable(true);
  additionalMetaResourceField.setSortable(true);

  Parameter parameter = new Sort(metaResource).parameter();
  Assert.assertEquals("sort", parameter.getName());
  Assert.assertEquals("query", parameter.getIn());
  Assert.assertEquals("ResourceType sort order (csv)", parameter.getDescription());
  Assert.assertNull(parameter.getRequired());
  Schema schema = parameter.getSchema();
  Assert.assertTrue(schema instanceof StringSchema);
  Assert.assertEquals("id,name", schema.getExample());
}
 
Example 20
private void magicParameterExplodedMatrixArray(Parameter parameter) {
  ParameterTypeValidator validator = ArrayTypeValidator.ArrayTypeValidatorFactory.createArrayTypeValidator(this
    .resolveInnerSchemaPrimitiveTypeValidator(((ArraySchema) parameter.getSchema()).getItems(), true), "matrix_exploded_array", true, parameter.getSchema().getMaxItems(), parameter.getSchema()
    .getMinItems());

  this.addPathParamRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
    .createValidationRuleWithCustomTypeValidator(parameter.getName(), validator, OpenApi3Utils.isRequiredParam(parameter), false, ParameterLocation.PATH));
}
 
Example 21
Source Project: crnk-framework   Source File: Fields.java    License: Apache License 2.0 5 votes vote down vote up
public Parameter parameter() {
  return new Parameter()
      .name("fields")
      .description(metaResource.getResourceType() + " fields to include (csv)")
      .in("query")
      .schema(new StringSchema()
          ._default(
              OASUtils.attributes(metaResource, true)  // TODO: Should primary key field(s) be included?
                  .map(MetaElement::getName)
                  .collect(joining(","))));
}
 
Example 22
Source Project: servicecomb-toolkit   Source File: ParameterUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getKeyString(Parameter parameter) {
  return new StringBuilder()
    .append("[name=")
    .append(parameter.getName())
    .append(",in=")
    .append(parameter.getIn())
    .append("]")
    .toString();
}
 
Example 23
Source Project: swagger-inflector   Source File: ValueCoercionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConversionException.class)
public void testConvertInvalidDoubleValue() throws Exception {
    List<String> values = Arrays.asList("abcdefg");

    Parameter parameter = new QueryParameter().schema(new NumberSchema());
    Object o = utils.cast(values, parameter, tf.constructType(Double.class), null);

    assertNull(o);
}
 
Example 24
Source Project: swagger-inflector   Source File: ValueCoercionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConversionException.class)
public void testConvertInvalidLongValue() throws Exception {
    List<String> values = Arrays.asList("1zzzzz");

    Parameter parameter = new QueryParameter().schema(new NumberSchema());
    Object o = utils.cast(values, parameter, tf.constructType(Long.class), null);

    assertNull(o);
}
 
Example 25
Source Project: spring-openapi   Source File: SchemaGeneratorHelper.java    License: MIT License 5 votes vote down vote up
public void enrichWithTypeAnnotations(Parameter parameter, Annotation[] annotations) {
    enrichWithAnnotation(io.swagger.v3.oas.annotations.media.Schema.class, annotations,
            schemaAnnotation -> {
                parameter.setDeprecated(schemaAnnotation.deprecated());
                parameter.setDescription(schemaAnnotation.description());
            });
    enrichWithAnnotation(Deprecated.class, annotations, deprecatedAnnotation -> parameter.setDeprecated(true));
}
 
Example 26
Source Project: RestDoc   Source File: Swagger3RestDocGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private List<Parameter> convertQueryString(ParameterModel paramModel, OpenAPI openAPI) {
    var parameters = new ArrayList<Parameter>();
    if (paramModel.getChildren() != null && paramModel.getChildren().size() > 0) // 复杂对象
    {
        convertParameterChildren(paramModel.getChildren(), null, openAPI)
                .stream().forEach(o -> parameters.add(o));
    } else {
        parameters.add(generateSingleParameterSchema("query", paramModel, openAPI));
    }
    return parameters;
}
 
Example 27
Source Project: RestDoc   Source File: Swagger3RestDocGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Parameter generateSingleParameterSchema(String in, ParameterModel paramModel, OpenAPI openAPI) {
    var parameter = new Parameter();
    parameter.setName(paramModel.getName());
    parameter.setDescription(paramModel.getDescription());
    parameter.setIn(in);
    parameter.setRequired(paramModel.isRequired());

    Schema schema = generateSchema(paramModel.getEnums(), paramModel.getDescription(), paramModel.getParameterType(), paramModel.getChildren(), openAPI);
    parameter.setSchema(schema);
    parameter.setDescription(combineStr(parameter.getDescription(), schema.getDescription()));
    return parameter;
}
 
Example 28
Source Project: swagger-parser   Source File: SwaggerConverter.java    License: Apache License 2.0 5 votes vote down vote up
private RequestBody convertParameterToRequestBody(io.swagger.models.parameters.Parameter param, List<String> consumes) {
    RequestBody body = new RequestBody();
    BodyParameter bp = (BodyParameter) param;

    List<String> mediaTypes = new ArrayList<>(globalConsumes);
    if (consumes != null && consumes.size() > 0) {
        mediaTypes.clear();
        mediaTypes.addAll(consumes);
    }

    if (mediaTypes.size() == 0) {
        mediaTypes.add("*/*");
    }

    if (StringUtils.isNotBlank(param.getDescription())) {
        body.description(param.getDescription());
    }
    body.required(param.getRequired());

    Content content = new Content();
    for (String type : mediaTypes) {
        content.addMediaType(type,
                new MediaType().schema(
                        convert(bp.getSchema())));
        if (StringUtils.isNotBlank(bp.getDescription())) {
            body.setDescription(bp.getDescription());
        }
    }
    convertExamples(((BodyParameter) param).getExamples(), content);
    body.content(content);
    return body;
}
 
Example 29
Source Project: springdoc-openapi   Source File: SpringDocTestApp.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI customOpenAPI() {
	return new OpenAPI()
			.components(new Components()
					.addSecuritySchemes("basicScheme",
							new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
					.addParameters("myHeader1",
							new Parameter().in("header").schema(new StringSchema()).name("myHeader1"))
					.addHeaders("myHeader2",
							new Header().description("myHeader2 header").schema(new StringSchema())))
			.info(new Info().title("Petstore API").version("v0").description(
					"This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.")
					.termsOfService("http://swagger.io/terms/")
					.license(new License().name("Apache 2.0").url("http://springdoc.org")));
}
 
Example 30
Source Project: swagger-inflector   Source File: DefaultValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionalParameter() throws Exception {
    Parameter parameter = new QueryParameter()
        .name("test")
        .schema(new StringSchema());

    converter.validate(null, parameter);
}