Java Code Examples for io.swagger.v3.oas.models.media.Content#get()

The following examples show how to use io.swagger.v3.oas.models.media.Content#get() . 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: RequestBodyBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build content.
 *
 * @param requestBody the request body
 * @param methodAttributes the method attributes
 * @param schema the schema
 * @param content the content
 */
private void buildContent(RequestBody requestBody, MethodAttributes methodAttributes, Schema<?> schema, Content content) {
	for (String value : methodAttributes.getMethodConsumes()) {
		io.swagger.v3.oas.models.media.MediaType mediaTypeObject = new io.swagger.v3.oas.models.media.MediaType();
		mediaTypeObject.setSchema(schema);
		if (content.get(value) != null) {
			mediaTypeObject.setExample(content.get(value).getExample());
			mediaTypeObject.setExamples(content.get(value).getExamples());
			mediaTypeObject.setEncoding(content.get(value).getEncoding());
		}
		content.addMediaType(value, mediaTypeObject);
	}
	requestBody.setContent(content);
}
 
Example 2
Source File: ContentDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
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 3
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 4
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@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 5
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}