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

The following examples show how to use io.swagger.v3.oas.models.parameters.Parameter. 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: ReflectionUtils.java    From swagger-inflector with 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 #2
Source File: ScalaGatlingCodegen.java    From openapi-generator with 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 #3
Source File: AbstractRequestBuilder.java    From springdoc-openapi with 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 #4
Source File: ParameterAllowEmptyValueChangeDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: HtmlRender.java    From openapi-diff with 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 #6
Source File: DataRestRequestBuilder.java    From springdoc-openapi with 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 #7
Source File: ParameterRequiredChangeDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 File: DataGenerator.java    From zap-extensions with 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 #9
Source File: Reader.java    From proteus with 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 #10
Source File: PathsProcessor.java    From swagger-parser with 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 #11
Source File: GenericParameterBuilder.java    From springdoc-openapi with 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 #12
Source File: StringTypeValidator.java    From swagger-inflector with 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 #13
Source File: ParameterNameCookieCaseValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: CallbackProcessor.java    From swagger-parser with 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 #15
Source File: OpenAPIResolverTest.java    From swagger-parser with 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 #16
Source File: AbstractOpenApiResource.java    From springdoc-openapi with 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 #17
Source File: SortTest.java    From crnk-framework with 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 #18
Source File: ArraySerializableParamExtractionTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@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 File: OpenAPIV3ParserTest.java    From swagger-parser with 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 #20
Source File: DefaultValidatorTest.java    From swagger-inflector with 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);
}
 
Example #21
Source File: ParameterProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public void processParameter(Parameter parameter) {
    String $ref = parameter.get$ref();
    if($ref != null){
        RefFormat refFormat = computeRefFormat(parameter.get$ref());
        if (isAnExternalRefFormat(refFormat)){
            final String newRef = externalRefProcessor.processRefToExternalParameter($ref, refFormat);
            if (newRef != null) {
                parameter.set$ref(newRef);
            }
        }
    }
    if (parameter.getSchema() != null){
        schemaProcessor.processSchema(parameter.getSchema());
    }
    if (parameter.getExamples() != null){
        Map <String, Example> examples = parameter.getExamples();
        for(String exampleName: examples.keySet()){
            final Example example = examples.get(exampleName);
            exampleProcessor.processExample(example);
        }
    }
    Schema schema = null;
    if(parameter.getContent() != null) {
        Map<String,MediaType> content = parameter.getContent();
        for( String mediaName : content.keySet()) {
            MediaType mediaType = content.get(mediaName);
            if(mediaType.getSchema()!= null) {
                schema = mediaType.getSchema();
                if (schema != null) {
                    schemaProcessor.processSchema(schema);
                }
            }
        }
    }
}
 
Example #22
Source File: SpringDocTestApp.java    From springdoc-openapi with 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 #23
Source File: GenericParameterBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build parameter from doc parameter.
 *
 * @param parameterDoc the parameter doc
 * @param components the components
 * @param jsonView the json view
 * @return the parameter
 */
public Parameter buildParameterFromDoc(io.swagger.v3.oas.annotations.Parameter parameterDoc,
		Components components, JsonView jsonView) {
	Parameter parameter = new Parameter();
	if (StringUtils.isNotBlank(parameterDoc.description()))
		parameter.setDescription(propertyResolverUtils.resolve(parameterDoc.description()));
	if (StringUtils.isNotBlank(parameterDoc.name()))
		parameter.setName(propertyResolverUtils.resolve(parameterDoc.name()));
	if (StringUtils.isNotBlank(parameterDoc.in().toString()))
		parameter.setIn(parameterDoc.in().toString());
	if (StringUtils.isNotBlank(parameterDoc.example())) {
		try {
			parameter.setExample(Json.mapper().readTree(parameterDoc.example()));
		}
		catch (IOException e) {
			parameter.setExample(parameterDoc.example());
		}
	}
	if (parameterDoc.deprecated())
		parameter.setDeprecated(parameterDoc.deprecated());
	if (parameterDoc.required())
		parameter.setRequired(parameterDoc.required());
	if (parameterDoc.allowEmptyValue())
		parameter.setAllowEmptyValue(parameterDoc.allowEmptyValue());
	if (parameterDoc.allowReserved())
		parameter.setAllowReserved(parameterDoc.allowReserved());

	setSchema(parameterDoc, components, jsonView, parameter);
	setExamples(parameterDoc, parameter);
	setExtensions(parameterDoc, parameter);
	setParameterStyle(parameter, parameterDoc);
	setParameterExplode(parameter, parameterDoc);

	return parameter;
}
 
Example #24
Source File: GenericParameterBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Sets extensions.
 *
 * @param parameterDoc the parameter doc
 * @param parameter the parameter
 */
private void setExtensions(io.swagger.v3.oas.annotations.Parameter parameterDoc, Parameter parameter) {
	if (parameterDoc.extensions().length > 0) {
		Map<String, Object> extensionMap = AnnotationsUtils.getExtensions(parameterDoc.extensions());
		extensionMap.forEach(parameter::addExtension);
	}
}
 
Example #25
Source File: BallerinaParameter.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
@Override
public BallerinaParameter buildContext(Parameter parameter, ExtendedAPI api) throws BallerinaServiceGenException {
    this.name = parameter.getName();
    this.in = parameter.getIn();
    this.description = parameter.getDescription();
    this.required = parameter.getRequired();
    this.allowEmptyValue = parameter.getAllowEmptyValue();
    return this;
}
 
Example #26
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue291() {
    String json = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  title: test spec\n" +
            "  version: '1.0'\n" +
            "paths:\n" +
            "  /test:\n" +
            "    get:\n" +
            "      description: test get\n" +
            "      parameters:\n" +
            "        - $ref: '#/components/parameters/testParam'\n" +
            "      responses:\n" +
            "        default:\n" +
            "          description: test response\n" +
            "components:\n" +
            "  parameters:\n" +
            "    testParam:\n" +
            "      name: test\n" +
            "      in: query\n" +
            "      style: form\n" +
            "      schema:\n" +
            "        type: array\n" +
            "        items:\n" +
            "          type: string";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(json, null, null);

    OpenAPI swagger = result.getOpenAPI();
    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();


    Parameter param = resolved.getPaths().get("/test").getGet().getParameters().get(0);
    QueryParameter qp = (QueryParameter) param;
    //assertEquals(qp.getCollectionFormat(), "csv");
}
 
Example #27
Source File: DataRestRequestBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build parameters.
 *
 * @param domainType the domain type
 * @param openAPI the open api
 * @param handlerMethod the handler method
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param resourceMetadata the resource metadata
 */
public void buildParameters(Class<?> domainType, OpenAPI openAPI, HandlerMethod handlerMethod, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, ResourceMetadata resourceMetadata) {
	String[] pNames = this.localSpringDocParameterNameDiscoverer.getParameterNames(handlerMethod.getMethod());
	MethodParameter[] parameters = handlerMethod.getMethodParameters();
	if (!resourceMetadata.isPagingResource()) {
		Optional<MethodParameter> methodParameterPage = Arrays.stream(parameters).filter(methodParameter -> DefaultedPageable.class.equals(methodParameter.getParameterType())).findFirst();
		if (methodParameterPage.isPresent())
			parameters = ArrayUtils.removeElement(parameters, methodParameterPage.get());
	}
	String[] reflectionParametersNames = Arrays.stream(handlerMethod.getMethod().getParameters()).map(java.lang.reflect.Parameter::getName).toArray(String[]::new);
	if (pNames == null || Arrays.stream(pNames).anyMatch(Objects::isNull))
		pNames = reflectionParametersNames;
	buildCommonParameters(domainType, openAPI, requestMethod, methodAttributes, operation, pNames, parameters);
}
 
Example #28
Source File: PrimaryKey.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public Parameter parameter() {
  MetaResourceField metaResourceField = OASUtils.getPrimaryKeyMetaResourceField(metaResource);
  return new Parameter()
      .name(metaResourceField.getName())
      .in("path")
      .schema(new ResourceAttribute(metaResource, metaResourceField).$ref());
}
 
Example #29
Source File: SchemaGeneratorHelper.java    From spring-openapi with 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 #30
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private OperationValue(HttpMethod method, String path, Operation operationModel, PathItem pathModel) {
  this.method = method;
  this.path = path;
  this.pathModel = pathModel;
  this.operationModel = operationModel;
  this.tags = operationModel.getTags();
  // Merge parameters
  List<Parameter> opParams = operationModel.getParameters()==null ? new ArrayList<>() : operationModel.getParameters();
  List<Parameter> parentParams = pathModel.getParameters() == null ? new ArrayList<>() : pathModel.getParameters();
  this.parameters = OpenApi3Utils.mergeParameters(opParams, parentParams);
  this.userHandlers = new ArrayList<>();
  this.userFailureHandlers = new ArrayList<>();
}