org.eclipse.microprofile.openapi.models.Operation Java Examples

The following examples show how to use org.eclipse.microprofile.openapi.models.Operation. 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: AirlinesOASFilter.java    From microprofile-open-api with Apache License 2.0 6 votes vote down vote up
@Override
public Operation filterOperation(Operation operation) {
    if("Get a booking with ID".equals(operation.getSummary())){
        operation.setSummary("filterOperation - Get a booking with ID");  
    } 
    else if("Update a booking with ID".equals(operation.getSummary())){
        operation.setSummary("filterOperation - Update a booking with ID");  
    }
    else if("Retrieve all available flights".equals(operation.getSummary())){
        operation.setOperationId("filterOperationGetFlights");
    }
    
    List<String> tags = operation.getTags();
    if (tags != null) {
        if (tags.contains("Bookings")) {
            tags = new ArrayList<>(tags);
            tags.set(tags.indexOf("Bookings"), "parent - Bookings");
            operation.setTags(tags);
        }
    }
    return operation;
}
 
Example #2
Source File: ServersUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the servers for an Operation.
 * 
 * @param config OpenApiConfig
 * @param operation Operation
 */
protected static void configureServers(OpenApiConfig config, Operation operation) {
    if (operation == null) {
        return;
    }
    if (operation.getOperationId() == null) {
        return;
    }

    Set<String> operationServers = config.operationServers(operation.getOperationId());
    if (operationServers != null && !operationServers.isEmpty()) {
        operation.servers(new ArrayList<>());
        for (String operationServer : operationServers) {
            Server server = new ServerImpl();
            server.setUrl(operationServer);
            operation.addServer(server);
        }
    }
}
 
Example #3
Source File: PathsReader.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the PathItem.
 * Also used in CallbackOperation
 * 
 * @param context the scanning context
 * @param annotationValue the annotation value
 * @return PathItem model
 */
public static PathItem readPathItem(final AnnotationScannerContext context,
        final AnnotationValue annotationValue) {
    if (annotationValue == null) {
        return null;
    }

    AnnotationInstance[] nestedArray = annotationValue.asNestedArray();
    PathItem pathItem = new PathItemImpl();
    for (AnnotationInstance operationAnno : nestedArray) {
        String method = JandexUtil.stringValue(operationAnno, PathsConstant.PROP_METHOD);
        Operation operation = OperationReader.readOperation(context, operationAnno);
        if (method == null) {
            continue;
        }
        try {
            PropertyDescriptor descriptor = new PropertyDescriptor(method.toUpperCase(), pathItem.getClass());
            Method mutator = descriptor.getWriteMethod();
            mutator.invoke(pathItem, operation);
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            IoLogging.log.readingCallbackOperation(e);
        }
    }
    return pathItem;
}
 
Example #4
Source File: OperationWriter.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a {@link Operation} to the JSON tree.
 * 
 * @param parent the parent json node
 * @param model the Operation model
 * @param method the name of the node (operation method)
 */
public static void writeOperation(ObjectNode parent, Operation model, String method) {
    if (model == null) {
        return;
    }
    ObjectNode node = parent.putObject(method);
    ObjectWriter.writeStringArray(node, model.getTags(), OperationConstant.PROP_TAGS);
    JsonUtil.stringProperty(node, OperationConstant.PROP_SUMMARY, model.getSummary());
    JsonUtil.stringProperty(node, OperationConstant.PROP_DESCRIPTION, model.getDescription());
    ExternalDocsWriter.writeExternalDocumentation(node, model.getExternalDocs());
    JsonUtil.stringProperty(node, OperationConstant.PROP_OPERATION_ID, model.getOperationId());
    ParameterWriter.writeParameterList(node, model.getParameters());
    RequestBodyWriter.writeRequestBody(node, model.getRequestBody());
    ResponseWriter.writeAPIResponses(node, model.getResponses());
    CallbackWriter.writeCallbacks(node, model.getCallbacks());
    JsonUtil.booleanProperty(node, OperationConstant.PROP_DEPRECATED, model.getDeprecated());
    SecurityRequirementWriter.writeSecurityRequirements(node, model.getSecurity());
    ServerWriter.writeServers(node, model.getServers());
    ExtensionWriter.writeExtensions(node, model);
}
 
Example #5
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a {@link Operation} OpenAPI node.
 * 
 * @param node json object
 * @return Operation model
 */
public static Operation readOperation(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    IoLogging.log.singleJsonObject("Operation");
    Operation model = new OperationImpl();
    model.setTags(JsonUtil.readStringArray(node.get(OperationConstant.PROP_TAGS)).orElse(null));
    model.setSummary(JsonUtil.stringProperty(node, OperationConstant.PROP_SUMMARY));
    model.setDescription(JsonUtil.stringProperty(node, OperationConstant.PROP_DESCRIPTION));
    model.setExternalDocs(ExternalDocsReader.readExternalDocs(node.get(ExternalDocsConstant.PROP_EXTERNAL_DOCS)));
    model.setOperationId(JsonUtil.stringProperty(node, OperationConstant.PROP_OPERATION_ID));
    model.setParameters(ParameterReader.readParameterList(node.get(OperationConstant.PROP_PARAMETERS)).orElse(null));
    model.setRequestBody(RequestBodyReader.readRequestBody(node.get(OperationConstant.PROP_REQUEST_BODY)));
    model.setResponses(ResponseReader.readResponses(node.get(OperationConstant.PROP_RESPONSES)));
    model.setCallbacks(CallbackReader.readCallbacks(node.get(OperationConstant.PROP_CALLBACKS)));
    model.setDeprecated(JsonUtil.booleanProperty(node, OperationConstant.PROP_DEPRECATED).orElse(null));
    model.setSecurity(
            SecurityRequirementReader.readSecurityRequirements(node.get(OperationConstant.PROP_SECURITY)).orElse(null));
    model.setServers(ServerReader.readServers(node.get(OperationConstant.PROP_SERVERS)).orElse(null));
    ExtensionReader.readExtensions(node, model);
    return model;
}
 
Example #6
Source File: JavaSecurityProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Add method-level or resource-level <code>RolesAllowed</code> values as
 * scopes to the current operation.
 * 
 * <ul>
 * <li>If a <code>DenyAll</code> annotation is present (and a method-level
 * <code>RolesAllowed</code> is not), the roles allowed will be set to an
 * empty array.
 * 
 * <li>If none of a <code>PermitAll</code>, a <code>DenyAll</code>, and a
 * <code>RolesAllowed</code> annotation is present at the method-level, the
 * roles allowed will be set to the resource's <code>RolesAllowed</code>.
 * </ul>
 * 
 * @param method the current JAX-RS method
 * @param operation the OpenAPI Operation
 */
private void processSecurityRolesForMethodOperation(MethodInfo method, Operation operation) {
    if (this.currentSecurityScheme != null) {
        String[] rolesAllowed = TypeUtil.getAnnotationValue(method, SecurityConstants.ROLES_ALLOWED);

        if (rolesAllowed != null) {
            addScopes(rolesAllowed);
            addRolesAllowed(operation, rolesAllowed);
        } else if (this.resourceRolesAllowed != null) {
            boolean denyAll = TypeUtil.getAnnotation(method, SecurityConstants.DENY_ALL) != null;
            boolean permitAll = TypeUtil.getAnnotation(method, SecurityConstants.PERMIT_ALL) != null;

            if (denyAll) {
                addRolesAllowed(operation, new String[0]);
            } else if (!permitAll) {
                addRolesAllowed(operation, this.resourceRolesAllowed);
            }
        }
    }
}
 
Example #7
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Process a callback annotation
 * 
 * @param context the scanning context
 * @param method the method
 * @param operation the operation to add this to
 */
default void processCallback(final AnnotationScannerContext context, final MethodInfo method, Operation operation) {
    List<AnnotationInstance> callbackAnnotations = CallbackReader.getCallbackAnnotations(method);

    Map<String, Callback> callbacks = new LinkedHashMap<>();
    for (AnnotationInstance annotation : callbackAnnotations) {
        String name = CallbackReader.getCallbackName(annotation);
        if (name == null && JandexUtil.isRef(annotation)) {
            name = JandexUtil.nameFromRef(annotation);
        }
        if (name != null) {
            callbacks.put(name, CallbackReader.readCallback(context, annotation));
        }

        if (!callbacks.isEmpty()) {
            operation.setCallbacks(callbacks);
        }
    }
}
 
Example #8
Source File: OpenApiSpecStyleValidator.java    From openapi-style-validator with Apache License 2.0 5 votes vote down vote up
private void validateOperations() {
    for (String key : openAPI.getPaths().getPathItems().keySet()) {
        PathItem path = openAPI.getPaths().getPathItems().get(key);
        for (PathItem.HttpMethod method : path.getOperations().keySet()) {
            Operation op = path.getOperations().get(method);
            if (parameters.isValidateOperationOperationId()) {
                if (op.getOperationId() == null || op.getOperationId().isEmpty()) {
                    errorAggregator.logMissingOrEmptyOperationAttribute(key, method, "operationId");
                }
            }

            if (parameters.isValidateOperationDescription()) {
                if (op.getDescription() == null || op.getDescription().isEmpty()) {
                    errorAggregator.logMissingOrEmptyOperationAttribute(key, method, "description");
                }
            }

            if (parameters.isValidateOperationSummary()) {
                if (op.getSummary() == null || op.getSummary().isEmpty()) {
                    errorAggregator.logMissingOrEmptyOperationAttribute(key, method, "summary");
                }
            }

            if (parameters.isValidateOperationTag()) {
                if (op.getTags() == null || op.getTags().isEmpty()) {
                    errorAggregator.logMissingOrEmptyOperationCollection(key, method, "tags");
                }
            }
        }
    }
}
 
Example #9
Source File: FilterUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Filters the given model.
 * 
 * @param filter
 * @param model
 */
private static void filterOperation(OASFilter filter, Operation model) {
    if (model != null) {
        filterCallbacks(filter, model.getCallbacks());
        model.setParameters(filterParameterList(filter, model.getParameters()));
        filterRequestBody(filter, model.getRequestBody());
        if (model.getRequestBody() != null && filter.filterRequestBody(model.getRequestBody()) == null) {
            model.setRequestBody(null);
        }
        if (model.getResponses() != null) {
            filterAPIResponses(filter, model.getResponses().getAPIResponses());
        }
        filterServers(filter, model.getServers());
    }
}
 
Example #10
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process tags.
 * Tag and Tags annotations combines with the resource tags we've already found (passed in)
 * 
 * @param method the REST method
 * @param openApi the OpenApi model
 * @param resourceTags tags passed in
 * @param operation the current operation
 */
default void processOperationTags(final MethodInfo method, OpenAPI openApi, Set<String> resourceTags,
        final Operation operation) {
    // 
    Set<String> tags = processTags(method, openApi, true);
    if (tags == null) {
        if (!resourceTags.isEmpty()) {
            operation.setTags(new ArrayList<>(resourceTags));
        }
    } else if (!tags.isEmpty()) {
        operation.setTags(new ArrayList<>(tags));
    }
}
 
Example #11
Source File: PathItemImpl.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.eclipse.microprofile.openapi.models.PathItem#getOperations()
 */
@Override
public Map<HttpMethod, Operation> getOperations() {
    Map<HttpMethod, Operation> ops = new LinkedHashMap<>();
    addOperationToMap(HttpMethod.GET, this.get, ops);
    addOperationToMap(HttpMethod.PUT, this.put, ops);
    addOperationToMap(HttpMethod.POST, this.post, ops);
    addOperationToMap(HttpMethod.DELETE, this.delete, ops);
    addOperationToMap(HttpMethod.OPTIONS, this.options, ops);
    addOperationToMap(HttpMethod.HEAD, this.head, ops);
    addOperationToMap(HttpMethod.PATCH, this.patch, ops);
    addOperationToMap(HttpMethod.TRACE, this.trace, ops);
    return ops;
}
 
Example #12
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * While scanning JAX-RS/Spring method, find the operations
 * 
 * @param context the scanning context
 * @param method the JAX-RS/Spring method
 * @return Maybe an Operation model
 */
default Optional<Operation> processOperation(final AnnotationScannerContext context, final MethodInfo method) {
    if (OperationReader.methodHasOperationAnnotation(method)) {
        if (OperationReader.operationIsHidden(method)) {
            return Optional.empty();
        }
        AnnotationInstance operationAnnotation = OperationReader.getOperationAnnotation(method);
        return Optional.of(OperationReader.readOperation(context, operationAnnotation));
    } else {
        return Optional.of(new OperationImpl());
    }
}
 
Example #13
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
default void processResponse(final AnnotationScannerContext context, final MethodInfo method, Operation operation,
        Map<DotName, AnnotationInstance> exceptionAnnotationMap) {

    List<AnnotationInstance> apiResponseAnnotations = ResponseReader.getResponseAnnotations(method);
    for (AnnotationInstance annotation : apiResponseAnnotations) {
        addApiReponseFromAnnotation(context, annotation, operation);
    }

    AnnotationInstance responseSchemaAnnotation = ResponseReader.getResponseSchemaAnnotation(method);
    addApiReponseSchemaFromAnnotation(context, responseSchemaAnnotation, method, operation);

    /*
     * If there is no response from annotations, try to create one from the method return value.
     * Do not generate a response if the app has used an empty @ApiResponses annotation. This
     * provides a way for the application to indicate that responses will be supplied some other
     * way (i.e. static file).
     */
    AnnotationInstance apiResponses = ResponseReader.getResponsesAnnotation(method);
    if (apiResponses == null || !JandexUtil.isEmpty(apiResponses)) {
        createResponseFromRestMethod(context, method, operation);
    }

    //Add api response using list of exceptions in the methods and exception mappers
    List<Type> methodExceptions = method.exceptions();

    for (Type type : methodExceptions) {
        DotName exceptionDotName = type.name();
        if (exceptionAnnotationMap != null && !exceptionAnnotationMap.isEmpty()
                && exceptionAnnotationMap.keySet().contains(exceptionDotName)) {
            AnnotationInstance exMapperApiResponseAnnotation = exceptionAnnotationMap.get(exceptionDotName);
            if (!this.responseCodeExistInMethodAnnotations(exMapperApiResponseAnnotation, apiResponseAnnotations)) {
                addApiReponseFromAnnotation(context, exMapperApiResponseAnnotation, operation);
            }
        }
    }
}
 
Example #14
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Add api response to api responses using the annotation information
 *
 * @param context The current scanning context
 * @param apiResponseAnnotation The api response annotation
 * @param operation The method operation
 */
default void addApiReponseFromAnnotation(final AnnotationScannerContext context, AnnotationInstance apiResponseAnnotation,
        Operation operation) {
    String responseCode = ResponseReader.getResponseName(apiResponseAnnotation);
    if (responseCode == null) {
        responseCode = APIResponses.DEFAULT;
    }
    APIResponse response = ResponseReader.readResponse(context, apiResponseAnnotation);
    APIResponses responses = ModelUtil.responses(operation);
    responses.addAPIResponse(responseCode, response);
}
 
Example #15
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Add api response to api responses using the annotation information
 * 
 * @param context the scanning context
 * @param annotation The APIResponseSchema annotation
 * @param method the current method
 * @param operation the method operation
 */
default void addApiReponseSchemaFromAnnotation(AnnotationScannerContext context,
        AnnotationInstance annotation,
        MethodInfo method,
        Operation operation) {

    if (annotation == null) {
        return;
    }

    String responseCode = ResponseReader.getResponseName(annotation);
    final int status;

    if (responseCode != null && responseCode.matches("\\d{3}")) {
        status = Integer.parseInt(responseCode);
    } else {
        status = getDefaultStatus(method);
        responseCode = String.valueOf(status);
    }

    APIResponse response = ResponseReader.readResponseSchema(context, annotation);

    if (response.getDescription() == null) {
        response.setDescription(getReasonPhrase(status));
    }

    APIResponses responses = ModelUtil.responses(operation);
    responses.addAPIResponse(responseCode, response);
}
 
Example #16
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Get the security requirements on method and class and add them to the openapi model
 * 
 * @param resourceClass the class
 * @param method the method
 * @param operation the operation to add them to
 */
default void processSecurityRequirementAnnotation(final ClassInfo resourceClass, final MethodInfo method,
        Operation operation) {

    List<AnnotationInstance> securityRequirementAnnotations = SecurityRequirementReader
            .getSecurityRequirementAnnotations(method);
    securityRequirementAnnotations.addAll(SecurityRequirementReader.getSecurityRequirementAnnotations(resourceClass));

    for (AnnotationInstance annotation : securityRequirementAnnotations) {
        SecurityRequirement requirement = SecurityRequirementReader.readSecurityRequirement(annotation);
        if (requirement != null) {
            operation.addSecurityRequirement(requirement);
        }
    }
}
 
Example #17
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process a certain method for server annotations.
 * 
 * @param method the method that contain the server annotation
 * @param operation the current Operation model being created
 */
default void processServerAnnotation(final MethodInfo method, Operation operation) {
    List<AnnotationInstance> serverAnnotations = ServerReader.getServerAnnotations(method);
    if (serverAnnotations.isEmpty()) {
        serverAnnotations.addAll(ServerReader.getServerAnnotations(method.declaringClass()));
    }
    for (AnnotationInstance annotation : serverAnnotations) {
        Server server = ServerReader.readServer(annotation);
        operation.addServer(server);
    }
}
 
Example #18
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process the Extensions annotations
 * 
 * @param context the scanning context
 * @param method the current REST method
 * @param operation the current operation
 */
default void processExtensions(final AnnotationScannerContext context, final MethodInfo method, Operation operation) {
    List<AnnotationInstance> extensionAnnotations = ExtensionReader.getExtensionsAnnotations(method);

    if (extensionAnnotations.isEmpty()) {
        extensionAnnotations.addAll(ExtensionReader.getExtensionsAnnotations(method.declaringClass()));
    }
    for (AnnotationInstance annotation : extensionAnnotations) {
        if (annotation.target() == null || !METHOD_PARAMETER.equals(annotation.target().kind())) {
            String name = ExtensionReader.getExtensionName(annotation);
            operation.addExtension(name, ExtensionReader.readExtensionValue(context, name, annotation));
        }
    }
}
 
Example #19
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Set the created operation to the pathItem
 * 
 * @param methodType the HTTP method type
 * @param pathItem the pathItem to set
 * @param operation the operation
 */
default void setOperationOnPathItem(PathItem.HttpMethod methodType, PathItem pathItem, Operation operation) {
    switch (methodType) {
        case DELETE:
            pathItem.setDELETE(operation);
            break;
        case GET:
            pathItem.setGET(operation);
            break;
        case HEAD:
            pathItem.setHEAD(operation);
            break;
        case OPTIONS:
            pathItem.setOPTIONS(operation);
            break;
        case PATCH:
            pathItem.setPATCH(operation);
            break;
        case POST:
            pathItem.setPOST(operation);
            break;
        case PUT:
            pathItem.setPUT(operation);
            break;
        case TRACE:
            pathItem.setTRACE(operation);
            break;
        default:
            break;
    }
}
 
Example #20
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a single Operation annotation.
 * 
 * @param context the scanning context
 * @param annotationInstance {@literal @}CallbackOperation annotation
 * @return Operation model
 */
public static Operation readOperation(final AnnotationScannerContext context,
        final AnnotationInstance annotationInstance) {
    if (annotationInstance == null) {
        return null;
    }
    IoLogging.log.singleAnnotation("@Operation");
    Operation operation = new OperationImpl();
    operation.setSummary(JandexUtil.stringValue(annotationInstance, OperationConstant.PROP_SUMMARY));
    operation.setDescription(JandexUtil.stringValue(annotationInstance, OperationConstant.PROP_DESCRIPTION));
    operation.setExternalDocs(
            ExternalDocsReader.readExternalDocs(annotationInstance.value(ExternalDocsConstant.PROP_EXTERNAL_DOCS)));
    operation.setParameters(ParameterReader.readParametersList(context,
            annotationInstance.value(OperationConstant.PROP_PARAMETERS)).orElse(null));
    operation.setRequestBody(RequestBodyReader.readRequestBody(context,
            annotationInstance.value(OperationConstant.PROP_REQUEST_BODY)));
    operation.setResponses(ResponseReader.readResponses(context,
            annotationInstance.value(OperationConstant.PROP_RESPONSES)));
    operation.setSecurity(SecurityRequirementReader
            .readSecurityRequirements(annotationInstance.value(OperationConstant.PROP_SECURITY)).orElse(null));
    operation.setExtensions(
            ExtensionReader.readExtensions(context,
                    annotationInstance.value(OperationConstant.PROP_EXTENSIONS)));

    // Below is only used in Jax-rs ??
    // Operation Id ??
    operation.setOperationId(JandexUtil.stringValue(annotationInstance, OperationConstant.PROP_OPERATION_ID));
    // Deprecated ??
    operation.setDeprecated(JandexUtil.booleanValue(annotationInstance, OperationConstant.PROP_DEPRECATED).orElse(null));

    // Below is not used ?
    // Tags ?
    // Callbacks
    // Servers
    return operation;
}
 
Example #21
Source File: OASFactoryResolverImplTest.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for
 * {@link OASFactoryResolverImpl#createObject(java.lang.Class)}.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testCreateObject_All() {
    Class modelClasses[] = { APIResponse.class, APIResponses.class, Callback.class, Components.class,
            Contact.class, Content.class, Discriminator.class, Encoding.class, Example.class,
            ExternalDocumentation.class, Header.class, Info.class, License.class, Link.class, MediaType.class,
            OAuthFlow.class, OAuthFlows.class, OpenAPI.class, Operation.class, Parameter.class, PathItem.class,
            Paths.class, RequestBody.class, Schema.class, SecurityRequirement.class,
            SecurityScheme.class, Server.class, ServerVariable.class, Tag.class, XML.class };
    for (Class modelClass : modelClasses) {
        Constructible object = OASFactory.createObject(modelClass);
        Assert.assertNotNull(object);
    }
}
 
Example #22
Source File: OperationHyphenFilter.java    From microprofile1.4-samples with MIT License 5 votes vote down vote up
/**
 * Replaces all spaces in each operation id with a hyphen.
 */
@Override
public Operation filterOperation(Operation operation) {
    if (operation.getOperationId().contains((" "))) {
        operation.setOperationId(operation.getOperationId().replace(" ", "-"));
    }

    return operation;
}
 
Example #23
Source File: AirlinesOASFilter.java    From microprofile-open-api with Apache License 2.0 5 votes vote down vote up
@Override
public PathItem filterPathItem(PathItem pathItem){
    if(pathItem.getGET() != null && "Retrieve all available flights".equals(pathItem.getGET().getSummary())){
        //Add new operation
        pathItem.PUT(OASFactory.createObject(Operation.class).
                summary("filterPathItem - added put operation")
                .responses(OASFactory.createObject(APIResponses.class).addAPIResponse("200", 
                        OASFactory.createObject(APIResponse.class).description("filterPathItem - successfully put airlines"))));
        
        //Spec states : All filterable descendant elements of a filtered element must be called before its ancestor
        //Override the operatioId value that was previously overridden by the filterOperation method
        pathItem.getGET().setOperationId("filterPathItemGetFlights");
    }
    
    if (pathItem.getPOST() != null && "createBooking".equals(pathItem.getPOST().getOperationId())) {
        Map<String, Callback> callbacks = pathItem.getPOST().getCallbacks();
        if (callbacks.containsKey("bookingCallback")) {
            Callback callback = callbacks.get("bookingCallback");
            if (callback.hasPathItem("http://localhost:9080/airlines/bookings")
                    && callback.getPathItem("http://localhost:9080/airlines/bookings").getGET() != null) {
                if ("child - Retrieve all bookings for current user".equals(callback.getPathItem("http://localhost:9080/airlines/bookings")
                        .getGET().getDescription())) {   
                    callback.getPathItem("http://localhost:9080/airlines/bookings").getGET()
                    .setDescription("parent - Retrieve all bookings for current user"); 
                }
            }
        }   
    }
    
    return pathItem;
}
 
Example #24
Source File: JavaSecurityProcessor.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static void processSecurityRoles(MethodInfo method, Operation operation) {
    current.get().processSecurityRolesForMethodOperation(method, operation);
}
 
Example #25
Source File: ModelConstructionTest.java    From microprofile-open-api with Apache License 2.0 4 votes vote down vote up
@Test
public void operationTest() {
    final Operation o = processConstructible(Operation.class);
    
    final Parameter p = createConstructibleInstance(Parameter.class);
    checkSameObject(o, o.addParameter(p));
    checkListEntry(o.getParameters(), p);
    assertEquals(o.getParameters().size(), 1, "The list is expected to contain one entry.");
    o.removeParameter(p);
    assertEquals(o.getParameters().size(), 0, "The list is expected to be empty.");
    
    final Parameter p2 = createConstructibleInstance(Parameter.class);
    o.setParameters(Collections.singletonList(p2));
    assertEquals(o.getParameters().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(o.getParameters(), p2);
    checkSameObject(o, o.addParameter(p));
    assertEquals(o.getParameters().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(o.getParameters(), p);
    
    Parameter otherParameter  = createConstructibleInstance(Parameter.class);
    checkListImmutable(o, Operation::getParameters, otherParameter);
    
    final SecurityRequirement sr = createConstructibleInstance(SecurityRequirement.class);
    sr.addScheme("OAuth2", Arrays.asList("read", "write"));
    checkSameObject(o, o.addSecurityRequirement(sr));
    checkListEntry(o.getSecurity(), sr);
    assertEquals(o.getSecurity().size(), 1, "The list is expected to contain one entry.");
    o.removeSecurityRequirement(sr);
    assertEquals(o.getSecurity().size(), 0, "The list is expected to be empty.");
    
    final SecurityRequirement sr2 = createConstructibleInstance(SecurityRequirement.class);
    sr2.addScheme("ApiKey");
    o.setSecurity(Collections.singletonList(sr2));
    assertEquals(o.getSecurity().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(o.getSecurity(), sr2);
    checkSameObject(o, o.addSecurityRequirement(sr));
    assertEquals(o.getSecurity().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(o.getSecurity(), sr);
    
    SecurityRequirement otherSecurityRequirement  = createConstructibleInstance(SecurityRequirement.class);
    otherSecurityRequirement.addScheme("BasicAuth");
    checkListImmutable(o, Operation::getSecurity, otherSecurityRequirement);
    
    final Server s = createConstructibleInstance(Server.class);
    checkSameObject(o, o.addServer(s));
    checkListEntry(o.getServers(), s);
    assertEquals(o.getServers().size(), 1, "The list is expected to contain one entry.");
    o.removeServer(s);
    assertEquals(o.getServers().size(), 0, "The list is expected to be empty.");
    
    final Server s2 = createConstructibleInstance(Server.class);
    o.setServers(Collections.singletonList(s2));
    assertEquals(o.getServers().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(o.getServers(), s2);
    checkSameObject(o, o.addServer(s));
    assertEquals(o.getServers().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(o.getServers(), s);
    
    Server otherServer  = createConstructibleInstance(Server.class);
    checkListImmutable(o, Operation::getServers, otherServer);
    
    final String tag = new String("myTag");
    checkSameObject(o, o.addTag(tag));
    checkListEntry(o.getTags(), tag);
    assertEquals(o.getTags().size(), 1, "The list is expected to contain one entry.");
    o.removeTag(tag);
    assertEquals(o.getTags().size(), 0, "The list is expected to be empty.");
    
    final String tag2 = new String("myTag2");
    o.setTags(Collections.singletonList(tag2));
    assertEquals(o.getTags().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(o.getTags(), tag2);
    checkSameObject(o, o.addTag(tag));
    assertEquals(o.getTags().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(o.getTags(), tag);
    
    String otherTag  = new String("otherTag");
    checkListImmutable(o, Operation::getTags, otherTag);
    
    final String callbackKey = "myCallback";
    final Callback callbackValue = createConstructibleInstance(Callback.class);
    checkSameObject(o, o.addCallback(callbackKey, callbackValue));
    checkMapEntry(o.getCallbacks(), callbackKey, callbackValue);
    assertEquals(o.getCallbacks().size(), 1, "The map is expected to contain one entry.");
    o.removeCallback(callbackKey);
    assertEquals(o.getCallbacks().size(), 0, "The map is expected to be empty.");
    
    final String callbackKey2 = "myCallbackKey2";
    final Callback callbackValue2 = createConstructibleInstance(Callback.class);
    o.setCallbacks(Collections.singletonMap(callbackKey2, callbackValue2));
    checkMapEntry(o.getCallbacks(), callbackKey2, callbackValue2);
    assertEquals(o.getCallbacks().size(), 1, "The map is expected to contain one entry.");
    checkSameObject(o, o.addCallback(callbackKey, callbackValue));
    checkMapEntry(o.getCallbacks(), callbackKey, callbackValue);
    assertEquals(o.getCallbacks().size(), 2, "The map is expected to contain two entries.");
    
    Callback otherCallback  = createConstructibleInstance(Callback.class);
    checkMapImmutable(o, Operation::getCallbacks, "otherCallback", otherCallback);
    checkNullValueInAdd(o::getCallbacks, o::addCallback, "someCallback", callbackValue);
}
 
Example #26
Source File: ModelConstructionTest.java    From microprofile-open-api with Apache License 2.0 4 votes vote down vote up
@Test
public void pathItemTest() {
    final PathItem pi = processConstructible(PathItem.class);
    
    final Parameter p = createConstructibleInstance(Parameter.class);
    checkSameObject(pi, pi.addParameter(p));
    checkListEntry(pi.getParameters(), p);
    assertEquals(pi.getParameters().size(), 1, "The list is expected to contain one entry.");
    pi.removeParameter(p);
    assertEquals(pi.getParameters().size(), 0, "The list is expected to be empty.");
    
    final Parameter p2 = createConstructibleInstance(Parameter.class);
    pi.setParameters(Collections.singletonList(p2));
    assertEquals(pi.getParameters().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(pi.getParameters(), p2);
    checkSameObject(pi, pi.addParameter(p));
    assertEquals(pi.getParameters().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(pi.getParameters(), p);
    
    Parameter otherParameter  = createConstructibleInstance(Parameter.class);
    checkListImmutable(pi, PathItem::getParameters, otherParameter);
    
    final Server s = createConstructibleInstance(Server.class);
    checkSameObject(pi, pi.addServer(s));
    checkListEntry(pi.getServers(), s);
    assertEquals(pi.getServers().size(), 1, "The list is expected to contain one entry.");
    pi.removeServer(s);
    assertEquals(pi.getServers().size(), 0, "The list is expected to be empty.");
    
    final Server s2 = createConstructibleInstance(Server.class);
    pi.setServers(Collections.singletonList(s2));
    assertEquals(pi.getServers().size(), 1, "The list is expected to contain one entry.");
    checkListEntry(pi.getServers(), s2);
    checkSameObject(pi, pi.addServer(s));
    assertEquals(pi.getServers().size(), 2, "The list is expected to contain two entries.");
    checkListEntry(pi.getServers(), s);
    
    Server otherServer  = createConstructibleInstance(Server.class);
    checkListImmutable(pi, PathItem::getServers, otherServer);
    
    final Operation o1 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.GET(o1));
    checkSameObject(o1, pi.getGET());
    
    final Operation o2 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.PUT(o2));
    checkSameObject(o2, pi.getPUT());
    
    final Operation o3 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.POST(o3));
    checkSameObject(o3, pi.getPOST());
    
    final Operation o4 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.DELETE(o4));
    checkSameObject(o4, pi.getDELETE());
    
    final Operation o5 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.OPTIONS(o5));
    checkSameObject(o5, pi.getOPTIONS());
    
    final Operation o6 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.HEAD(o6));
    checkSameObject(o6, pi.getHEAD());
    
    final Operation o7 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.PATCH(o7));
    checkSameObject(o7, pi.getPATCH());
    
    final Operation o8 = createConstructibleInstance(Operation.class);
    checkSameObject(pi, pi.TRACE(o8));
    checkSameObject(o8, pi.getTRACE());
    
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.GET, o1);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.PUT, o2);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.POST, o3);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.DELETE, o4);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.OPTIONS, o5);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.HEAD, o6);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.PATCH, o7);
    checkMapEntry(pi.getOperations(), PathItem.HttpMethod.TRACE, o8);
}
 
Example #27
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * Process a single Spring method to produce an OpenAPI Operation.
 *
 * @param openApi
 * @param resourceClass
 * @param method
 * @param methodType
 * @param resourceTags
 * @param locatorPathParameters
 */
private void processControllerMethod(final AnnotationScannerContext context,
        final ClassInfo resourceClass,
        final MethodInfo method,
        final PathItem.HttpMethod methodType,
        OpenAPI openApi,
        Set<String> resourceTags,
        List<Parameter> locatorPathParameters) {

    SpringLogging.log.processingMethod(method.toString());

    // Figure out the current @Produces and @Consumes (if any)
    CurrentScannerInfo.setCurrentConsumes(getMediaTypes(method, MediaTypeProperty.consumes).orElse(null));
    CurrentScannerInfo.setCurrentProduces(getMediaTypes(method, MediaTypeProperty.produces).orElse(null));

    // Process any @Operation annotation
    Optional<Operation> maybeOperation = processOperation(context, method);
    if (!maybeOperation.isPresent()) {
        return; // If the operation is marked as hidden, just bail here because we don't want it as part of the model.
    }
    final Operation operation = maybeOperation.get();

    // Process tags - @Tag and @Tags annotations combines with the resource tags we've already found (passed in)
    processOperationTags(method, openApi, resourceTags, operation);

    // Process @Parameter annotations.
    PathItem pathItem = new PathItemImpl();
    Function<AnnotationInstance, Parameter> reader = t -> ParameterReader.readParameter(context, t);
    ResourceParameters params = ParameterProcessor.process(context.getIndex(), resourceClass, method, reader,
            context.getExtensions());
    operation.setParameters(params.getOperationParameters());

    pathItem.setParameters(ListUtil.mergeNullableLists(locatorPathParameters, params.getPathItemParameters()));

    // Process any @RequestBody annotation (note: the @RequestBody annotation can be found on a method argument *or* on the method)
    RequestBody requestBody = processRequestBody(context, method, params);
    if (requestBody != null) {
        operation.setRequestBody(requestBody);
    }

    // Process @APIResponse annotations
    processResponse(context, method, operation, null);

    // Process @SecurityRequirement annotations
    processSecurityRequirementAnnotation(resourceClass, method, operation);

    // Process @Callback annotations
    processCallback(context, method, operation);

    // Process @Server annotations
    processServerAnnotation(method, operation);

    // Process @Extension annotations
    processExtensions(context, method, operation);

    // Process Security Roles
    JavaSecurityProcessor.processSecurityRoles(method, operation);

    // Now set the operation on the PathItem as appropriate based on the Http method type
    setOperationOnPathItem(methodType, pathItem, operation);

    // Figure out the path for the operation.  This is a combination of the App, Resource, and Method @Path annotations
    String path = super.makePath(params.getOperationPath());

    // Get or create a PathItem to hold the operation
    PathItem existingPath = ModelUtil.paths(openApi).getPathItem(path);

    if (existingPath == null) {
        ModelUtil.paths(openApi).addPathItem(path, pathItem);
    } else {
        // Changes applied to 'existingPath', no need to re-assign or add to OAI.
        MergeUtil.mergeObjects(existingPath, pathItem);
    }
}
 
Example #28
Source File: PathItemImpl.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * @see org.eclipse.microprofile.openapi.models.PathItem#setPOST(org.eclipse.microprofile.openapi.models.Operation)
 */
@Override
public void setPOST(Operation post) {
    this.post = post;
}
 
Example #29
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * Process a single JAX-RS method to produce an OpenAPI Operation.
 * 
 * @param openApi
 * @param resourceClass
 * @param method
 * @param methodType
 * @param resourceTags
 * @param locatorPathParameters
 */
private void processResourceMethod(final AnnotationScannerContext context,
        final ClassInfo resourceClass,
        final MethodInfo method,
        final PathItem.HttpMethod methodType,
        OpenAPI openApi,
        Set<String> resourceTags,
        List<Parameter> locatorPathParameters,
        Map<DotName, AnnotationInstance> exceptionAnnotationMap) {

    JaxRsLogging.log.processingMethod(method.toString());

    // Figure out the current @Produces and @Consumes (if any)
    CurrentScannerInfo.setCurrentConsumes(getMediaTypes(method, JaxRsConstants.CONSUMES).orElse(null));
    CurrentScannerInfo.setCurrentProduces(getMediaTypes(method, JaxRsConstants.PRODUCES).orElse(null));

    // Process any @Operation annotation
    Optional<Operation> maybeOperation = processOperation(context, method);
    if (!maybeOperation.isPresent()) {
        return; // If the operation is marked as hidden, just bail here because we don't want it as part of the model.
    }
    final Operation operation = maybeOperation.get();

    // Process tags - @Tag and @Tags annotations combines with the resource tags we've already found (passed in)
    processOperationTags(method, openApi, resourceTags, operation);

    // Process @Parameter annotations.
    Function<AnnotationInstance, Parameter> reader = t -> ParameterReader.readParameter(context, t);

    ResourceParameters params = ParameterProcessor.process(context, resourceClass, method,
            reader, context.getExtensions());
    operation.setParameters(params.getOperationParameters());

    PathItem pathItem = new PathItemImpl();
    pathItem.setParameters(ListUtil.mergeNullableLists(locatorPathParameters, params.getPathItemParameters()));

    // Process any @RequestBody annotation (note: the @RequestBody annotation can be found on a method argument *or* on the method)
    RequestBody requestBody = processRequestBody(context, method, params);
    if (requestBody != null) {
        operation.setRequestBody(requestBody);
    }

    // Process @APIResponse annotations
    processResponse(context, method, operation, exceptionAnnotationMap);

    // Process @SecurityRequirement annotations
    processSecurityRequirementAnnotation(resourceClass, method, operation);

    // Process @Callback annotations
    processCallback(context, method, operation);

    // Process @Server annotations
    processServerAnnotation(method, operation);

    // Process @Extension annotations
    processExtensions(context, method, operation);

    // Process Security Roles
    JavaSecurityProcessor.processSecurityRoles(method, operation);

    // Now set the operation on the PathItem as appropriate based on the Http method type
    setOperationOnPathItem(methodType, pathItem, operation);

    // Figure out the path for the operation.  This is a combination of the App, Resource, and Method @Path annotations
    final String path;

    if (this.subResourceStack.isEmpty()) {
        path = super.makePath(params.getFullOperationPath());
    } else {
        // When processing a sub-resource tree, ignore any @Path information from the current class
        path = super.makePath(params.getOperationPath());
    }

    // Get or create a PathItem to hold the operation
    PathItem existingPath = ModelUtil.paths(openApi).getPathItem(path);

    if (existingPath == null) {
        ModelUtil.paths(openApi).addPathItem(path, pathItem);
    } else {
        // Changes applied to 'existingPath', no need to re-assign or add to OAI.
        MergeUtil.mergeObjects(existingPath, pathItem);
    }
}
 
Example #30
Source File: OperationImpl.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * @see org.eclipse.microprofile.openapi.models.Operation#addTag(java.lang.String)
 */
@Override
public Operation addTag(String tag) {
    this.tags = ModelUtil.add(tag, this.tags, ArrayList<String>::new);
    return this;
}