Java Code Examples for io.swagger.v3.oas.models.media.MediaType#getSchema()
The following examples show how to use
io.swagger.v3.oas.models.media.MediaType#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: AbstractRequestBuilder.java From springdoc-openapi with Apache License 2.0 | 6 votes |
/** * 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: RequestBodyProcessor.java From swagger-parser with Apache License 2.0 | 6 votes |
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 3
Source File: PathsProcessor.java From swagger-parser with Apache License 2.0 | 6 votes |
protected void updateLocalRefs(ApiResponse response, String pathRef) { if (response.get$ref() != null){ if(isLocalRef(response.get$ref())) { response.set$ref(computeLocalRef(response.get$ref(), pathRef)); } } if(response.getContent() != null) { Map<String, MediaType> content = response.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); } } } } }
Example 4
Source File: PathsProcessor.java From swagger-parser with Apache License 2.0 | 6 votes |
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 5
Source File: PathsProcessor.java From swagger-parser with Apache License 2.0 | 6 votes |
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 6
Source File: ResourceInterfaceGenerator.java From spring-openapi with MIT License | 5 votes |
private MethodSpec createMethod(OperationData operationData) { Operation operation = operationData.getOperation(); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getMethodName(operation)) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); if (operation.getDescription() != null) { methodSpecBuilder.addJavadoc(operation.getDescription()); } if (operation.getParameters() != null) { operation.getParameters() .forEach(parameter -> methodSpecBuilder.addParameter( parseProperties(formatParameterName(parameter.getName()), parameter.getSchema()).build() )); } if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) { LinkedHashMap<String, MediaType> mediaTypes = operation.getRequestBody().getContent(); methodSpecBuilder.addParameter(parseProperties("requestBody", mediaTypes.entrySet().iterator().next().getValue().getSchema()).build()); } if (operation.getResponses() == null || CollectionUtils.isEmpty(operation.getResponses().entrySet())) { methodSpecBuilder.returns(TypeName.VOID); } else { ApiResponse apiResponse = operation.getResponses().entrySet().stream() .filter(responseEntry -> StringUtils.startsWith(responseEntry.getKey(), "2")) // HTTP 20x .findFirst() .map(Map.Entry::getValue) .orElse(null); if (apiResponse != null && apiResponse.getContent() != null && !apiResponse.getContent().isEmpty()) { MediaType mediaType = apiResponse.getContent().entrySet().iterator().next().getValue(); if (mediaType.getSchema() != null) { methodSpecBuilder.returns(determineTypeName(mediaType.getSchema())); return methodSpecBuilder.build(); } } methodSpecBuilder.returns(TypeName.VOID); } return methodSpecBuilder.build(); }
Example 7
Source File: SpringDocAnnotationsUtils.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * Gets content. * * @param annotationContents the annotation contents * @param classTypes the class types * @param methodTypes the method types * @param schema the schema * @param components the components * @param jsonViewAnnotation the json view annotation * @return the content */ public static Optional<Content> getContent(io.swagger.v3.oas.annotations.media.Content[] annotationContents, String[] classTypes, String[] methodTypes, Schema schema, Components components, JsonView jsonViewAnnotation) { if (ArrayUtils.isEmpty(annotationContents)) { return Optional.empty(); } // Encapsulating Content model Content content = new Content(); for (io.swagger.v3.oas.annotations.media.Content annotationContent : annotationContents) { MediaType mediaType = getMediaType(schema, components, jsonViewAnnotation, annotationContent); ExampleObject[] examples = annotationContent.examples(); setExamples(mediaType, examples); addExtension(annotationContent, mediaType); io.swagger.v3.oas.annotations.media.Encoding[] encodings = annotationContent.encoding(); addEncodingToMediaType(jsonViewAnnotation, mediaType, encodings); if (StringUtils.isNotBlank(annotationContent.mediaType())) { content.addMediaType(annotationContent.mediaType(), mediaType); } else { if (mediaType.getSchema() != null) applyTypes(classTypes, methodTypes, content, mediaType); } } if (content.size() == 0 && annotationContents.length != 1) { return Optional.empty(); } return Optional.of(content); }
Example 8
Source File: PythonClientExperimentalCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
@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 9
Source File: ContentDiff.java From openapi-diff with Apache License 2.0 | 5 votes |
public Optional<ChangedContent> diff(Content left, Content right, DiffContext context) { MapKeyDiff<String, MediaType> mediaTypeDiff = MapKeyDiff.diff(left, right); List<String> sharedMediaTypes = mediaTypeDiff.getSharedKey(); Map<String, ChangedMediaType> changedMediaTypes = new LinkedHashMap<>(); for (String mediaTypeKey : sharedMediaTypes) { MediaType oldMediaType = left.get(mediaTypeKey); MediaType newMediaType = right.get(mediaTypeKey); ChangedMediaType changedMediaType = new ChangedMediaType(oldMediaType.getSchema(), newMediaType.getSchema(), context); openApiDiff .getSchemaDiff() .diff( new HashSet<>(), oldMediaType.getSchema(), newMediaType.getSchema(), context.copyWithRequired(true)) .ifPresent(changedMediaType::setSchema); if (!isUnchanged(changedMediaType)) { changedMediaTypes.put(mediaTypeKey, changedMediaType); } } return isChanged( new ChangedContent(left, right, context) .setIncreased(mediaTypeDiff.getIncreased()) .setMissing(mediaTypeDiff.getMissing()) .setChanged(changedMediaTypes)); }
Example 10
Source File: VaadinConnectTsGenerator.java From flow with Apache License 2.0 | 5 votes |
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 11
Source File: ParameterProcessor.java From swagger-parser with Apache License 2.0 | 5 votes |
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 12
Source File: ExternalRefProcessor.java From swagger-parser with Apache License 2.0 | 5 votes |
private void processRefContent(Map<String, MediaType> content, String $ref) { for(MediaType mediaType : content.values()) { if(mediaType.getSchema() != null) { processRefSchemaObject(mediaType.getSchema(), $ref); } if(mediaType.getExamples() != null) { processRefExamples(mediaType.getExamples(), $ref); } } }
Example 13
Source File: HeaderProcessor.java From swagger-parser with Apache License 2.0 | 5 votes |
public void processHeader(Header header) { if(header.get$ref() != null){ RefFormat refFormat = computeRefFormat(header.get$ref()); String $ref = header.get$ref(); if (isAnExternalRefFormat(refFormat)){ final String newRef = externalRefProcessor.processRefToExternalHeader($ref, refFormat); if (newRef != null) { header.set$ref(newRef); } } } if (header.getSchema() != null) { schemaProcessor.processSchema(header.getSchema()); } if (header.getExamples() != null){ if (header.getExamples() != null) { Map<String,Example> examples = header.getExamples(); for (String key : examples.keySet()){ exampleProcessor.processExample(header.getExamples().get(key)); } } } Schema schema = null; if(header.getContent() != null) { Map<String,MediaType> content = header.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 14
Source File: OASParserUtil.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private static void extractReferenceFromContent(Content content, SwaggerUpdateContext context) { if (content != null) { for (MediaType mediaType : content.values()) { Schema schema = mediaType.getSchema(); extractReferenceFromSchema(schema, context); } } }
Example 15
Source File: OpenAPIV3ParserTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@Test public void shouldParseApiWithParametersUsingContentvsSchema() { // Tests that the content method of specifying the format of a parameter // gets resolved. // Test checks if an API's single parameter of array type gets fully resolved to // referenced definitions. String location = "src/test/resources/issue-1078/api.yaml"; ParseOptions options = new ParseOptions(); options.setResolve(true); // This test uses an Array in the parameters, test if it get's fully resolved. options.setResolveFully(true); OpenAPIV3Parser tested = new OpenAPIV3Parser(); // Parse yaml SwaggerParseResult result = tested.readLocation(location, emptyList(), options); OpenAPI api = result.getOpenAPI(); Paths paths = api.getPaths(); // First ensure all schemas were resolved, this is important when this library // is used to generate code Components components = api.getComponents(); assertNotNull(components); assertThat(components.getSchemas().size(), equalTo(4)); assertNotNull(components.getSchemas().get("LocationType")); assertNotNull(components.getSchemas().get("Lat")); assertNotNull(components.getSchemas().get("Long")); assertNotNull(components.getSchemas().get("SearchResult")); PathItem apiEndpoint = paths.get("/api-endpoint-1"); List<Parameter> parameters = apiEndpoint.getGet().getParameters(); // Ensure there's only one parameter in this test assertThat(parameters.size(), equalTo(1)); // We are testing content for a parameter so make sure its there. Content content = parameters.get(0).getContent(); assertNotNull(content); // spec says only one content is permitted in 3.x assertThat( content.size(), equalTo(1)); // Ensure there's a media type MediaType mediaType = content.entrySet().iterator().next().getValue(); assertNotNull(mediaType); // This test has a single parameter of type array Schema parameterSchema = mediaType.getSchema(); Assert.assertTrue(parameterSchema instanceof ArraySchema); ArraySchema arraySchema = (ArraySchema)parameterSchema; // Test if the item schema was resolved properly Schema itemSchema = arraySchema.getItems(); assertNotNull(itemSchema); Assert.assertTrue(itemSchema instanceof ObjectSchema); // Ensure the referenced item's schema has been resolved. ObjectSchema objSchema = (ObjectSchema)itemSchema; Map<String, Schema> objectItemSchemas = objSchema.getProperties(); assertThat( objectItemSchemas.size(), equalTo(2)); Assert.assertTrue(objectItemSchemas.get("lat") instanceof IntegerSchema); Assert.assertTrue(objectItemSchemas.get("long") instanceof IntegerSchema); }
Example 16
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method generates Sample/Mock payloads for Open API Specification (3.0) definitions * * @param apiDefinition API Definition * @return swagger Json */ @Override public Map<String, Object> generateExample(String apiDefinition) { OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser(); SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null); if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) { log.debug("Errors found when parsing OAS definition"); } OpenAPI swagger = parseAttemptForV3.getOpenAPI(); //return map Map<String, Object> returnMap = new HashMap<>(); //List for APIResMedPolicyList List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>(); for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) { int minResponseCode = 0; int responseCode = 0; String path = entry.getKey(); //initializing apiResourceMediationPolicyObject APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy(); //setting path for apiResourceMediationPolicyObject apiResourceMediationPolicyObject.setPath(path); Map<String, Schema> definitions = swagger.getComponents().getSchemas(); //operation map to get verb Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap(); List<Operation> operations = swagger.getPaths().get(path).readOperations(); for (Operation op : operations) { ArrayList<Integer> responseCodes = new ArrayList<Integer>(); //for each HTTP method get the verb StringBuilder genCode = new StringBuilder(); boolean hasJsonPayload = false; boolean hasXmlPayload = false; //for setting only one initializing if condition per response code boolean respCodeInitialized = false; for (Map.Entry<PathItem.HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) { //add verb to apiResourceMediationPolicyObject apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey())); } for (String responseEntry : op.getResponses().keySet()) { if (!responseEntry.equals("default")) { responseCode = Integer.parseInt(responseEntry); responseCodes.add(responseCode); minResponseCode = Collections.min(responseCodes); } Content content = op.getResponses().get(responseEntry).getContent(); if (content != null) { MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE); MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE); if (applicationJson != null) { Schema jsonSchema = applicationJson.getSchema(); if (jsonSchema != null) { String jsonExample = getJsonExample(jsonSchema, definitions); genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false)); respCodeInitialized = true; hasJsonPayload = true; } } if (applicationXml != null) { Schema xmlSchema = applicationXml.getSchema(); if (xmlSchema != null) { String xmlExample = getXmlExample(xmlSchema, definitions); genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized)); hasXmlPayload = true; } } } else { setDefaultGeneratedResponse(genCode, responseEntry); hasJsonPayload = true; hasXmlPayload = true; } } //inserts minimum response code and mock payload variables to static script String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode); //gets response section string depending on availability of json/xml payloads String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload); String finalScript = finalGenCode + responseConditions; apiResourceMediationPolicyObject.setContent(finalScript); //sets script to each resource in the swagger op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript); apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject); } checkAndSetEmptyScope(swagger); returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger)); returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList); } return returnMap; }
Example 17
Source File: MediaTypeSchemaValidator.java From servicecomb-toolkit with Apache License 2.0 | 4 votes |
@Override protected Schema getPropertyObject(MediaType oasObject) { return oasObject.getSchema(); }
Example 18
Source File: OpenAPIDeserializerTest.java From swagger-parser with Apache License 2.0 | 4 votes |
@Test(dataProvider = "data") public void readProducesTestEndpoint(JsonNode rootNode) throws Exception { final OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); final SwaggerParseResult result = deserializer.deserialize(rootNode); Assert.assertNotNull(result); final OpenAPI openAPI = result.getOpenAPI(); Assert.assertNotNull(openAPI); final Paths paths = openAPI.getPaths(); Assert.assertNotNull(paths); Assert.assertEquals(paths.size(), 18); //parameters operation get PathItem producesTestEndpoint = paths.get("/producesTest"); Assert.assertNotNull(producesTestEndpoint.getGet()); Assert.assertNotNull(producesTestEndpoint.getGet().getParameters()); Assert.assertTrue(producesTestEndpoint.getGet().getParameters().isEmpty()); Operation operation = producesTestEndpoint.getGet(); ApiResponses responses = operation.getResponses(); Assert.assertNotNull(responses); Assert.assertFalse(responses.isEmpty()); ApiResponse response = responses.get("200"); Assert.assertNotNull(response); Assert.assertEquals("it works", response.getDescription()); Content content = response.getContent(); Assert.assertNotNull(content); MediaType mediaType = content.get("application/json"); Assert.assertNotNull(mediaType); Schema schema = mediaType.getSchema(); Assert.assertNotNull(schema); Assert.assertTrue(schema instanceof ObjectSchema); ObjectSchema objectSchema = (ObjectSchema) schema; schema = objectSchema.getProperties().get("name"); Assert.assertNotNull(schema); Assert.assertTrue(schema instanceof StringSchema); }
Example 19
Source File: ResponseProcessor.java From swagger-parser with Apache License 2.0 | 4 votes |
public void processResponse(ApiResponse response) { if (response.get$ref() != null){ processReferenceResponse(response); } Schema schema = null; if(response.getContent() != null){ Map<String,MediaType> content = response.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); } } } } if (response.getHeaders() != null){ Map<String,Header> headers = response.getHeaders(); for(String headerName : headers.keySet()){ Header header = headers.get(headerName); headerProcessor.processHeader(header); } } if (response.getLinks() != null){ Map<String,Link> links = response.getLinks(); for(String linkName : links.keySet()){ Link link = links.get(linkName); linkProcessor.processLink(link); } } }
Example 20
Source File: MediaTypeSchemaDiffValidator.java From servicecomb-toolkit with Apache License 2.0 | 4 votes |
@Override protected Schema getPropertyObject(MediaType oasObject) { return oasObject.getSchema(); }