Search in sources :

Example 41 with Header

use of io.swagger.v3.oas.models.headers.Header in project openremote by openremote.

the class ManagerWebService method init.

@Override
public void init(Container container) throws Exception {
    super.init(container);
    String rootRedirectPath = getString(container.getConfig(), ROOT_REDIRECT_PATH, ROOT_REDIRECT_PATH_DEFAULT);
    // Modify swagger object mapper to match ours
    configureObjectMapper(Json.mapper());
    Json.mapper().addMixIn(ServerVariable.class, ServerVariableMixin.class);
    // Add swagger resource
    OpenAPI oas = new OpenAPI().servers(Collections.singletonList(new Server().url("/api/{realm}/").variables(new ServerVariables().addServerVariable("realm", new ServerVariable()._default("master"))))).schemaRequirement("openid", new SecurityScheme().type(SecurityScheme.Type.OAUTH2).flows(new OAuthFlows().authorizationCode(new OAuthFlow().authorizationUrl("/auth/realms/master/protocol/openid-connect/auth").refreshUrl("/auth/realms/master/protocol/openid-connect/token").tokenUrl("/auth/realms/master/protocol/openid-connect/token")))).security(Collections.singletonList(new SecurityRequirement().addList("openid")));
    Info info = new Info().title("OpenRemote Manager REST API").description("This is the documentation for the OpenRemote Manager HTTP REST API.  Please see the [wiki](https://github.com/openremote/openremote/wiki) for more info.").contact(new Contact().email("info@openremote.io")).license(new License().name("AGPL 3.0").url("https://www.gnu.org/licenses/agpl-3.0.en.html"));
    oas.info(info);
    SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourcePackages(Stream.of("org.openremote.model.*").collect(Collectors.toSet())).openAPI(oas);
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.openApiConfiguration(oasConfig);
    addApiSingleton(openApiResource);
    initialised = true;
    ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), apiSingletons, true);
    // Serve REST API
    HttpHandler apiHandler = createApiHandler(container, resteasyDeployment);
    if (apiHandler != null) {
        // Authenticating requests requires a realm, either we receive this in a header or
        // we extract it (e.g. from request path segment) and set it as a header before
        // processing the request
        HttpHandler baseApiHandler = apiHandler;
        apiHandler = exchange -> {
            String path = exchange.getRelativePath().substring(API_PATH.length());
            Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(path);
            if (!realmSubMatcher.matches()) {
                exchange.setStatusCode(NOT_FOUND.getStatusCode());
                throw new WebApplicationException(NOT_FOUND);
            }
            // Extract realm from path and push it into REQUEST_HEADER_REALM header
            String realm = realmSubMatcher.group(1);
            // Move the realm from path segment to header
            exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
            URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
            exchange.setRequestURI(url.toString(), true);
            exchange.setRequestPath(url.getPath());
            exchange.setRelativePath(url.getPath());
            baseApiHandler.handleRequest(exchange);
        };
    }
    // Serve deployment files unsecured (explicitly map deployment folders to request paths)
    builtInAppDocRoot = Paths.get(getString(container.getConfig(), APP_DOCROOT, APP_DOCROOT_DEFAULT));
    customAppDocRoot = Paths.get(getString(container.getConfig(), CUSTOM_APP_DOCROOT, CUSTOM_APP_DOCROOT_DEFAULT));
    HttpHandler defaultHandler = null;
    if (Files.isDirectory(customAppDocRoot)) {
        HttpHandler customBaseFileHandler = createFileHandler(container, customAppDocRoot, null);
        defaultHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            customBaseFileHandler.handleRequest(exchange);
        };
    }
    PathHandler deploymentHandler = defaultHandler != null ? new PathHandler(defaultHandler) : new PathHandler();
    // Serve deployment files
    if (Files.isDirectory(builtInAppDocRoot)) {
        HttpHandler appBaseFileHandler = createFileHandler(container, builtInAppDocRoot, null);
        HttpHandler appFileHandler = exchange -> {
            if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
                exchange.setRelativePath("/index.html");
            }
            // Reinstate the full path
            exchange.setRelativePath(exchange.getRequestPath());
            appBaseFileHandler.handleRequest(exchange);
        };
        deploymentHandler.addPrefixPath(MANAGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SWAGGER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(CONSOLE_LOADER_APP_PATH, appFileHandler);
        deploymentHandler.addPrefixPath(SHARED_PATH, appFileHandler);
    }
    // Redirect / to default app
    if (rootRedirectPath != null) {
        getRequestHandlers().add(new RequestHandler("Default app redirect", exchange -> exchange.getRequestPath().equals("/"), exchange -> {
            LOG.finer("Handling root request, redirecting client to default app");
            new RedirectHandler(redirect(exchange, rootRedirectPath)).handleRequest(exchange);
        }));
    }
    if (apiHandler != null) {
        getRequestHandlers().add(pathStartsWithHandler("REST API Handler", API_PATH, apiHandler));
    }
    // This will try and handle any request that makes it to this handler
    getRequestHandlers().add(new RequestHandler("Deployment files", exchange -> true, deploymentHandler));
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Json(io.swagger.v3.core.util.Json) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) WebService(org.openremote.container.web.WebService) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) ValueUtil.configureObjectMapper(org.openremote.model.util.ValueUtil.configureObjectMapper) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ServletInfo(io.undertow.servlet.api.ServletInfo) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) RedirectHandler(io.undertow.server.handlers.RedirectHandler) Servlets(io.undertow.servlet.Servlets) HashSet(java.util.HashSet) License(io.swagger.v3.oas.models.info.License) PathHandler(io.undertow.server.handlers.PathHandler) Matcher(java.util.regex.Matcher) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI) io.swagger.v3.oas.models.security(io.swagger.v3.oas.models.security) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) URI(java.net.URI) Path(java.nio.file.Path) REALM_PARAM_NAME(org.openremote.model.Constants.REALM_PARAM_NAME) Files(java.nio.file.Files) Collection(java.util.Collection) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) Info(io.swagger.v3.oas.models.info.Info) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) HttpHandler(io.undertow.server.HttpHandler) Container(org.openremote.model.Container) IdentityService(org.openremote.container.security.IdentityService) Server(io.swagger.v3.oas.models.servers.Server) Stream(java.util.stream.Stream) Contact(io.swagger.v3.oas.models.info.Contact) Paths(java.nio.file.Paths) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) WebApplicationException(javax.ws.rs.WebApplicationException) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) RedirectBuilder.redirect(io.undertow.util.RedirectBuilder.redirect) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) HttpHandler(io.undertow.server.HttpHandler) Server(io.swagger.v3.oas.models.servers.Server) WebApplicationException(javax.ws.rs.WebApplicationException) Matcher(java.util.regex.Matcher) RedirectHandler(io.undertow.server.handlers.RedirectHandler) License(io.swagger.v3.oas.models.info.License) CanonicalPathHandler(io.undertow.server.handlers.CanonicalPathHandler) PathHandler(io.undertow.server.handlers.PathHandler) MapAccess.getString(org.openremote.container.util.MapAccess.getString) HttpString(io.undertow.util.HttpString) ServletInfo(io.undertow.servlet.api.ServletInfo) Info(io.swagger.v3.oas.models.info.Info) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) URI(java.net.URI) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) Contact(io.swagger.v3.oas.models.info.Contact) OpenApiResource(io.swagger.v3.jaxrs2.integration.resources.OpenApiResource) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 42 with Header

use of io.swagger.v3.oas.models.headers.Header in project swagger-parser by swagger-api.

the class SwaggerConverter method convert.

public Parameter convert(io.swagger.models.parameters.Parameter v2Parameter) {
    Parameter v3Parameter = new Parameter();
    if (StringUtils.isNotBlank(v2Parameter.getDescription())) {
        v3Parameter.setDescription(v2Parameter.getDescription());
    }
    if (v2Parameter instanceof SerializableParameter) {
        v3Parameter.setAllowEmptyValue(((SerializableParameter) v2Parameter).getAllowEmptyValue());
    }
    v3Parameter.setIn(v2Parameter.getIn());
    v3Parameter.setName(v2Parameter.getName());
    Object exampleExtension = v2Parameter.getVendorExtensions().get("x-example");
    if (exampleExtension != null) {
        v3Parameter.setExample(exampleExtension);
    }
    Schema schema = null;
    if (v2Parameter instanceof RefParameter) {
        RefParameter ref = (RefParameter) v2Parameter;
        if (ref.get$ref().indexOf("#/parameters") == 0) {
            String updatedRef = "#/components/";
            if (components.getRequestBodies() != null && components.getRequestBodies().get(ref.getSimpleRef()) != null) {
                updatedRef += "requestBodies";
            } else if (components.getSchemas() != null && components.getSchemas().get("formData_" + ref.getSimpleRef()) != null) {
                updatedRef += "schemas";
            } else {
                updatedRef += "parameters";
            }
            updatedRef += ref.get$ref().substring("#/parameters".length());
            ref.set$ref(updatedRef);
        }
        v3Parameter.set$ref(ref.get$ref());
    } else if (v2Parameter instanceof SerializableParameter) {
        SerializableParameter sp = (SerializableParameter) v2Parameter;
        if ("array".equals(sp.getType())) {
            ArraySchema a = new ArraySchema();
            // TODO: convert arrays to proper template format
            String cf = sp.getCollectionFormat();
            if (StringUtils.isEmpty(cf)) {
                cf = "csv";
            }
            switch(cf) {
                case "ssv":
                    if ("query".equals(v2Parameter.getIn())) {
                        v3Parameter.setStyle(Parameter.StyleEnum.SPACEDELIMITED);
                    }
                    break;
                case "pipes":
                    if ("query".equals(v2Parameter.getIn())) {
                        v3Parameter.setStyle((Parameter.StyleEnum.PIPEDELIMITED));
                    }
                    break;
                case "tsv":
                    break;
                case "multi":
                    if ("query".equals(v2Parameter.getIn())) {
                        v3Parameter.setStyle(Parameter.StyleEnum.FORM);
                        v3Parameter.setExplode(true);
                    }
                    break;
                case "csv":
                default:
                    if ("query".equals(v2Parameter.getIn())) {
                        v3Parameter.setStyle(Parameter.StyleEnum.FORM);
                        v3Parameter.setExplode(false);
                    } else if ("header".equals(v2Parameter.getIn()) || "path".equals(v2Parameter.getIn())) {
                        v3Parameter.setStyle(Parameter.StyleEnum.SIMPLE);
                        v3Parameter.setExplode(false);
                    }
            }
            Property items = sp.getItems();
            Schema itemsSchema = convert(items);
            a.setItems(itemsSchema);
            if (sp.getMaxItems() != null) {
                a.setMaxItems(sp.getMaxItems());
            }
            if (sp.getMinItems() != null) {
                a.setMinItems(sp.getMinItems());
            }
            if (sp.isUniqueItems() != null) {
                a.setUniqueItems(sp.isUniqueItems());
            }
            schema = a;
        } else {
            schema = SchemaTypeUtil.createSchema(sp.getType(), sp.getFormat());
            schema.setType(sp.getType());
            schema.setFormat(sp.getFormat());
            schema.setMaximum(sp.getMaximum());
            schema.setExclusiveMaximum(sp.isExclusiveMaximum());
            schema.setMinimum(sp.getMinimum());
            schema.setExclusiveMinimum(sp.isExclusiveMinimum());
            schema.setMinLength(sp.getMinLength());
            schema.setMaxLength(sp.getMaxLength());
            if (sp.getMultipleOf() != null) {
                schema.setMultipleOf(new BigDecimal(sp.getMultipleOf().toString()));
            }
            schema.setPattern(sp.getPattern());
        }
        if (sp.getEnum() != null) {
            for (String e : sp.getEnum()) {
                switch(sp.getType() == null ? SchemaTypeUtil.OBJECT_TYPE : sp.getType()) {
                    case SchemaTypeUtil.INTEGER_TYPE:
                        schema.addEnumItemObject(Integer.parseInt(e));
                        break;
                    case SchemaTypeUtil.NUMBER_TYPE:
                        schema.addEnumItemObject(new BigDecimal(e));
                        break;
                    case SchemaTypeUtil.BOOLEAN_TYPE:
                        schema.addEnumItemObject(Boolean.valueOf(e));
                        break;
                    default:
                        schema.addEnumItemObject(e);
                        break;
                }
            }
        }
        if (sp.getVendorExtensions() != null) {
            Object nullableExtension = sp.getVendorExtensions().get("x-nullable");
            if (nullableExtension != null) {
                schema.setNullable((Boolean) nullableExtension);
            }
        }
        schema.setExtensions(convert(sp.getVendorExtensions()));
        if (sp instanceof AbstractSerializableParameter) {
            AbstractSerializableParameter ap = (AbstractSerializableParameter) sp;
            schema.setDefault(ap.getDefault());
        }
    }
    if (v2Parameter.getRequired()) {
        v3Parameter.setRequired(v2Parameter.getRequired());
    }
    v3Parameter.setSchema(schema);
    v3Parameter.setExtensions(convert(v2Parameter.getVendorExtensions()));
    return v3Parameter;
}
Also used : SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) RefParameter(io.swagger.models.parameters.RefParameter) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) FileSchema(io.swagger.v3.oas.models.media.FileSchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) RefParameter(io.swagger.models.parameters.RefParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) BigDecimal(java.math.BigDecimal)

Example 43 with Header

use of io.swagger.v3.oas.models.headers.Header in project swagger-parser by swagger-api.

the class V2ConverterTest method testIssue785.

@Test(description = "OpenAPIParser.readLocation fails when fetching valid Swagger 2.0 resource with AuthorizationValues provided")
public void testIssue785() {
    AuthorizationValue apiKey = new AuthorizationValue("api_key", "special-key", "header");
    List<AuthorizationValue> authorizationValues = Arrays.asList(apiKey);
    SwaggerConverter converter = new SwaggerConverter();
    List<io.swagger.models.auth.AuthorizationValue> convertedAuthList = converter.convert(authorizationValues);
    assertEquals(convertedAuthList.size(), authorizationValues.size());
}
Also used : AuthorizationValue(io.swagger.v3.parser.core.models.AuthorizationValue) SwaggerConverter(io.swagger.v3.parser.converter.SwaggerConverter) Test(org.testng.annotations.Test)

Example 44 with Header

use of io.swagger.v3.oas.models.headers.Header in project swagger-parser by swagger-api.

the class ResolverFully method resolveHeaders.

private void resolveHeaders(Map<String, Header> headers) {
    if (headers == null || headers.isEmpty()) {
        return;
    }
    for (Map.Entry<String, Header> header : headers.entrySet()) {
        Header value = header.getValue();
        Header resolvedValue = value.get$ref() != null ? resolveHeader(value) : value;
        Map<String, Example> examples = resolvedValue.getExamples();
        if (examples != null) {
            Map<String, Example> resolved = resolveExample(examples);
            resolvedValue.setExamples(resolved);
        }
        Schema schema = resolvedValue.getSchema();
        if (schema != null) {
            Schema resolvedSchema = resolveSchema(schema);
            if (resolvedSchema != null) {
                resolvedValue.setSchema(resolvedSchema);
            }
        }
        header.setValue(resolvedValue);
    }
}
Also used : Header(io.swagger.v3.oas.models.headers.Header) Example(io.swagger.v3.oas.models.examples.Example) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap)

Example 45 with Header

use of io.swagger.v3.oas.models.headers.Header in project swagger-parser by swagger-api.

the class ResponseProcessorTest method testProcessResponse.

@Test
public void testProcessResponse(@Injectable final Schema responseSchema, @Injectable final Header responseHeader) throws Exception {
    new StrictExpectations() {

        {
            new SchemaProcessor(cache, swagger);
            times = 1;
            result = propertyProcessor;
            new HeaderProcessor(cache, swagger);
            times = 1;
            result = headerProcessor;
            new LinkProcessor(cache, swagger);
            times = 1;
            result = linkProcessor;
            propertyProcessor.processSchema(responseSchema);
            times = 1;
            headerProcessor.processHeader(responseHeader);
            times = 1;
        }
    };
    ApiResponse response = new ApiResponse();
    response.content(new Content().addMediaType("*/*", new MediaType().schema(responseSchema)));
    response.addHeaderObject("foo", responseHeader);
    new ResponseProcessor(cache, swagger).processResponse(response);
    new FullVerifications() {

        {
        }
    };
}
Also used : StrictExpectations(mockit.StrictExpectations) Content(io.swagger.v3.oas.models.media.Content) MediaType(io.swagger.v3.oas.models.media.MediaType) FullVerifications(mockit.FullVerifications) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)32 OpenAPI (io.swagger.v3.oas.models.OpenAPI)26 Header (io.swagger.v3.oas.models.headers.Header)25 Parameter (io.swagger.v3.oas.models.parameters.Parameter)16 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)13 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)11 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)11 Schema (io.swagger.v3.oas.models.media.Schema)10 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)10 MediaType (io.swagger.v3.oas.models.media.MediaType)8 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)8 Components (io.swagger.v3.oas.models.Components)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 StringSchema (io.swagger.v3.oas.models.media.StringSchema)6 AuthorizationValue (io.swagger.v3.parser.core.models.AuthorizationValue)6 PathItem (io.swagger.v3.oas.models.PathItem)5 Example (io.swagger.v3.oas.models.examples.Example)5 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)5 PathParameter (io.swagger.v3.oas.models.parameters.PathParameter)5 RefFormat (io.swagger.v3.parser.models.RefFormat)5