Search in sources :

Example 61 with RequestBody

use of io.swagger.v3.oas.models.parameters.RequestBody in project snow-owl by b2ihealthcare.

the class FhirBundleController method getBatchResponse.

@Operation(summary = "Perform batch operations", description = "Executes the FHIR requests included in the bundle provided.")
@ApiResponses({ @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "400", description = "Bad Request") })
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = AbstractFhirController.APPLICATION_FHIR_JSON)
public Promise<Bundle> getBatchResponse(@Parameter(name = "bundle", description = "The bundle including the list of requests to perform") @RequestBody final Bundle bundle, HttpServletRequest request) throws JsonProcessingException {
    Collection<Entry> entries = bundle.getEntry();
    Bundle responseBundle = Bundle.builder().language("en").type(BundleType.BATCH_RESPONSE).build();
    ObjectNode rootNode = (ObjectNode) objectMapper.valueToTree(responseBundle);
    ArrayNode arrayNode = rootNode.putArray("entry");
    for (Entry entry : entries) {
        FhirBatchRequestProcessor requestProcessor = FhirBatchRequestProcessor.getInstance(entry, objectMapper, this);
        requestProcessor.process(arrayNode, request);
    }
    Bundle treeToValue = objectMapper.treeToValue(rootNode, Bundle.class);
    return Promise.immediate(treeToValue);
}
Also used : Entry(com.b2international.snowowl.fhir.core.model.Entry) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Bundle(com.b2international.snowowl.fhir.core.model.Bundle) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses)

Example 62 with RequestBody

use of io.swagger.v3.oas.models.parameters.RequestBody in project carbon-apimgt by wso2.

the class OAS3Parser method modifyGraphQLSwagger.

/**
 * 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);
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) JSONObject(org.json.simple.JSONObject) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Content(io.swagger.v3.oas.models.media.Content) Schema(io.swagger.v3.oas.models.media.Schema) MediaType(io.swagger.v3.oas.models.media.MediaType) Operation(io.swagger.v3.oas.models.Operation) Paths(io.swagger.v3.oas.models.Paths) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 63 with RequestBody

use of io.swagger.v3.oas.models.parameters.RequestBody in project carbon-apimgt by wso2.

the class OASParserUtil method processReferenceObjectMap.

private static void processReferenceObjectMap(SwaggerUpdateContext context) {
    // Get a deep copy of the reference objects in order to prevent Concurrent modification exception
    // since we may need to update the reference object mapping while iterating through it
    Map<String, Set<String>> referenceObjectsMappingCopy = getReferenceObjectsCopy(context.getReferenceObjectMapping());
    int preRefObjectCount = getReferenceObjectCount(context.getReferenceObjectMapping());
    Set<Components> aggregatedComponents = context.getAggregatedComponents();
    for (Components sourceComponents : aggregatedComponents) {
        for (Map.Entry<String, Set<String>> refCategoryEntry : referenceObjectsMappingCopy.entrySet()) {
            String category = refCategoryEntry.getKey();
            if (REQUEST_BODIES.equalsIgnoreCase(category)) {
                Map<String, RequestBody> sourceRequestBodies = sourceComponents.getRequestBodies();
                if (sourceRequestBodies != null) {
                    for (String refKey : refCategoryEntry.getValue()) {
                        RequestBody requestBody = sourceRequestBodies.get(refKey);
                        setRefOfRequestBody(requestBody, context);
                    }
                }
            }
            if (SCHEMAS.equalsIgnoreCase(category)) {
                Map<String, Schema> sourceSchemas = sourceComponents.getSchemas();
                if (sourceSchemas != null) {
                    for (String refKey : refCategoryEntry.getValue()) {
                        Schema schema = sourceSchemas.get(refKey);
                        extractReferenceFromSchema(schema, context);
                    }
                }
            }
            if (PARAMETERS.equalsIgnoreCase(category)) {
                Map<String, Parameter> parameters = sourceComponents.getParameters();
                if (parameters != null) {
                    for (String refKey : refCategoryEntry.getValue()) {
                        Parameter parameter = parameters.get(refKey);
                        // Extract the parameter reference only if it exists in the source definition
                        if (parameter != null) {
                            Content content = parameter.getContent();
                            if (content != null) {
                                extractReferenceFromContent(content, context);
                            } else {
                                String ref = parameter.get$ref();
                                if (ref != null) {
                                    extractReferenceWithoutSchema(ref, context);
                                }
                            }
                        }
                    }
                }
            }
            if (RESPONSES.equalsIgnoreCase(category)) {
                Map<String, ApiResponse> responses = sourceComponents.getResponses();
                if (responses != null) {
                    for (String refKey : refCategoryEntry.getValue()) {
                        ApiResponse response = responses.get(refKey);
                        // Extract the response reference only if it exists in the source definition
                        if (response != null) {
                            Content content = response.getContent();
                            extractReferenceFromContent(content, context);
                        }
                    }
                }
            }
            if (HEADERS.equalsIgnoreCase(category)) {
                Map<String, Header> headers = sourceComponents.getHeaders();
                if (headers != null) {
                    for (String refKey : refCategoryEntry.getValue()) {
                        Header header = headers.get(refKey);
                        Content content = header.getContent();
                        extractReferenceFromContent(content, context);
                    }
                }
            }
        }
        int postRefObjectCount = getReferenceObjectCount(context.getReferenceObjectMapping());
        if (postRefObjectCount > preRefObjectCount) {
            processReferenceObjectMap(context);
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Components(io.swagger.v3.oas.models.Components) Header(io.swagger.v3.oas.models.headers.Header) Parameter(io.swagger.v3.oas.models.parameters.Parameter) RefParameter(io.swagger.models.parameters.RefParameter) Map(java.util.Map) HashMap(java.util.HashMap) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 64 with RequestBody

use of io.swagger.v3.oas.models.parameters.RequestBody in project atlasmap by atlasmap.

the class CsvService method inspect.

/**
 * Inspect a CSV instance and return a Document object.
 * @param request request
 * @param format format
 * @param delimiter delimiter
 * @param firstRecordAsHeader first record as header
 * @param skipHeaderRecord skip header record
 * @param headers headers
 * @param commentMarker comment marker
 * @param escape escape
 * @param ignoreEmptyLines ignore empty lines
 * @param ignoreHeaderCase ignore header case
 * @param ignoreSurroundingSpaces ignore surrounding spaces
 * @param nullString null string
 * @param quote quote
 * @param allowDuplicateHeaderNames allow duplicate header names
 * @param allowMissingColumnNames allow missing column names
 * @return {@link CsvInspectionResponse}
 * @throws IOException unexpected error
 */
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Path("/inspect")
@Operation(summary = "Inspect CSV", description = "Inspect a CSV instance and return a Document object")
@RequestBody(description = "Csv", content = @Content(mediaType = "text/csv", schema = @Schema(implementation = String.class)))
@ApiResponses(@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = CsvInspectionResponse.class)), description = "Return a Document object"))
public Response inspect(InputStream request, @QueryParam("format") String format, @QueryParam("delimiter") String delimiter, @QueryParam("firstRecordAsHeader") Boolean firstRecordAsHeader, @QueryParam("skipRecordHeader") Boolean skipHeaderRecord, @QueryParam("headers") String headers, @QueryParam("commentMarker") String commentMarker, @QueryParam("escape") String escape, @QueryParam("ignoreEmptyLines") Boolean ignoreEmptyLines, @QueryParam("ignoreHeaderCase") Boolean ignoreHeaderCase, @QueryParam("ignoreSurroundingSpaces") Boolean ignoreSurroundingSpaces, @QueryParam("nullString") String nullString, @QueryParam("quote") String quote, @QueryParam("allowDuplicateHeaderNames") Boolean allowDuplicateHeaderNames, @QueryParam("allowMissingColumnNames") Boolean allowMissingColumnNames) throws IOException {
    long startTime = System.currentTimeMillis();
    CsvInspectionResponse response = new CsvInspectionResponse();
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Options: delimiter={}, firstRecordAsHeader={}", delimiter, firstRecordAsHeader);
        }
        CsvConfig csvConfig = new CsvConfig(format);
        if (delimiter != null) {
            csvConfig.setDelimiter(delimiter.charAt(0));
        }
        csvConfig.setFirstRecordAsHeader(firstRecordAsHeader);
        csvConfig.setSkipHeaderRecord(skipHeaderRecord);
        csvConfig.setHeaders(headers);
        if (commentMarker != null) {
            csvConfig.setCommentMarker(commentMarker.charAt(0));
        }
        if (escape != null) {
            csvConfig.setEscape(escape.charAt(0));
        }
        csvConfig.setIgnoreEmptyLines(ignoreEmptyLines);
        csvConfig.setIgnoreHeaderCase(ignoreHeaderCase);
        csvConfig.setIgnoreSurroundingSpaces(ignoreSurroundingSpaces);
        csvConfig.setNullString(nullString);
        if (quote != null) {
            csvConfig.setQuote(quote.charAt(0));
        }
        csvConfig.setAllowDuplicateHeaderNames(allowDuplicateHeaderNames);
        csvConfig.setAllowMissingColumnNames(allowMissingColumnNames);
        CsvFieldReader csvFieldReader = new CsvFieldReader(csvConfig);
        csvFieldReader.setDocument(request);
        Document document = csvFieldReader.readSchema();
        response.setCsvDocument(document);
        request.close();
    } catch (Exception e) {
        LOG.error("Error inspecting CSV: " + e.getMessage(), e);
        response.setErrorMessage(e.getMessage());
    } finally {
        request.close();
        ;
        response.setExecutionTime(System.currentTimeMillis() - startTime);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(("Response: {}" + new ObjectMapper().writeValueAsString(response)));
    }
    return Response.ok().entity(toJson(response)).build();
}
Also used : CsvInspectionResponse(io.atlasmap.csv.v2.CsvInspectionResponse) CsvConfig(io.atlasmap.csv.core.CsvConfig) Document(io.atlasmap.v2.Document) CsvFieldReader(io.atlasmap.csv.core.CsvFieldReader) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses) RequestBody(io.swagger.v3.oas.annotations.parameters.RequestBody)

Example 65 with RequestBody

use of io.swagger.v3.oas.models.parameters.RequestBody in project atlasmap by atlasmap.

the class JavaService method inspectClass.

/**
 * Inspects a Java Class with specified fully qualified class name and return a Document object.
 * @param requestIn request
 * @return {@link ClassInspectionResponse}
 */
@POST
@Path("/class")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Operation(summary = "Inspect Class", description = "Inspect a Java Class with specified fully qualified class name and return a Document object")
@RequestBody(description = "ClassInspectionRequest object", content = @Content(schema = @Schema(implementation = ClassInspectionRequest.class)))
@ApiResponses(@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = ClassInspectionResponse.class)), description = "Return a Document object represented by JavaClass"))
public Response inspectClass(InputStream requestIn) {
    ClassInspectionRequest request = fromJson(requestIn, ClassInspectionRequest.class);
    ClassInspectionResponse response = new ClassInspectionResponse();
    ClassInspectionService classInspectionService = new ClassInspectionService();
    classInspectionService.setConversionService(DefaultAtlasConversionService.getInstance());
    configureInspectionService(classInspectionService, request);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Class inspection request: {}", new String(toJson(request)));
    }
    long startTime = System.currentTimeMillis();
    try {
        JavaClass c = null;
        if (request.getClasspath() == null || request.getClasspath().isEmpty()) {
            AtlasService atlasService = resourceContext.getResource(AtlasService.class);
            c = classInspectionService.inspectClass(atlasService.getLibraryLoader(), request.getClassName(), request.getCollectionType(), request.getCollectionClassName());
        } else {
            c = classInspectionService.inspectClass(request.getClassName(), request.getCollectionType(), request.getClasspath());
        }
        response.setJavaClass(c);
    } catch (Throwable e) {
        String msg = String.format("Error inspecting class %s - %s: %s", request.getClassName(), e.getClass().getName(), e.getMessage());
        LOG.error(msg, e);
        response.setErrorMessage(msg);
    } finally {
        response.setExecutionTime(System.currentTimeMillis() - startTime);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Class inspection response: {}", new String(toJson(response)));
    }
    return Response.ok().entity(toJson(response)).build();
}
Also used : ClassInspectionResponse(io.atlasmap.java.v2.ClassInspectionResponse) AtlasService(io.atlasmap.service.AtlasService) JavaClass(io.atlasmap.java.v2.JavaClass) ClassInspectionService(io.atlasmap.java.inspect.ClassInspectionService) ClassInspectionRequest(io.atlasmap.java.v2.ClassInspectionRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses) RequestBody(io.swagger.v3.oas.annotations.parameters.RequestBody)

Aggregations

Test (org.testng.annotations.Test)67 OpenAPI (io.swagger.v3.oas.models.OpenAPI)62 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)59 Schema (io.swagger.v3.oas.models.media.Schema)46 Operation (io.swagger.v3.oas.annotations.Operation)41 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)40 MediaType (io.swagger.v3.oas.models.media.MediaType)36 StringSchema (io.swagger.v3.oas.models.media.StringSchema)35 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)32 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)32 Content (io.swagger.v3.oas.models.media.Content)31 ApiResponses (io.swagger.v3.oas.annotations.responses.ApiResponses)28 Operation (io.swagger.v3.oas.models.Operation)27 PathItem (io.swagger.v3.oas.models.PathItem)23 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)21 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)19 Parameter (io.swagger.v3.oas.models.parameters.Parameter)15 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)14 Components (io.swagger.v3.oas.models.Components)13 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)12