Java Code Examples for io.swagger.v3.oas.models.parameters.Parameter#getSchema()

The following examples show how to use io.swagger.v3.oas.models.parameters.Parameter#getSchema() . 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: ResolverCache.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
protected <T> void updateLocalRefs(String file, T result) {
    if(result instanceof Parameter){
        Parameter parameter = (Parameter)result;
        if (parameter.getSchema() != null){
            updateLocalRefs(file,parameter.getSchema());
        }
    }
    if(result instanceof Schema && ((Schema)(result)).get$ref() != null) {
        Schema prop = (Schema) result;
        updateLocalRefs(file, prop);
    }
    else if(result instanceof Schema) {
        Schema model = (Schema) result;
        updateLocalRefs(file, model);
    }
}
 
Example 2
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static void visitParameters(OpenAPI openAPI, List<Parameter> parameters, OpenAPISchemaVisitor visitor,
                                    List<String> visitedSchemas) {
    if (parameters != null) {
        for (Parameter p : parameters) {
            Parameter parameter = getReferencedParameter(openAPI, p);
            if (parameter != null) {
                if (parameter.getSchema() != null) {
                    visitSchema(openAPI, parameter.getSchema(), null, visitedSchemas, visitor);
                }
                visitContent(openAPI, parameter.getContent(), visitor, visitedSchemas);
            } else {
                once(LOGGER).warn("Unreferenced parameter(s) found.");
            }
        }
    }
}
 
Example 3
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 4
Source File: SortTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
void parameterNoSortableAttributes() {
  MetaResource metaResource = getTestMetaResource();
  MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0);
  MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1);
  metaResourceField.setSortable(false);
  additionalMetaResourceField.setSortable(false);

  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("", schema.getExample());
}
 
Example 5
Source File: SortTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
void parameterSortableAttribute() {
  MetaResource metaResource = getTestMetaResource();
  MetaResourceField metaResourceField = (MetaResourceField) metaResource.getChildren().get(0);
  MetaResourceField additionalMetaResourceField = (MetaResourceField) metaResource.getChildren().get(1);
  metaResourceField.setSortable(false);
  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("name", schema.getExample());
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test(description = "OpenAPI v2 converter - proper IntegerSchema parsing")
public void testIssue1032() throws Exception {
    final OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_1032_YAML);
    assertNotNull(oas);
    Parameter unixTimestampQueryParameter = oas.getComponents().getParameters().get(UNIX_TIMESTAMP_QUERY_PARAM);
    assertNotNull(unixTimestampQueryParameter);
    Schema s = unixTimestampQueryParameter.getSchema();
    assertTrue((s instanceof IntegerSchema), "actual type: " + s);
    IntegerSchema integerSchema = (IntegerSchema) s;
    assertEquals(INTEGER_TYPE, integerSchema.getType());
    assertEquals(INT64_FORMAT, integerSchema.getFormat());
}
 
Example 12
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test(description = "Missing array item type in parameters")
public void testIssue1() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(PET_STORE_JSON);
    Parameter statusParameter = oas.getPaths().get(PET_FIND_BY_STATUS_PATH).getGet().getParameters().get(0);
    assertNotNull(statusParameter);
    assertTrue(statusParameter.getSchema() instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema) statusParameter.getSchema();
    assertEquals(ARRAY_TYPE, arraySchema.getType());
    assertEquals(ENUM_SIZE, arraySchema.getItems().getEnum().size());
}
 
Example 13
Source File: DataGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private String generateArrayValue(String name, Parameter parameter) {
    boolean isPath = isPath(parameter.getIn());
    if (!(parameter.getSchema() instanceof ArraySchema
            && ((ArraySchema) parameter.getSchema()).getItems() instanceof ArraySchema)) {
        return generateValue(name, ((ArraySchema) parameter.getSchema()).getItems(), isPath);
    }
    return generators
            .getArrayGenerator()
            .generate(
                    name,
                    ((ArraySchema) ((ArraySchema) parameter.getSchema()).getItems()),
                    "",
                    isPath);
}
 
Example 14
Source File: OpenAPI3RequestValidationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private ParameterTypeValidator resolveAnyOfOneOfTypeValidator(Parameter parameter) {
  ComposedSchema composedSchema;
  if (parameter.getSchema() instanceof ComposedSchema) composedSchema = (ComposedSchema) parameter.getSchema();
  else return null;

  if (OpenApi3Utils.isAnyOfSchema(composedSchema)) {
    return new AnyOfTypeValidator(this.resolveTypeValidatorsForAnyOfOneOf(new ArrayList<>(composedSchema.getAnyOf
      ()), parameter));
  } else if (OpenApi3Utils.isOneOfSchema(composedSchema)) {
    return new OneOfTypeValidator(this.resolveTypeValidatorsForAnyOfOneOf(new ArrayList<>(composedSchema.getOneOf
      ()), parameter));
  } else return null;
}
 
Example 15
Source File: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Apply bean validator annotations.
 *
 * @param parameter the parameter
 * @param annotations the annotations
 */
public void applyBeanValidatorAnnotations(final Parameter parameter, final List<Annotation> annotations) {
	Map<String, Annotation> annos = new HashMap<>();
	if (annotations != null)
		annotations.forEach(annotation -> annos.put(annotation.annotationType().getName(), annotation));
	boolean annotationExists = Arrays.stream(ANNOTATIONS_FOR_REQUIRED).anyMatch(annos::containsKey);
	if (annotationExists)
		parameter.setRequired(true);
	Schema<?> schema = parameter.getSchema();
	applyValidationsToSchema(annos, schema);
}
 
Example 16
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue85(@Injectable final List<AuthorizationValue> auths) {
    String yaml =
            "openapi: '3.0.1'\n" +
                    "paths: \n" +
                    "  /test/method: \n" +
                    "    post: \n" +
                    "      parameters: \n" +
                    "        - \n" +
                    "          in: \"path\"\n" +
                    "          name: \"body\"\n" +
                    "          required: false\n" +
                    "          schema: \n" +
                    "            $ref: '#/components/Schemas/StructureA'\n" +
                    "components: \n" +
                    "   schemas:\n" +
                    "       StructureA: \n" +
                    "           type: object\n" +
                    "           properties: \n" +
                    "               someProperty: \n" +
                    "                   type: string\n" +
                    "               arrayOfOtherType: \n" +
                    "                   type: array\n" +
                    "                   items: \n" +
                    "                       $ref: '#/definitions/StructureB'\n" +
                    "       StructureB: \n" +
                    "           type: object\n" +
                    "           properties: \n" +
                    "               someProperty: \n" +
                    "                   type: string\n";

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readContents(yaml,auths,options).getOpenAPI();
    ResolverFully resolverUtil = new ResolverFully();
    resolverUtil.resolveFully(openAPI);
    Parameter param = openAPI.getPaths().get("/test/method").getPost().getParameters().get(0);

    Schema schema = param.getSchema();
    assertNotNull(schema.getProperties().get("someProperty"));

    ArraySchema am = (ArraySchema) schema.getProperties().get("arrayOfOtherType");
    assertNotNull(am);
    Schema prop = am.getItems();
    assertTrue(prop instanceof Schema);
}
 
Example 17
Source File: DefaultConverter.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
public Object coerceValue(List<String> arguments, Parameter parameter, Class<?> cls) throws ConversionException {
    if (arguments == null || arguments.size() == 0) {
        return null;
    }

    LOGGER.debug("casting `" + arguments + "` to " + cls);
    if (List.class.equals(cls)) {
        if (parameter.getSchema() != null) {
            List<Object> output = new ArrayList<>();
            if (parameter.getSchema() instanceof ArraySchema) {
                ArraySchema arraySchema = ((ArraySchema) parameter.getSchema());
                Schema inner = arraySchema.getItems();


                // TODO: this does not need to be done this way, update the helper method
                Parameter innerParam = new QueryParameter();
                innerParam.setSchema(inner);
                JavaType innerClass = getTypeFromParameter(innerParam, definitions);
                for (String obj : arguments) {
                    String[] parts = new String[0];

                    if (Parameter.StyleEnum.FORM.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj) && parameter.getExplode() == false ) {
                        parts = obj.split(",");
                    }
                    if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                        parts = obj.split("|");
                    }
                    if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                        parts = obj.split(" ");
                    }
                    if (Parameter.StyleEnum.FORM.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj) && parameter.getExplode() == true) {
                        parts = new String[1];
                        parts[0]= obj;
                    }
                    for (String p : parts) {
                        Object ob = cast(p, inner, innerClass);
                        if (ob != null) {
                            output.add(ob);
                        }
                    }
                }
            }
            return output;
        }
    } else if (parameter.getSchema() != null) {
        TypeFactory tf = Json.mapper().getTypeFactory();

        return cast(arguments.get(0), parameter.getSchema(), tf.constructType(cls));

    }
    return null;
}
 
Example 18
Source File: ExternalRefProcessor.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public String processRefToExternalParameter(String $ref, RefFormat refFormat) {
    String renamedRef = cache.getRenamedRef($ref);
    if(renamedRef != null) {
        return renamedRef;
    }

    final Parameter parameter = cache.loadRef($ref, refFormat, Parameter.class);

    if(parameter == null) {
        // stop!  There's a problem.  retain the original ref
        LOGGER.warn("unable to load model reference from `" + $ref + "`.  It may not be available " +
                "or the reference isn't a valid model schema");
        return $ref;
    }
    String newRef;

    if (openAPI.getComponents() == null) {
        openAPI.setComponents(new Components());
    }
    Map<String, Parameter> parameters = openAPI.getComponents().getParameters();

    if (parameters == null) {
        parameters = new LinkedHashMap<>();
    }

    final String possiblyConflictingDefinitionName = computeDefinitionName($ref);

    Parameter existingParameters = parameters.get(possiblyConflictingDefinitionName);

    if (existingParameters != null) {
        LOGGER.debug("A model for " + existingParameters + " already exists");
        if(existingParameters.get$ref() != null) {
            // use the new model
            existingParameters = null;
        }
    }
    newRef = possiblyConflictingDefinitionName;
    cache.putRenamedRef($ref, newRef);

    if(existingParameters == null) {
        // don't overwrite existing model reference
        openAPI.getComponents().addParameters(newRef, parameter);
        cache.addReferencedKey(newRef);

        String file = $ref.split("#/")[0];
        if (parameter.get$ref() != null) {
            RefFormat format = computeRefFormat(parameter.get$ref());
            if (isAnExternalRefFormat(format)) {
                parameter.set$ref(processRefToExternalParameter(parameter.get$ref(), format));
            } else {
                processRefToExternalParameter(file + parameter.get$ref(), RefFormat.RELATIVE);
            }
        }
    }

    if(parameter != null) {
        if(parameter.getContent() != null){
            processRefContent(parameter.getContent(), $ref);
        }
        if(parameter.getSchema() != null){
            processRefSchemaObject(parameter.getSchema(), $ref);
        }
    }

    return newRef;
}
 
Example 19
Source File: ParameterSchemaDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Schema getPropertyObject(Parameter oasObject) {
  return oasObject.getSchema();
}
 
Example 20
Source File: ParameterSchemaValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Schema getPropertyObject(Parameter oasObject) {
  return oasObject.getSchema();
}