Search in sources :

Example 11 with Parameter

use of io.swagger.v3.oas.annotations.Parameter in project syncope by apache.

the class SyncopeOpenApiCustomizer method addParameters.

@Override
protected void addParameters(final List<Parameter> parameters) {
    if (domains == null) {
        domains = new ArrayList<>(ApplicationContextProvider.getApplicationContext().getBean(DomainsHolder.class).getDomains().keySet());
    }
    Optional<Parameter> domainHeaderParameter = parameters.stream().filter(parameter -> parameter instanceof HeaderParameter && RESTHeaders.DOMAIN.equals(parameter.getName())).findFirst();
    if (!domainHeaderParameter.isPresent()) {
        HeaderParameter parameter = new HeaderParameter();
        parameter.setName(RESTHeaders.DOMAIN);
        parameter.setRequired(true);
        Schema<String> schema = new Schema<>();
        schema.setType("string");
        schema.setEnum(domains);
        schema.setDefault(SyncopeConstants.MASTER_DOMAIN);
        parameter.setSchema(schema);
        parameters.add(parameter);
    }
}
Also used : ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) Content(io.swagger.v3.oas.models.media.Content) URL(java.net.URL) MediaType(io.swagger.v3.oas.models.media.MediaType) Parameter(io.swagger.v3.oas.models.parameters.Parameter) OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) Header(io.swagger.v3.oas.models.headers.Header) ErrorTO(org.apache.syncope.common.lib.to.ErrorTO) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) DomainsHolder(org.apache.syncope.core.persistence.api.DomainsHolder) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) Map(java.util.Map) OpenApiCustomizer(org.apache.cxf.jaxrs.openapi.OpenApiCustomizer) Optional(java.util.Optional) Schema(io.swagger.v3.oas.models.media.Schema) RESTHeaders(org.apache.syncope.common.rest.api.RESTHeaders) ApplicationContextProvider(org.apache.syncope.core.spring.ApplicationContextProvider) Schema(io.swagger.v3.oas.models.media.Schema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter)

Example 12 with Parameter

use of io.swagger.v3.oas.annotations.Parameter in project cxf by apache.

the class OpenApiCustomizer method customize.

public void customize(final OpenAPI oas) {
    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        cris.forEach(cri -> {
            cri.getMethodDispatcher().getOperationResourceInfos().forEach(ori -> {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue());
                operations.put(normalizedPath, cri);
                methods.put(Pair.of(ori.getHttpMethod(), normalizedPath), ori);
            });
        });
        List<Tag> tags = new ArrayList<>();
        oas.getPaths().forEach((pathKey, pathItem) -> {
            Tag tag = null;
            if (replaceTags && operations.containsKey(pathKey)) {
                ClassResourceInfo cri = operations.get(pathKey);
                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_"));
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }
                if (!tags.contains(tag)) {
                    tags.add(tag);
                }
            }
            for (Map.Entry<HttpMethod, Operation> subentry : pathItem.readOperationsMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }
                Pair<String, String> key = Pair.of(subentry.getKey().name(), pathKey);
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);
                    if (StringUtils.isBlank(subentry.getValue().getSummary())) {
                        subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));
                    }
                    if (subentry.getValue().getParameters() == null) {
                        List<Parameter> parameters = new ArrayList<>();
                        addParameters(parameters);
                        subentry.getValue().setParameters(parameters);
                    } else {
                        for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                            if (StringUtils.isBlank(subentry.getValue().getParameters().get(i).getDescription())) {
                                subentry.getValue().getParameters().get(i).setDescription(javadocProvider.getMethodParameterDoc(ori, i));
                            }
                        }
                        addParameters(subentry.getValue().getParameters());
                    }
                    if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) {
                        ApiResponse response = subentry.getValue().getResponses().entrySet().iterator().next().getValue();
                        if (StringUtils.isBlank(response.getDescription())) {
                            response.setDescription(javadocProvider.getMethodResponseDoc(ori));
                        }
                    }
                }
            }
        });
        if (replaceTags && oas.getTags() != null) {
            oas.setTags(tags);
        }
    }
}
Also used : HashMap(java.util.HashMap) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Parameter(io.swagger.v3.oas.models.parameters.Parameter) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Tag(io.swagger.v3.oas.models.tags.Tag) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.swagger.v3.oas.models.PathItem.HttpMethod) Pair(org.apache.commons.lang3.tuple.Pair)

Example 13 with Parameter

use of io.swagger.v3.oas.annotations.Parameter in project vertx-web by vert-x3.

the class OpenAPI3PathResolver method solve.

public Pattern solve() {
    // Filter parameters to get only path parameters
    parameters = parameters.stream().filter(parameter -> parameter.getIn().equals("path")).collect(Collectors.toList());
    if (ILLEGAL_PATH_MATCHER.matcher(oasPath).matches())
        throw new RouterFactoryException("Path template not supported", RouterFactoryException.ErrorType.INVALID_SPEC_PATH);
    Matcher parametersMatcher = OAS_PATH_PARAMETERS_PATTERN.matcher(oasPath);
    if (!parameters.isEmpty() && parametersMatcher.find()) {
        // Need to create a specific match pattern with path parameters and some string manipulation magic
        StringBuilder regex = new StringBuilder();
        int lastMatchEnd = 0;
        boolean endSlash = oasPath.charAt(oasPath.length() - 1) == '/';
        parametersMatcher.reset();
        int i = 0;
        while (parametersMatcher.find()) {
            // Append constant string
            regex.append(Pattern.quote(oasPath.substring(lastMatchEnd, parametersMatcher.start())));
            lastMatchEnd = parametersMatcher.end();
            String paramName = parametersMatcher.group(1);
            Optional<Parameter> parameterOptional = parameters.stream().filter(p -> p.getName().equals(paramName)).findFirst();
            if (parameterOptional.isPresent()) {
                // For every parameter style I have to generate a different regular expression
                Parameter parameter = parameterOptional.get();
                String style = (parameter.getStyle() != null) ? parameter.getStyle().toString() : "simple";
                boolean explode = (parameter.getExplode() != null) ? parameter.getExplode() : false;
                boolean isObject = OpenApi3Utils.isParameterObjectOrAllOfType(parameter);
                boolean isArray = OpenApi3Utils.isParameterArrayType(parameter);
                String groupName = "p" + i;
                if (style.equals("simple")) {
                    regex.append("(?<" + groupName + ">[^\\/\\;\\?\\:\\@\\&\\.\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)?");
                    mappedGroups.put(groupName, paramName);
                } else if (style.equals("label")) {
                    if (isObject && explode) {
                        Map<String, OpenApi3Utils.ObjectField> properties = OpenApi3Utils.solveObjectParameters(parameter.getSchema());
                        for (Map.Entry<String, OpenApi3Utils.ObjectField> entry : properties.entrySet()) {
                            groupName = "p" + i;
                            regex.append("\\.?" + entry.getKey() + "=(?<" + groupName + ">[^\\/\\;\\?\\:\\@\\=\\.\\&\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)");
                            mappedGroups.put(groupName, entry.getKey());
                            i++;
                        }
                    } else {
                        regex.append("\\.?(?<" + groupName + ">[^\\/\\;\\?\\:\\@\\=\\&\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)?");
                        mappedGroups.put(groupName, paramName);
                    }
                } else if (style.equals("matrix")) {
                    if (isObject && explode) {
                        Map<String, OpenApi3Utils.ObjectField> properties = OpenApi3Utils.solveObjectParameters(parameter.getSchema());
                        for (Map.Entry<String, OpenApi3Utils.ObjectField> entry : properties.entrySet()) {
                            groupName = "p" + i;
                            regex.append("\\;" + entry.getKey() + "=(?<" + groupName + ">[^\\/\\;\\?\\:\\@\\=\\.\\&\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)");
                            mappedGroups.put(groupName, entry.getKey());
                            i++;
                        }
                    } else if (isArray && explode) {
                        regex.append("(?<" + groupName + ">(?>;" + paramName + "=[^\\/\\;\\?\\:\\@\\&\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)+)");
                        mappedGroups.put(groupName, paramName);
                    } else {
                        regex.append(";" + paramName + "=(?<" + groupName + ">[^\\/\\;\\?\\:\\@\\=\\&\\\"\\<\\>\\#\\{\\}\\|\\\\\\^\\~\\[\\]\\`]*)?");
                        mappedGroups.put(groupName, paramName);
                    }
                }
            } else {
                throw RouterFactoryException.createSpecInvalidException("Missing parameter description for parameter name: " + paramName);
            }
            i++;
        }
        regex.append(Pattern.quote(oasPath.substring(lastMatchEnd, (endSlash) ? oasPath.length() - 1 : oasPath.length())));
        if (endSlash)
            regex.append(QUERY_REGEX_WITH_SLASH);
        else
            regex.append(QUERY_REGEX_WITHOUT_SLASH);
        resolvedPattern = Pattern.compile(regex.toString());
    } else {
        resolvedPattern = Pattern.compile(Pattern.quote(oasPath));
    }
    return resolvedPattern;
}
Also used : List(java.util.List) Matcher(java.util.regex.Matcher) Map(java.util.Map) Parameter(io.swagger.v3.oas.models.parameters.Parameter) RouterFactoryException(io.vertx.ext.web.api.contract.RouterFactoryException) Optional(java.util.Optional) HashMap(java.util.HashMap) Pattern(java.util.regex.Pattern) Collectors(java.util.stream.Collectors) Matcher(java.util.regex.Matcher) RouterFactoryException(io.vertx.ext.web.api.contract.RouterFactoryException) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Map(java.util.Map) HashMap(java.util.HashMap)

Example 14 with Parameter

use of io.swagger.v3.oas.annotations.Parameter in project vertx-web by vert-x3.

the class OpenApi3Utils method mergeParameters.

public static List<Parameter> mergeParameters(List<Parameter> operationParameters, List<Parameter> parentParameters) {
    if (parentParameters == null && operationParameters == null) {
        return new ArrayList<>();
    } else if (operationParameters == null) {
        return new ArrayList<>(parentParameters);
    } else if (parentParameters == null) {
        return new ArrayList<>(operationParameters);
    } else {
        List<Parameter> result = new ArrayList<>(operationParameters);
        List<Parameter> actualParams = new ArrayList<>(operationParameters);
        for (int i = 0; i < parentParameters.size(); i++) {
            for (int j = 0; j < actualParams.size(); j++) {
                Parameter parentParam = parentParameters.get(i);
                Parameter actualParam = actualParams.get(j);
                if (!(parentParam.getIn().equalsIgnoreCase(actualParam.getIn()) && parentParam.getName().equals(actualParam.getName())))
                    result.add(parentParam);
            }
        }
        return result;
    }
}
Also used : Parameter(io.swagger.v3.oas.models.parameters.Parameter)

Example 15 with Parameter

use of io.swagger.v3.oas.annotations.Parameter in project vertx-web by vert-x3.

the class OpenAPI3ValidationTest method testQueryParameterArrayDefaultStyle.

@Test
public void testQueryParameterArrayDefaultStyle() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/arrayTests/default").getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec);
    loadHandlers("/queryTests/arrayTests/default", HttpMethod.GET, false, validationHandler, (routingContext) -> {
        RequestParameters params = routingContext.get("parsedParameters");
        List<String> result = new ArrayList<>();
        for (RequestParameter r : params.queryParameter("parameter").getArray()) result.add(r.getInteger().toString());
        routingContext.response().setStatusMessage(serializeInCSVStringArray(result)).end();
    });
    List<String> values = new ArrayList<>();
    values.add("4");
    values.add("2");
    values.add("26");
    testRequest(HttpMethod.GET, "/queryTests/arrayTests/default?parameter=" + serializeInCSVStringArray(values), 200, serializeInCSVStringArray(values));
}
Also used : OpenAPI3RequestValidationHandlerImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl) RequestParameter(io.vertx.ext.web.api.RequestParameter) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Aggregations

Operation (io.swagger.v3.oas.models.Operation)15 OpenAPI3RequestValidationHandlerImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl)14 Test (org.junit.Test)14 RequestParameters (io.vertx.ext.web.api.RequestParameters)11 Parameter (io.swagger.v3.oas.models.parameters.Parameter)5 RequestParameter (io.vertx.ext.web.api.RequestParameter)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)4 HashMap (java.util.HashMap)3 List (java.util.List)3 Schema (io.swagger.v3.oas.models.media.Schema)2 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 JsonView (com.fasterxml.jackson.annotation.JsonView)1 ModelConverters (io.swagger.v3.core.converter.ModelConverters)1 ResolvedSchema (io.swagger.v3.core.converter.ResolvedSchema)1 ResolvedParameter (io.swagger.v3.jaxrs2.ResolvedParameter)1 AbstractOpenAPIExtension (io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension)1 OpenAPIExtension (io.swagger.v3.jaxrs2.ext.OpenAPIExtension)1