Search in sources :

Example 11 with Callback

use of io.swagger.v3.oas.annotations.callbacks.Callback in project swagger-parser by swagger-api.

the class ExternalRefProcessor method processRefToExternalCallback.

public String processRefToExternalCallback(String $ref, RefFormat refFormat) {
    String renamedRef = cache.getRenamedRef($ref);
    if (renamedRef != null) {
        return renamedRef;
    }
    final Callback callback = cache.loadRef($ref, refFormat, Callback.class);
    if (callback == 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, Callback> callbacks = openAPI.getComponents().getCallbacks();
    if (callbacks == null) {
        callbacks = new LinkedHashMap<>();
    }
    final String possiblyConflictingDefinitionName = computeDefinitionName($ref);
    Callback existingCallback = callbacks.get(possiblyConflictingDefinitionName);
    if (existingCallback != null) {
        LOGGER.debug("A model for " + existingCallback + " already exists");
        if (existingCallback.get$ref() != null) {
            // use the new model
            existingCallback = null;
        }
    }
    newRef = possiblyConflictingDefinitionName;
    cache.putRenamedRef($ref, newRef);
    if (existingCallback == null) {
        // don't overwrite existing model reference
        openAPI.getComponents().addCallbacks(newRef, callback);
        cache.addReferencedKey(newRef);
        String file = $ref.split("#/")[0];
        if (callback.get$ref() != null) {
            if (callback.get$ref() != null) {
                RefFormat format = computeRefFormat(callback.get$ref());
                if (isAnExternalRefFormat(format)) {
                    callback.set$ref(processRefToExternalCallback(callback.get$ref(), format));
                } else {
                    processRefToExternalCallback(file + callback.get$ref(), RefFormat.RELATIVE);
                }
            }
        }
    }
    return newRef;
}
Also used : Components(io.swagger.v3.oas.models.Components) Callback(io.swagger.v3.oas.models.callbacks.Callback) RefUtils.computeRefFormat(io.swagger.v3.parser.util.RefUtils.computeRefFormat) RefUtils.isAnExternalRefFormat(io.swagger.v3.parser.util.RefUtils.isAnExternalRefFormat) RefFormat(io.swagger.v3.parser.models.RefFormat)

Example 12 with Callback

use of io.swagger.v3.oas.annotations.callbacks.Callback in project swagger-parser by swagger-api.

the class OperationProcessor method processOperation.

public void processOperation(Operation operation) {
    final List<Parameter> processedOperationParameters = parameterProcessor.processParameters(operation.getParameters());
    if (processedOperationParameters != null) {
        operation.setParameters(processedOperationParameters);
    }
    final RequestBody requestBody = operation.getRequestBody();
    if (requestBody != null) {
        requestBodyProcessor.processRequestBody(requestBody);
    }
    final Map<String, ApiResponse> responses = operation.getResponses();
    if (responses != null) {
        for (String responseCode : responses.keySet()) {
            ApiResponse response = responses.get(responseCode);
            if (response != null) {
                // This part allows parser to put response schema inline without the resolveFully option set to true
                if (response.get$ref() != null) {
                    responseProcessor.processResponse(response);
                    RefFormat refFormat = computeRefFormat(response.get$ref());
                    ApiResponse resolvedResponse = cache.loadRef(response.get$ref(), refFormat, ApiResponse.class);
                    if (resolvedResponse != null) {
                        response = resolvedResponse;
                        responses.put(responseCode, resolvedResponse);
                    }
                }
                responseProcessor.processResponse(response);
            }
        }
    }
    final Map<String, Callback> callbacks = operation.getCallbacks();
    if (callbacks != null) {
        for (String name : callbacks.keySet()) {
            Callback callback = callbacks.get(name);
            if (callback != null) {
                if (callback.get$ref() != null) {
                    String $ref = callback.get$ref();
                    RefFormat refFormat = computeRefFormat($ref);
                    if (isAnExternalRefFormat(refFormat)) {
                        final String newRef = externalRefProcessor.processRefToExternalCallback($ref, refFormat);
                        if (newRef != null) {
                            callback.set$ref(newRef);
                        }
                    }
                }
                for (String callbackName : callback.keySet()) {
                    PathItem pathItem = callback.get(callbackName);
                    final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap();
                    for (PathItem.HttpMethod httpMethod : operationMap.keySet()) {
                        Operation op = operationMap.get(httpMethod);
                        processOperation(op);
                    }
                    List<Parameter> parameters = pathItem.getParameters();
                    if (parameters != null) {
                        for (Parameter parameter : parameters) {
                            parameterProcessor.processParameter(parameter);
                        }
                    }
                }
            }
        }
    }
}
Also used : RefUtils.isAnExternalRefFormat(io.swagger.v3.parser.util.RefUtils.isAnExternalRefFormat) RefUtils.computeRefFormat(io.swagger.v3.parser.util.RefUtils.computeRefFormat) RefFormat(io.swagger.v3.parser.models.RefFormat) Operation(io.swagger.v3.oas.models.Operation) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) PathItem(io.swagger.v3.oas.models.PathItem) Callback(io.swagger.v3.oas.models.callbacks.Callback) Parameter(io.swagger.v3.oas.models.parameters.Parameter) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 13 with Callback

use of io.swagger.v3.oas.annotations.callbacks.Callback in project swagger-parser by swagger-api.

the class CallbackProcessor method processCallback.

public void processCallback(Callback callback) {
    if (callback.get$ref() != null) {
        processReferenceCallback(callback);
    }
    // Resolver PathItem
    for (String name : callback.keySet()) {
        PathItem pathItem = callback.get(name);
        final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap();
        for (PathItem.HttpMethod httpMethod : operationMap.keySet()) {
            Operation operation = operationMap.get(httpMethod);
            operationProcessor.processOperation(operation);
        }
        List<Parameter> parameters = pathItem.getParameters();
        if (parameters != null) {
            for (Parameter parameter : parameters) {
                parameterProcessor.processParameter(parameter);
            }
        }
    }
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Operation(io.swagger.v3.oas.models.Operation)

Example 14 with Callback

use of io.swagger.v3.oas.annotations.callbacks.Callback in project swagger-parser by swagger-api.

the class OpenAPIResolverTest method componentsResolver.

@Test
public void componentsResolver() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String pathFile = FileUtils.readFileToString(new File("src/test/resources/oas3.yaml.template"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    final JsonNode rootNode = mapper.readTree(pathFile.getBytes());
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);
    Assert.assertNotNull(result);
    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    assertEquals(new OpenAPIResolver(openAPI, new ArrayList<>(), null).resolve(), openAPI);
    Map<String, Schema> schemas = openAPI.getComponents().getSchemas();
    // internal url schema
    Schema pet = schemas.get("Pet");
    Schema category = (Schema) pet.getProperties().get("category");
    assertEquals(category.get$ref(), "#/components/schemas/Category");
    // remote url schema
    Schema user = (Schema) pet.getProperties().get("user");
    assertEquals(user.get$ref(), "#/components/schemas/User");
    // ArraySchema items
    ArraySchema tagsProperty = (ArraySchema) pet.getProperties().get("tags");
    assertEquals(tagsProperty.getItems().get$ref(), "#/components/schemas/ExampleSchema");
    assertEquals(tagsProperty.getType(), "array");
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("ExampleSchema"));
    // Schema not
    assertEquals(schemas.get("OrderRef").getNot().get$ref(), "#/components/schemas/Category");
    // Schema additionalProperties
    assertTrue(schemas.get("OrderRef").getAdditionalProperties() instanceof Schema);
    Schema additionalProperties = (Schema) schemas.get("OrderRef").getAdditionalProperties();
    assertEquals(additionalProperties.get$ref(), "#/components/schemas/User");
    // AllOfSchema
    ComposedSchema extended = (ComposedSchema) schemas.get("ExtendedErrorModel");
    Schema root = (Schema) extended.getAllOf().get(0).getProperties().get("rootCause");
    assertEquals(root.get$ref(), "#/components/schemas/Category");
    Map<String, ApiResponse> responses = openAPI.getComponents().getResponses();
    // internal response headers
    ApiResponse illegalInput = responses.get("IllegalInput");
    assertEquals(illegalInput.getHeaders().get("X-Ref-Limit-Limit").get$ref(), "#/components/headers/X-Rate-Limit-Reset");
    // internal response links
    assertEquals(illegalInput.getLinks().get("address").get$ref(), "#/components/links/unsubscribe");
    // internal url response schema
    MediaType generalError = responses.get("GeneralError").getContent().get("application/json");
    assertEquals(generalError.getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    Map<String, RequestBody> requestBodies = openAPI.getComponents().getRequestBodies();
    // internal url requestBody schema
    RequestBody requestBody1 = requestBodies.get("requestBody1");
    MediaType xmlMedia = requestBody1.getContent().get("application/json");
    assertEquals(xmlMedia.getSchema().get$ref(), "#/components/schemas/Pet");
    // internal url requestBody ArraySchema
    RequestBody requestBody2 = requestBodies.get("requestBody2");
    MediaType jsonMedia = requestBody2.getContent().get("application/json");
    ArraySchema items = (ArraySchema) jsonMedia.getSchema();
    assertEquals(items.getItems().get$ref(), "#/components/schemas/User");
    // internal request body
    assertEquals("#/components/requestBodies/requestBody2", requestBodies.get("requestBody3").get$ref());
    // remote request body url
    assertEquals(requestBodies.get("reference").get$ref(), "#/components/requestBodies/remote_requestBody");
    Map<String, Parameter> parameters = openAPI.getComponents().getParameters();
    // remote url parameter
    assertEquals(parameters.get("remoteParameter").get$ref(), "#/components/parameters/parameter");
    // internal Schema Parameter
    assertEquals(parameters.get("newParam").getSchema().get$ref(), "#/components/schemas/Tag");
    // parameter examples
    assertEquals(parameters.get("contentParameter").getExamples().get("cat"), openAPI.getComponents().getExamples().get("cat"));
    // parameter content schema
    assertEquals(parameters.get("contentParameter").getContent().get("application/json").getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    // internal Schema header
    Map<String, Header> headers = openAPI.getComponents().getHeaders();
    // header remote schema ref
    assertEquals(headers.get("X-Rate-Limit-Remaining").getSchema().get$ref(), "#/components/schemas/User");
    // header examples
    assertEquals(headers.get("X-Rate-Limit-Reset").getExamples().get("headerExample").get$ref(), "#/components/examples/dog");
    // remote header ref
    assertEquals(headers.get("X-Ref-Limit-Limit").get$ref(), "#/components/headers/X-Rate-Limit-Reset");
    // header content
    assertEquals(headers.get("X-Rate-Limit-Reset").getContent().get("application/json").getSchema().get$ref(), "#/components/schemas/ExtendedErrorModel");
    Map<String, Example> examples = openAPI.getComponents().getExamples();
    // internal url example
    Example frogExample = examples.get("frog");
    assertEquals(frogExample.get$ref(), "#/components/examples/cat");
    // remote example url
    assertEquals(examples.get("referenceCat").get$ref(), "#/components/examples/example");
    // internal url securityScheme
    SecurityScheme scheme = openAPI.getComponents().getSecuritySchemes().get("reference");
    assertEquals(scheme.getType(), SecurityScheme.Type.APIKEY);
    SecurityScheme remoteScheme = openAPI.getComponents().getSecuritySchemes().get("remote_reference");
    assertEquals(remoteScheme.getType(), SecurityScheme.Type.OAUTH2);
    Map<String, Link> links = openAPI.getComponents().getLinks();
    // internal link
    assertEquals(openAPI.getComponents().getLinks().get("referenced").get$ref(), "#/components/links/unsubscribe");
    // remote ref link
    assertEquals(openAPI.getComponents().getLinks().get("subscribe").get$ref(), "#/components/links/link");
    Map<String, Callback> callbacks = openAPI.getComponents().getCallbacks();
    // internal callback reference
    assertEquals(callbacks.get("referenced").get$ref(), "#/components/callbacks/failed");
    // callback pathItem -> operation ->requestBody
    assertEquals(callbacks.get("heartbeat").get("$request.query.heartbeat-url").getPost().getRequestBody().get$ref(), "#/components/requestBodies/requestBody3");
    // remote callback ref
    assertEquals(callbacks.get("remoteCallback").get$ref(), "#/components/callbacks/callback");
}
Also used : OpenAPIDeserializer(io.swagger.v3.parser.util.OpenAPIDeserializer) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) JsonNode(com.fasterxml.jackson.databind.JsonNode) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Example(io.swagger.v3.oas.models.examples.Example) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) MediaType(io.swagger.v3.oas.models.media.MediaType) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Callback(io.swagger.v3.oas.models.callbacks.Callback) Header(io.swagger.v3.oas.models.headers.Header) OpenAPIResolver(io.swagger.v3.parser.OpenAPIResolver) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) File(java.io.File) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Link(io.swagger.v3.oas.models.links.Link) Test(org.testng.annotations.Test)

Example 15 with Callback

use of io.swagger.v3.oas.annotations.callbacks.Callback in project OpenOLAT by OpenOLAT.

the class OnlyOfficeWebService method postCallback.

@POST
@Path("/callback")
@Operation(summary = "Post Callback", description = "Post Callback")
@ApiResponse(responseCode = "200", description = "The contents", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = CallbackResponseVO.class)), @Content(mediaType = "application/xml", schema = @Schema(implementation = CallbackResponseVO.class)) })
@ApiResponse(responseCode = "403", description = "Forbidden")
@ApiResponse(responseCode = "404", description = "File not found")
@Produces(MediaType.APPLICATION_JSON)
public Response postCallback(@PathParam("fileId") String fileId, @QueryParam("versionControlled") boolean versionControlled, @Context HttpHeaders httpHeaders) {
    log.debug("ONLYOFFICE REST post callback request for File ID: {}", fileId);
    logRequestHeaders(httpHeaders);
    if (!onlyOfficeModule.isEnabled() || !onlyOfficeModule.isEditorEnabled()) {
        return Response.serverError().status(Status.FORBIDDEN).build();
    }
    if (!onlyOfficeService.fileExists(fileId)) {
        log.debug("File not found. File ID: {}", fileId);
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    String authorisazion = httpHeaders.getHeaderString("Authorization");
    if (!StringHelper.containsNonWhitespace(authorisazion) || !authorisazion.startsWith("Bearer")) {
        log.debug("Missing or invalid authorization header. File ID: {}", fileId);
        return Response.serverError().status(Status.BAD_REQUEST).build();
    }
    // The part after "Bearer "
    String jwtToken = authorisazion.substring(7);
    log.debug("JWT token: {}", jwtToken);
    Callback callback = onlyOfficeSecurityService.getPayload(jwtToken, CallbackImpl.class);
    if (callback == null) {
        log.debug("Error while converting JWT token to callback. File ID: {}", fileId);
        return Response.serverError().status(Status.BAD_REQUEST).build();
    }
    log.debug("Callback: {}", callback);
    CallbackResponseVO responseVO;
    CallbackStatus status = CallbackStatus.valueOf(callback.getStatus());
    switch(status) {
        case Editing:
            // If a document is opened in view mode, ONLYOFFICE does not send an editing callback and therefore the document won't be locked.
            responseVO = doOpenCloseEditor(fileId, callback);
            break;
        case ClosedWithoutChanges:
            responseVO = doFinishContentUnchanged(fileId);
            break;
        case MustSave:
        case MustForceSave:
            responseVO = doFinishContentChanged(fileId, callback, versionControlled);
            break;
        case ErrorCorrupted:
            log.warn("ONLYOFFICE has reported that saving the document has failed. File ID: {}", fileId);
            responseVO = success();
            break;
        case ErrorCorruptedForce:
            log.warn("ONLYOFFICE has reported that saving the document has failed. File ID: {}", fileId);
            responseVO = success();
            break;
        case ErrorDocumentNotFound:
            // I never get that status, so I do not know, how to reproduce it.
            log.warn("ONLYOFFICE has reported that no doc with the specified key can be found. File ID: {}", fileId);
            responseVO = success();
            break;
        default:
            // nothing to do
            responseVO = success();
    }
    return Response.ok(responseVO).build();
}
Also used : Callback(org.olat.core.commons.services.doceditor.onlyoffice.Callback) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Aggregations

Callback (io.swagger.v3.oas.models.callbacks.Callback)19 Operation (io.swagger.v3.oas.models.Operation)13 PathItem (io.swagger.v3.oas.models.PathItem)13 OpenAPI (io.swagger.v3.oas.models.OpenAPI)12 Parameter (io.swagger.v3.oas.models.parameters.Parameter)9 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)9 Test (org.testng.annotations.Test)9 Components (io.swagger.v3.oas.models.Components)7 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)6 Schema (io.swagger.v3.oas.models.media.Schema)6 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 Operation (io.swagger.v3.oas.annotations.Operation)4 Example (io.swagger.v3.oas.models.examples.Example)4 Link (io.swagger.v3.oas.models.links.Link)4 StringSchema (io.swagger.v3.oas.models.media.StringSchema)4 ApiResponses (io.swagger.v3.oas.models.responses.ApiResponses)4 SecurityScheme (io.swagger.v3.oas.models.security.SecurityScheme)4 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4