Java Code Examples for io.swagger.v3.oas.models.parameters.RequestBody#getContent()

The following examples show how to use io.swagger.v3.oas.models.parameters.RequestBody#getContent() . 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: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Apply bean validator annotations.
 *
 * @param requestBody the request body
 * @param annotations the annotations
 * @param isOptional the is optional
 */
public void applyBeanValidatorAnnotations(final RequestBody requestBody, final List<Annotation> annotations, boolean isOptional) {
	Map<String, Annotation> annos = new HashMap<>();
	boolean requestBodyRequired = false;
	if (!CollectionUtils.isEmpty(annotations)) {
		annotations.forEach(annotation -> annos.put(annotation.annotationType().getName(), annotation));
		requestBodyRequired = annotations.stream()
				.filter(annotation -> org.springframework.web.bind.annotation.RequestBody.class.equals(annotation.annotationType()))
				.anyMatch(annotation -> ((org.springframework.web.bind.annotation.RequestBody) annotation).required());
	}
	boolean validationExists = Arrays.stream(ANNOTATIONS_FOR_REQUIRED).anyMatch(annos::containsKey);

	if (validationExists || (!isOptional && requestBodyRequired))
		requestBody.setRequired(true);
	Content content = requestBody.getContent();
	for (MediaType mediaType : content.values()) {
		Schema<?> schema = mediaType.getSchema();
		applyValidationsToSchema(annos, schema);
	}
}
 
Example 2
Source File: RequestModelConverter.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private String generateBody() {
    RequestBody requestBody = operationModel.getOperation().getRequestBody();
    if (requestBody != null) {
        Content content = requestBody.getContent();
        Schema<?> schema;

        if (content.containsKey("application/json")) {
            schema = content.get("application/json").getSchema();
            return generators.getBodyGenerator().generate(schema);
        }
        if (content.containsKey("application/x-www-form-urlencoded")) {
            schema = content.get("application/x-www-form-urlencoded").getSchema();
            return generators.getBodyGenerator().generateForm(schema);
        }
        if (content.containsKey("application/octet-stream")
                || content.containsKey("multipart/form-data")) {
            return "";
        }

        if (!content.isEmpty()) {
            schema = content.entrySet().iterator().next().getValue().getSchema();
            return generators.getBodyGenerator().generate(schema);
        }
    }
    return "";
}
 
Example 3
Source File: RequestBodyProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void processRequestBody(RequestBody requestBody) {

        if (requestBody.get$ref() != null){
            processReferenceRequestBody(requestBody);
        }
        Schema schema = null;
        if(requestBody.getContent() != null){
            Map<String,MediaType> content = requestBody.getContent();
            for( String mediaName : content.keySet()) {
                MediaType mediaType = content.get(mediaName);
                if(mediaType.getSchema()!= null) {
                    schema = mediaType.getSchema();
                    if (schema != null) {
                        schemaProcessor.processSchema(schema);
                    }
                }
                if(mediaType.getExamples() != null) {
                    for(Example ex: mediaType.getExamples().values()){
                        exampleProcessor.processExample(ex);
                    }
                }
            }
        }
    }
 
Example 4
Source File: PathsProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
protected void updateLocalRefs(RequestBody body, String pathRef) {
    if (body.get$ref() != null){
        if(isLocalRef(body.get$ref())) {
            body.set$ref(computeLocalRef(body.get$ref(), pathRef));
        }
    }
    if(body.getContent() != null) {
        Map<String, MediaType> content = body.getContent();
        for (String key: content.keySet()) {
            MediaType mediaType = content.get(key);
            if (mediaType.getSchema() != null) {
                updateLocalRefs(mediaType.getSchema(), pathRef);
            }
            Map<String, Example> examples = content.get(key).getExamples();
            if (examples != null) {
                for (Example example : examples.values()) {
                    updateLocalRefs(example, pathRef);
                }
            }
        }
    }else if(body.get$ref() != null){

    }
}
 
Example 5
Source File: OperationParameterExampleInterceptor.java    From spring-openapi with MIT License 5 votes vote down vote up
private MediaType getRequestBodyMediaType(RequestBody transformedRequestBody) {
	if (transformedRequestBody == null || transformedRequestBody.getContent() == null || transformedRequestBody.getContent().isEmpty()) {
		return null;
	}
	Object object = ((LinkedHashMap) transformedRequestBody.getContent()).values().iterator().next();
	if (object instanceof MediaType) {
		return (MediaType) object;
	}
	return null;
}
 
Example 6
Source File: PythonClientExperimentalCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
    CodegenParameter result = super.fromRequestBody(body, imports, bodyParameterName);
    // if we generated a model with a non-object type because it has validations or enums,
    // make sure that the datatype of that body parameter refers to our model class
    Content content = body.getContent();
    Set<String> keySet = content.keySet();
    Object[] keyArray = (Object[]) keySet.toArray();
    MediaType mediaType = content.get(keyArray[0]);
    Schema schema = mediaType.getSchema();
    String ref = schema.get$ref();
    if (ref == null) {
        return result;
    }
    String modelName = ModelUtils.getSimpleRef(ref);
    // the result lacks validation info so we need to make a CodegenProperty from the schema to check
    // if we have validation and enum info exists
    Schema realSchema = ModelUtils.getSchema(this.openAPI, modelName);
    CodegenProperty modelProp = fromProperty("body", realSchema);
    if (modelProp.isPrimitiveType && (modelProp.hasValidation || modelProp.isEnum)) {
        String simpleDataType = result.dataType;
        result.dataType = toModelName(modelName);
        result.baseType = getPythonClassName(result.dataType);
        imports.remove(modelName);
        imports.add(result.dataType);
        // set the example value
        if (modelProp.isEnum) {
            String value = modelProp._enum.get(0).toString();
            result.example = result.dataType + "(" + toEnumValue(value, simpleDataType) + ")";
        } else {
            result.example = result.dataType + "(" + result.example + ")";
        }
    } else if (!result.isPrimitiveType) {
        // fix the baseType for the api docs so the .md link to the class's documentation file is correct
        result.baseType = getPythonClassName(result.baseType);
    }
    return result;
}
 
Example 7
Source File: OpenApiOperationValidations.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether a GET or HEAD operation is configured to expect a body.
 * <p>
 * RFC7231 describes this behavior as:
 * <p>
 * A payload within a GET request message has no defined semantics;
 * sending a payload body on a GET request might cause some existing
 * implementations to reject the request.
 * <p>
 * See https://tools.ietf.org/html/rfc7231#section-4.3.1
 * <p>
 * Because there are no defined semantics, and because some client and server implementations
 * may silently ignore the entire body (see https://xhr.spec.whatwg.org/#the-send()-method) or
 * throw an error (see https://fetch.spec.whatwg.org/#ref-for-dfn-throw%E2%91%A1%E2%91%A1),
 * we maintain that the existence of a body for this operation is most likely programmer error and raise awareness.
 *
 * @param wrapper Wraps an operation with accompanying HTTP Method
 * @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail}
 */
private static ValidationRule.Result checkAntipatternGetOrHeadWithBody(OperationWrapper wrapper) {
    if (wrapper == null) {
        return ValidationRule.Pass.empty();
    }

    ValidationRule.Result result = ValidationRule.Pass.empty();

    if (wrapper.getHttpMethod() == PathItem.HttpMethod.GET || wrapper.getHttpMethod() == PathItem.HttpMethod.HEAD) {
        RequestBody body = wrapper.getOperation().getRequestBody();

        if (body != null) {
            if (StringUtils.isNotEmpty(body.get$ref()) || (body.getContent() != null && body.getContent().size() > 0)) {
                result = new ValidationRule.Fail();
                result.setDetails(String.format(
                        Locale.ROOT,
                        "%s %s contains a request body and is considered an anti-pattern.",
                        wrapper.getHttpMethod().name(),
                        wrapper.getOperation().getOperationId())
                );
            }
        }

    }

    return result;
}
 
Example 8
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Schema getRequestBodySchema(RequestBody body) {
    Content content = body.getContent();
    if (content == null) {
        return null;
    }
    MediaType mediaType = content.get(DEFAULT_CONTENT_TYPE);
    if (mediaType != null && mediaType.getSchema() != null) {
        return mediaType.getSchema();
    }
    return null;
}
 
Example 9
Source File: StringTypeValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public void validate(Object argument, RequestBody body, Iterator<Validator> chain) throws ValidationException {
    if (body.getContent() != null) {
        for(String media: body.getContent().keySet()) {
            if (body.getContent().get(media) != null) {
                MediaType mediaType = body.getContent().get(media);
                Set<String> allowable = validateAllowedValues(argument, mediaType.getSchema());
                if(allowable != null){
                    throw new ValidationException()
                        .message(new ValidationMessage()
                                .code(ValidationError.UNACCEPTABLE_VALUE)
                                .message(" parameter  value `" + argument + "` is not in the allowable values `" + allowable + "`"));
                }
                if (validateFormat(argument,mediaType.getSchema())){
                    throw new ValidationException()
                        .message(new ValidationMessage()
                                .code(ValidationError.INVALID_FORMAT)
                                .message( " parameter value `" + argument + "` is not a valid " + mediaType.getSchema().getFormat()));
                }


            }
        }
    }

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

    return;
}
 
Example 10
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void setRefOfRequestBody(RequestBody requestBody, SwaggerUpdateContext context) {
    if (requestBody != null) {
        Content content = requestBody.getContent();

        extractReferenceFromContent(content, context);
    }
}
 
Example 11
Source File: OpenAPI3RequestValidationHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void parseRequestBody(RequestBody requestBody) {
  if (requestBody != null && requestBody.getContent() != null) {
    for (Map.Entry<String, ? extends MediaType> mediaType : requestBody.getContent().entrySet()) {
      if (Utils.isJsonContentType(mediaType.getKey()) && mediaType.getValue().getSchema() != null) {
        this.setEntireBodyValidator(JsonTypeValidator.JsonTypeValidatorFactory
          .createJsonTypeValidator(OpenApi3Utils.generateSanitizedJsonSchemaNode(mediaType.getValue().getSchema(), this.spec)));
      } else if (mediaType.getKey().equals("application/x-www-form-urlencoded") && mediaType.getValue().getSchema()
        != null) {
        for (Map.Entry<String, ? extends Schema> paramSchema : ((Map<String, Schema>) mediaType.getValue().getSchema().getProperties())
          .entrySet()) {
          this.addFormParamRule(ParameterValidationRuleImpl.ParameterValidationRuleFactory
            .createValidationRuleWithCustomTypeValidator(paramSchema.getKey(), this
              .resolveSchemaTypeValidatorFormEncoded(paramSchema.getValue()), !OpenApi3Utils.isRequiredParam
              (mediaType.getValue().getSchema(), paramSchema.getKey()), false, ParameterLocation.BODY_FORM));
        }
      } else if (mediaType.getKey().equals("multipart/form-data") && mediaType.getValue().getSchema() != null &&
        mediaType.getValue().getSchema().getType().equals("object")) {
        for (Map.Entry<String, ? extends Schema> multipartProperty : ((Map<String, Schema>) mediaType.getValue().getSchema().getProperties())
          .entrySet()) {
          Encoding encodingProperty = null;
          if (mediaType.getValue().getEncoding() != null)
            encodingProperty = mediaType.getValue().getEncoding().get(multipartProperty.getKey());
          String contentTypeRegex = null;
          if (encodingProperty != null && encodingProperty.getContentType() != null)
            contentTypeRegex = OpenApi3Utils.resolveContentTypeRegex(encodingProperty.getContentType());

          handleMultimapParameter(multipartProperty.getKey(), contentTypeRegex, multipartProperty.getValue(),
            mediaType.getValue().getSchema());
        }
      } else {
        this.addBodyFileRule(mediaType.getKey());
      }
    }
    this.bodyRequired = safeBoolean.apply(requestBody.getRequired());
  }
}
 
Example 12
Source File: RequestBodyContentValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, MediaType> getMapProperty(RequestBody oasObject) {
  return oasObject.getContent();
}
 
Example 13
Source File: RequestBodyContentDiffValidator.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, MediaType> getMapProperty(RequestBody oasObject) {
  return oasObject.getContent();
}
 
Example 14
Source File: RequestBodyDiff.java    From openapi-diff with Apache License 2.0 4 votes vote down vote up
@Override
protected Optional<ChangedRequestBody> computeDiff(
    HashSet<String> refSet, RequestBody left, RequestBody right, DiffContext context) {
  Content oldRequestContent = new Content();
  Content newRequestContent = new Content();
  RequestBody oldRequestBody = null;
  RequestBody newRequestBody = null;
  if (left != null) {
    oldRequestBody =
        refPointer.resolveRef(
            openApiDiff.getOldSpecOpenApi().getComponents(), left, left.get$ref());
    if (oldRequestBody.getContent() != null) {
      oldRequestContent = oldRequestBody.getContent();
    }
  }
  if (right != null) {
    newRequestBody =
        refPointer.resolveRef(
            openApiDiff.getNewSpecOpenApi().getComponents(), right, right.get$ref());
    if (newRequestBody.getContent() != null) {
      newRequestContent = newRequestBody.getContent();
    }
  }
  boolean leftRequired =
      oldRequestBody != null && Boolean.TRUE.equals(oldRequestBody.getRequired());
  boolean rightRequired =
      newRequestBody != null && Boolean.TRUE.equals(newRequestBody.getRequired());

  ChangedRequestBody changedRequestBody =
      new ChangedRequestBody(oldRequestBody, newRequestBody, context)
          .setChangeRequired(leftRequired != rightRequired);
  openApiDiff
      .getMetadataDiff()
      .diff(
          oldRequestBody != null ? oldRequestBody.getDescription() : null,
          newRequestBody != null ? newRequestBody.getDescription() : null,
          context)
      .ifPresent(changedRequestBody::setDescription);
  openApiDiff
      .getContentDiff()
      .diff(oldRequestContent, newRequestContent, context)
      .ifPresent(changedRequestBody::setContent);
  openApiDiff
      .getExtensionsDiff()
      .diff(getExtensions(left), getExtensions(right), context)
      .ifPresent(changedRequestBody::setExtensions);

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

    final RequestBody body = cache.loadRef($ref, refFormat, RequestBody.class);

    if(body == 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, RequestBody> bodies = openAPI.getComponents().getRequestBodies();

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

    final String possiblyConflictingDefinitionName = computeDefinitionName($ref);

    RequestBody existingBody= bodies.get(possiblyConflictingDefinitionName);

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

    if(existingBody == null) {
        // don't overwrite existing model reference
        openAPI.getComponents().addRequestBodies(newRef, body);
        cache.addReferencedKey(newRef);

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

    return newRef;
}
 
Example 16
Source File: RequestBodyBuilder.java    From springdoc-openapi with Apache License 2.0 2 votes vote down vote up
/**
 * Merge content.
 *
 * @param requestBody the request body
 * @param methodAttributes the method attributes
 * @param schema the schema
 */
private void mergeContent(RequestBody requestBody, MethodAttributes methodAttributes, Schema<?> schema) {
	Content content = requestBody.getContent();
	buildContent(requestBody, methodAttributes, schema, content);
}