io.swagger.v3.oas.models.media.MediaType Java Examples
The following examples show how to use
io.swagger.v3.oas.models.media.MediaType.
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: OperationContext.java From servicecomb-toolkit with Apache License 2.0 | 6 votes |
private void processProduces() { if (getProduces() == null) { return; } List<String> produceList = Arrays.stream(produces).filter(s -> !StringUtils.isEmpty(s)) .collect(Collectors.toList()); if (!produceList.isEmpty()) { ApiResponse apiResponse = new ApiResponse(); Content content = new Content(); MediaType mediaType = new MediaType(); Schema schema = ModelConverter .getSchema(getMethod().getReturnType(), getComponents(), RequestResponse.RESPONSE); mediaType.schema(schema); for (String produce : produceList) { content.addMediaType(produce, mediaType); } apiResponse.description("OK"); apiResponse.setContent(content); addResponse(HttpStatuses.OK, apiResponse); } }
Example #2
Source File: OpenApiObjectGenerator.java From flow with Apache License 2.0 | 6 votes |
private ApiResponse createApiSuccessfulResponse( MethodDeclaration methodDeclaration) { Content successfulContent = new Content(); // "description" is a REQUIRED property of Response ApiResponse successfulResponse = new ApiResponse().description(""); methodDeclaration.getJavadoc().ifPresent(javadoc -> { for (JavadocBlockTag blockTag : javadoc.getBlockTags()) { if (blockTag.getType() == JavadocBlockTag.Type.RETURN) { successfulResponse.setDescription( "Return " + blockTag.getContent().toText()); } } }); if (!methodDeclaration.getType().isVoidType()) { MediaType mediaItem = createReturnMediaType(methodDeclaration); successfulContent.addMediaType("application/json", mediaItem); successfulResponse.content(successfulContent); } return successfulResponse; }
Example #3
Source File: OpenAPIResolverTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test(description = "resolve array response remote refs in yaml") public void testYamlArrayResponseRemoteRefs() { final OpenAPI swagger = new OpenAPI(); swagger.path("/fun", new PathItem() .get(new Operation() .responses(new ApiResponses().addApiResponse("200", new ApiResponse() .content(new Content().addMediaType("*/*",new MediaType().schema( new ArraySchema().items( new Schema().$ref(replacePort(REMOTE_REF_YAML)))))))))); final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve(); final ApiResponse response = swagger.getPaths().get("/fun").getGet().getResponses().get("200"); final ArraySchema array = (ArraySchema) response.getContent().get("*/*").getSchema(); assertNotNull(array.getItems()); assertEquals(array.getItems().get$ref(), "#/components/schemas/Tag"); assertNotNull(swagger.getComponents().getSchemas().get("Tag")); }
Example #4
Source File: InputModeller.java From tcases with MIT License | 6 votes |
/** * Returns the schema for the given parameter. */ private Schema<?> parameterSchema( OpenAPI api, Parameter parameter) { // The schema should be defined either by... Schema<?> schema = // ... the schema property... Optional.ofNullable( parameter.getSchema()) // ... or the content property .orElse( Optional.ofNullable( parameter.getContent()) .map( content -> content.values().stream().findFirst().map( MediaType::getSchema).orElse( null)) .orElse( null)); return analyzeSchema( api, schema); }
Example #5
Source File: SpringDocAnnotationsUtils.java From springdoc-openapi with Apache License 2.0 | 6 votes |
/** * Gets media type. * * @param schema the schema * @param components the components * @param jsonViewAnnotation the json view annotation * @param annotationContent the annotation content * @return the media type */ private static MediaType getMediaType(Schema schema, Components components, JsonView jsonViewAnnotation, io.swagger.v3.oas.annotations.media.Content annotationContent) { MediaType mediaType = new MediaType(); if (!annotationContent.schema().hidden()) { if (components != null) { try { getSchema(annotationContent, components, jsonViewAnnotation).ifPresent(mediaType::setSchema); } catch (Exception e) { if (isArray(annotationContent)) mediaType.setSchema(new ArraySchema().items(new StringSchema())); else mediaType.setSchema(new StringSchema()); } } else { mediaType.setSchema(schema); } } return mediaType; }
Example #6
Source File: ReflectionUtils.java From swagger-inflector with Apache License 2.0 | 6 votes |
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 #7
Source File: InlineModelResolverTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testBasicInput() { OpenAPI openAPI = new OpenAPI(); openAPI.setComponents(new Components()); Schema user = new Schema(); user.addProperties("name", new StringSchema()); openAPI.path("/foo/baz", new PathItem() .post(new Operation() .requestBody(new RequestBody() .content(new Content().addMediaType("*/*",new MediaType().schema(new Schema().$ref("User"))))))); openAPI.getComponents().addSchemas("User", user); new InlineModelResolver().flatten(openAPI); }
Example #8
Source File: BodyParamExtractionTest.java From swagger-inflector with Apache License 2.0 | 6 votes |
@Test public void testConvertDoubleArrayBodyParam() throws Exception { Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class); RequestBody body = new RequestBody(). content(new Content() .addMediaType("application/json",new MediaType().schema(new ArraySchema() .items(new ArraySchema().items(new StringSchema()))))); JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0]; assertNotNull(jt); assertEquals(jt.getRawClass(), List[].class); JavaType inner = jt.getContentType(); assertEquals(inner.getRawClass(), List.class); assertEquals(inner.getContentType().getRawClass(), String.class); }
Example #9
Source File: InlineModelResolverTest.java From swagger-parser with Apache License 2.0 | 6 votes |
@Test public void testArbitraryObjectResponseMapInline() { OpenAPI openAPI = new OpenAPI(); Schema schema = new Schema(); schema.setAdditionalProperties(new ObjectSchema()); openAPI.path("/foo/baz", new PathItem() .get(new Operation() .responses(new ApiResponses().addApiResponse("200", new ApiResponse() .description("it works!") .content(new Content().addMediaType("*/*", new MediaType().schema(schema))))))); new InlineModelResolver().flatten(openAPI); ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200"); Schema property = response.getContent().get("*/*").getSchema(); assertTrue(property.getAdditionalProperties() != null); assertTrue(property.getAdditionalProperties() instanceof Schema); assertTrue(openAPI.getComponents().getSchemas() == null); Schema inlineProp = (Schema)property.getAdditionalProperties(); assertTrue(inlineProp instanceof ObjectSchema); ObjectSchema op = (ObjectSchema) inlineProp; assertNull(op.getProperties()); }
Example #10
Source File: InputModeller.java From tcases with MIT License | 6 votes |
/** * Returns the {@link IVarDef input variable definition} for the given request body. */ private Optional<IVarDef> requestBodyVarDef( OpenAPI api, RequestBody body) { return resultFor( "requestBody", () -> Optional.ofNullable( body) .map( b -> resolveRequestBody( api, b)) .map( b -> { String contentVarTag = "Content"; Map<String,MediaType> mediaTypes = expectedValueOf( b.getContent(), "Request body content"); return VarSetBuilder.with( "Body") .type( "request") .members( instanceDefinedVar( contentVarTag, Boolean.TRUE.equals( b.getRequired())), mediaTypeVar( contentVarTag, mediaTypes)) .members( mediaTypeContentVars( api, contentVarTag, mediaTypes)) .build(); })); }
Example #11
Source File: OASErrors.java From crnk-framework with Apache License 2.0 | 6 votes |
public static Map<String, ApiResponse> generateStandardApiErrorResponses() { Map<String, ApiResponse> responses = new LinkedHashMap<>(); List<Integer> responseCodes = getStandardHttpStatusCodes(); for (Integer responseCode : responseCodes) { if (responseCode >= 400 && responseCode <= 599) { ApiResponse apiResponse = new ApiResponse(); apiResponse.description(HttpStatus.toMessage(responseCode)); apiResponse.content(new Content() .addMediaType("application/vnd.api+json", new MediaType().schema(new Failure().$ref())) ); responses.put(responseCode.toString(), apiResponse); } } return responses; }
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 6 votes |
public Content getContent(ObjectNode node, String location, ParseResult result){ if (node == null) { return null; } Content content = new Content(); Set<String> keys = getKeys(node); for(String key : keys) { MediaType mediaType = getMediaType((ObjectNode) node.get(key), String.format("%s.'%s'", location, key), result); if (mediaType != null) { content.addMediaType(key, mediaType); } } return content; }
Example #17
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 #18
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 #19
Source File: StringTypeValidator.java From swagger-inflector with Apache License 2.0 | 5 votes |
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 #20
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 #21
Source File: SwaggerConverter.java From swagger-parser with Apache License 2.0 | 5 votes |
private RequestBody convertParameterToRequestBody(io.swagger.models.parameters.Parameter param, List<String> consumes) { RequestBody body = new RequestBody(); BodyParameter bp = (BodyParameter) param; List<String> mediaTypes = new ArrayList<>(globalConsumes); if (consumes != null && consumes.size() > 0) { mediaTypes.clear(); mediaTypes.addAll(consumes); } if (mediaTypes.size() == 0) { mediaTypes.add("*/*"); } if (StringUtils.isNotBlank(param.getDescription())) { body.description(param.getDescription()); } body.required(param.getRequired()); Content content = new Content(); for (String type : mediaTypes) { content.addMediaType(type, new MediaType().schema( convert(bp.getSchema()))); if (StringUtils.isNotBlank(bp.getDescription())) { body.setDescription(bp.getDescription()); } } convertExamples(((BodyParameter) param).getExamples(), content); body.content(content); return body; }
Example #22
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 #23
Source File: BodyParamExtractionTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void testUUIDBodyParam() throws Exception { Map<String, Schema> definitions = new HashMap<>(); RequestBody body = new RequestBody(). content(new Content() .addMediaType("application/json",new MediaType() .schema(new Schema().type("string").format("uuid")))); JavaType jt = utils.getTypeFromRequestBody(body,"application/json" , definitions)[0]; assertEquals(jt.getRawClass(), UUID.class); }
Example #24
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Construct openAPI definition for graphQL. Add get and post operations * * @param openAPI OpenAPI * @return modified openAPI for GraphQL */ private void modifyGraphQLSwagger(OpenAPI openAPI) { SwaggerData.Resource resource = new SwaggerData.Resource(); resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN); resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED); resource.setPath("/"); resource.setVerb(APIConstants.HTTP_POST); Operation postOperation = createOperation(resource); //post operation RequestBody requestBody = new RequestBody(); requestBody.setDescription("Query or mutation to be passed to graphQL API"); requestBody.setRequired(true); JSONObject typeOfPayload = new JSONObject(); JSONObject payload = new JSONObject(); typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING); payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload); Schema postSchema = new Schema(); postSchema.setType(APIConstants.OBJECT); postSchema.setProperties(payload); MediaType mediaType = new MediaType(); mediaType.setSchema(postSchema); Content content = new Content(); content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType); requestBody.setContent(content); postOperation.setRequestBody(requestBody); //add post and get operations to path /* PathItem pathItem = new PathItem(); pathItem.setPost(postOperation); Paths paths = new Paths(); paths.put("/", pathItem); openAPI.setPaths(paths); }
Example #25
Source File: InlineModelResolverTest.java From swagger-parser with Apache License 2.0 | 5 votes |
@Test public void testInlineMapResponse() throws Exception { OpenAPI openAPI = new OpenAPI(); Schema schema = new Schema(); schema.setAdditionalProperties(new StringSchema()); schema.addExtension("x-ext", "ext-prop"); ApiResponse apiResponse = new ApiResponse(); apiResponse.description("it works!"); MediaType mediaType = new MediaType(); mediaType.setSchema(schema); Content content = new Content(); content.addMediaType("*/*",mediaType); apiResponse.setContent(content); apiResponse.addExtension("x-foo", "bar"); ApiResponses apiResponses = new ApiResponses(); apiResponses.addApiResponse("200",apiResponse); openAPI.path("/foo/baz", new PathItem() .get(new Operation() .responses(apiResponses))); new InlineModelResolver().flatten(openAPI); ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200"); Schema property = response.getContent().get("*/*").getSchema(); assertTrue(property.getAdditionalProperties() != null); assertTrue(openAPI.getComponents().getSchemas() == null); assertEquals(1, property.getExtensions().size()); assertEquals("ext-prop", property.getExtensions().get("x-ext")); }
Example #26
Source File: BodyParamExtractionTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void testConvertComplexArrayBodyParam() throws Exception { Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class); RequestBody body = new RequestBody(). content(new Content() .addMediaType("application/json",new MediaType().schema(new ArraySchema() .items(new Schema().$ref("#/components/schemas/Person"))))); JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0]; assertEquals(jt.getRawClass(), Person[].class); }
Example #27
Source File: OpenApiObjectGenerator.java From flow with Apache License 2.0 | 5 votes |
private MediaType createReturnMediaType( MethodDeclaration methodDeclaration) { MediaType mediaItem = new MediaType(); Type methodReturnType = methodDeclaration.getType(); Schema schema = parseTypeToSchema(methodReturnType, ""); if (methodDeclaration.isAnnotationPresent(Nullable.class)) { schema = schemaResolver.createNullableWrapper(schema); } usedTypes.putAll(collectUsedTypesFromSchema(schema)); mediaItem.schema(schema); return mediaItem; }
Example #28
Source File: InputModeller.java From tcases with MIT License | 5 votes |
/** * Returns the {@link IVarDef input variable definitions} for the given media type content. */ private Stream<IVarDef> mediaTypeContentVars( OpenAPI api, String contentVarTag, Map<String,MediaType> mediaTypes) { return mediaTypes.entrySet().stream() .map( contentDef -> { String mediaType = contentDef.getKey(); return resultFor( mediaType, () -> { String mediaTypeVarName = mediaTypeVarName( mediaType); String mediaTypeVarTag = mediaTypeVarTag( contentVarTag, mediaType); VarSetBuilder contentVar = VarSetBuilder.with( mediaTypeVarName) .when( has( mediaTypeVarTag)); // Schema defined for this media type? Schema<?> mediaTypeSchema = contentDef.getValue().getSchema(); if( mediaTypeSchema == null) { // No, use perfunctory "must be defined" input model for contents notifyWarning( String.format( "No schema defined for media type=%s", mediaType)); contentVar.members( instanceDefinedVar( mediaTypeVarTag, false)); } else { // Yes, use schema input model for contents contentVar.members( instanceSchemaVars( mediaTypeVarTag, false, analyzeSchema( api, mediaTypeSchema))); } return contentVar.build(); }); }); }
Example #29
Source File: MarkdownRender.java From openapi-diff with Apache License 2.0 | 5 votes |
protected String listContent(String prefix, String title, Map<String, MediaType> mediaTypes) { StringBuilder sb = new StringBuilder(); mediaTypes .entrySet() .stream() .map(e -> this.itemContent(title, e.getKey(), e.getValue())) .forEach(e -> sb.append(prefix).append(e)); return sb.toString(); }
Example #30
Source File: ResourceReferenceResponse.java From crnk-framework with Apache License 2.0 | 5 votes |
public ApiResponse response() { return new ApiResponse() .description(HttpStatus.toMessage(200)) .content( new Content() .addMediaType( "application/vnd.api+json", new MediaType() .schema(new ResourceReferenceResponseSchema(metaResource).$ref()))); }