Search in sources :

Example 6 with SwaggerApiEntity

use of io.gravitee.rest.api.model.api.SwaggerApiEntity in project gravitee-management-rest-api by gravitee-io.

the class SwaggerService_CreateAPITest method shouldPrepareAPIFromSwaggerV3WithMultiServer.

@Test
public void shouldPrepareAPIFromSwaggerV3WithMultiServer() throws IOException {
    final SwaggerApiEntity api = prepareInline("io/gravitee/rest/api/management/service/mock/openapi-multiserver.yaml", true);
    assertEquals("/v1", api.getProxy().getVirtualHosts().get(0).getPath());
    final List<String> endpoints = api.getProxy().getGroups().iterator().next().getEndpoints().stream().map(Endpoint::getTarget).collect(Collectors.toList());
    assertEquals(3, endpoints.size());
    assertTrue(endpoints.contains("https://development.gigantic-server.com/v1"));
    assertTrue(endpoints.contains("https://staging.gigantic-server.com/v1"));
    assertTrue(endpoints.contains("https://api.gigantic-server.com/v1"));
}
Also used : SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 7 with SwaggerApiEntity

use of io.gravitee.rest.api.model.api.SwaggerApiEntity in project gravitee-management-rest-api by gravitee-io.

the class SwaggerService_CreateAPITest method shouldPrepareAPIFromSwaggerV3WithMonoServer.

@Test
public void shouldPrepareAPIFromSwaggerV3WithMonoServer() throws IOException {
    final SwaggerApiEntity api = prepareInline("io/gravitee/rest/api/management/service/mock/openapi-monoserver.yaml", true);
    assertEquals("/v1", api.getProxy().getVirtualHosts().get(0).getPath());
    final List<String> endpoints = api.getProxy().getGroups().iterator().next().getEndpoints().stream().map(Endpoint::getTarget).collect(Collectors.toList());
    assertEquals(1, 2, endpoints.size());
    assertTrue(endpoints.contains("https://development.gigantic-server.com/v1"));
}
Also used : SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 8 with SwaggerApiEntity

use of io.gravitee.rest.api.model.api.SwaggerApiEntity in project gravitee-management-rest-api by gravitee-io.

the class OAIToAPIConverter method visit.

@Override
public SwaggerApiEntity visit(OpenAPI oai) {
    final SwaggerApiEntity apiEntity = new SwaggerApiEntity();
    // Name
    apiEntity.setName(oai.getInfo().getTitle());
    // Description
    apiEntity.setDescription(oai.getInfo().getDescription() == null ? "Description of " + apiEntity.getName() : oai.getInfo().getDescription());
    // Version
    apiEntity.setVersion(oai.getInfo().getVersion());
    fill(apiEntity, oai);
    // Use X-Gravitee to add information in API
    XGraviteeIODefinition xGraviteeIODefinition = null;
    if (oai.getExtensions() != null && oai.getExtensions().get(X_GRAVITEEIO_DEFINITION_VENDOR_EXTENSION) != null) {
        xGraviteeIODefinition = new ObjectMapper().convertValue(oai.getExtensions().get(X_GRAVITEEIO_DEFINITION_VENDOR_EXTENSION), XGraviteeIODefinition.class);
    }
    // Proxy
    Proxy proxy = new Proxy();
    String defaultEndpoint = null;
    // Proxy - Endpoints
    if (!oai.getServers().isEmpty()) {
        List<String> evaluatedServerUrl = mapServersToEndpoint(oai.getServers());
        EndpointGroup defaultGroup = new EndpointGroup();
        defaultGroup.setName("default-group");
        if (evaluatedServerUrl == null) {
            defaultGroup.setEndpoints(singleton(new HttpEndpoint("default", defaultEndpoint)));
        } else if (evaluatedServerUrl.size() == 1) {
            defaultEndpoint = evaluatedServerUrl.get(0);
            defaultGroup.setEndpoints(singleton(new HttpEndpoint("default", defaultEndpoint)));
        } else {
            defaultEndpoint = evaluatedServerUrl.get(0);
            defaultGroup.setEndpoints(new HashSet<>());
            for (int i = 0; i < evaluatedServerUrl.size(); i++) {
                defaultGroup.getEndpoints().add(new HttpEndpoint("server" + (i + 1), evaluatedServerUrl.get(i)));
            }
        }
        proxy.setGroups(singleton(defaultGroup));
        apiEntity.setProxy(proxy);
    }
    // Proxy - Context Path / Virtual Host
    if (xGraviteeIODefinition != null && xGraviteeIODefinition.getVirtualHosts() != null) {
        proxy.setVirtualHosts(xGraviteeIODefinition.getVirtualHosts().stream().map(vHost -> new VirtualHost(vHost.getHost(), vHost.getPath(), (vHost.getOverrideEntrypoint() != null ? vHost.getOverrideEntrypoint() : false))).collect(Collectors.toList()));
    } else {
        String contextPath = null;
        if (defaultEndpoint != null) {
            contextPath = URI.create(defaultEndpoint).getPath();
        }
        if (contextPath == null || contextPath.equals("/")) {
            contextPath = apiEntity.getName().replaceAll("\\s+", "").toLowerCase();
        }
        proxy.setVirtualHosts(singletonList(new VirtualHost(contextPath)));
    }
    apiEntity.setProxy(proxy);
    // Add xGraviteeIODefinition config
    if (xGraviteeIODefinition != null) {
        // Categories
        if (xGraviteeIODefinition.getCategories() != null && !xGraviteeIODefinition.getCategories().isEmpty()) {
            apiEntity.setCategories(new HashSet<>(xGraviteeIODefinition.getCategories()));
        }
        // Groups
        if (xGraviteeIODefinition.getGroups() != null && !xGraviteeIODefinition.getGroups().isEmpty()) {
            // Groups in schema are group name. Replace them by id
            Set<String> groupIdsToImport = xGraviteeIODefinition.getGroups().stream().flatMap(group -> groupService.findByName(group).stream()).map(GroupEntity::getId).collect(Collectors.toSet());
            apiEntity.setGroups(groupIdsToImport);
        }
        // Labels
        if (xGraviteeIODefinition.getLabels() != null && !xGraviteeIODefinition.getLabels().isEmpty()) {
            apiEntity.setLabels(xGraviteeIODefinition.getLabels());
        }
        // Metadata
        if (xGraviteeIODefinition.getMetadata() != null && !xGraviteeIODefinition.getMetadata().isEmpty()) {
            final List<ApiMetadataEntity> apiMetadataEntities = xGraviteeIODefinition.getMetadata().stream().map(metadata -> {
                ApiMetadataEntity apiMetadata = new ApiMetadataEntity();
                apiMetadata.setKey(IdGenerator.generate(metadata.getName()));
                apiMetadata.setName(metadata.getName());
                apiMetadata.setValue(metadata.getValue());
                apiMetadata.setFormat(metadata.getFormat() != null ? MetadataFormat.valueOf(metadata.getFormat().name()) : MetadataFormat.STRING);
                return apiMetadata;
            }).collect(Collectors.toList());
            apiEntity.setMetadata(apiMetadataEntities);
        }
        // Picture
        if (xGraviteeIODefinition.getPicture() != null && !StringUtils.isEmpty(xGraviteeIODefinition.getPicture())) {
            if (xGraviteeIODefinition.getPicture().matches(PICTURE_REGEX)) {
                apiEntity.setPicture(xGraviteeIODefinition.getPicture());
            }
        }
        // Properties
        if (xGraviteeIODefinition.getProperties() != null && !xGraviteeIODefinition.getProperties().isEmpty()) {
            Properties properties = new Properties();
            properties.setProperties(xGraviteeIODefinition.getProperties().stream().map(prop -> new Property(prop.getKey(), prop.getValue())).collect(Collectors.toList()));
            apiEntity.setProperties(properties);
        }
        // Tags
        if (xGraviteeIODefinition.getTags() != null && !xGraviteeIODefinition.getTags().isEmpty()) {
            final Map<String, String> tagMap = tagService.findByReference(GraviteeContext.getCurrentOrganization(), TagReferenceType.ORGANIZATION).stream().collect(toMap(TagEntity::getId, TagEntity::getName));
            final Set<String> tagIdToAdd = xGraviteeIODefinition.getTags().stream().map(tag -> findTagIdByName(tagMap, tag)).filter(Objects::nonNull).collect(Collectors.toSet());
            if (tagIdToAdd != null && !tagIdToAdd.isEmpty()) {
                apiEntity.setTags(tagIdToAdd);
            }
        }
        // Visibility
        if (xGraviteeIODefinition.getVisibility() != null) {
            apiEntity.setVisibility(Visibility.valueOf(xGraviteeIODefinition.getVisibility().name()));
        }
    }
    return apiEntity;
}
Also used : java.util(java.util) Properties(io.gravitee.definition.model.Properties) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Operation(io.swagger.v3.oas.models.Operation) PolicyOperationVisitorManager(io.gravitee.rest.api.service.impl.swagger.policy.PolicyOperationVisitorManager) StringUtils(org.apache.commons.lang3.StringUtils) Collections.singletonList(java.util.Collections.singletonList) OAIOperationVisitor(io.gravitee.rest.api.service.impl.swagger.visitor.v3.OAIOperationVisitor) PolicyHelper.clearNullValues(io.gravitee.rest.api.service.validator.PolicyHelper.clearNullValues) IdGenerator(io.gravitee.common.utils.IdGenerator) Matcher(java.util.regex.Matcher) Collections.singleton(java.util.Collections.singleton) Collectors.toMap(java.util.stream.Collectors.toMap) OpenAPI(io.swagger.v3.oas.models.OpenAPI) io.gravitee.rest.api.model(io.gravitee.rest.api.model) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) URI(java.net.URI) GroupService(io.gravitee.rest.api.service.GroupService) XGraviteeIODefinition(io.gravitee.rest.api.service.swagger.converter.extension.XGraviteeIODefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PathItem(io.swagger.v3.oas.models.PathItem) OAIDescriptor(io.gravitee.rest.api.service.swagger.OAIDescriptor) io.gravitee.definition.model(io.gravitee.definition.model) Collectors(java.util.stream.Collectors) OAIDescriptorVisitor(io.gravitee.rest.api.service.impl.swagger.visitor.v3.OAIDescriptorVisitor) Consumer(java.util.function.Consumer) Server(io.swagger.v3.oas.models.servers.Server) HttpMethod(io.gravitee.common.http.HttpMethod) CollectionUtils(org.springframework.util.CollectionUtils) SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) Pattern(java.util.regex.Pattern) Policy(io.gravitee.policy.api.swagger.Policy) TagService(io.gravitee.rest.api.service.TagService) Properties(io.gravitee.definition.model.Properties) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) XGraviteeIODefinition(io.gravitee.rest.api.service.swagger.converter.extension.XGraviteeIODefinition) SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with SwaggerApiEntity

use of io.gravitee.rest.api.model.api.SwaggerApiEntity in project gravitee-management-rest-api by gravitee-io.

the class OAIToAPIV2Converter method fill.

@Override
protected SwaggerApiEntity fill(SwaggerApiEntity apiEntity, OpenAPI oai) {
    // flows
    apiEntity.setGraviteeDefinitionVersion(DefinitionVersion.V2.getLabel());
    if (swaggerDescriptor.isWithPolicyPaths()) {
        List<Flow> allFlows = new ArrayList();
        oai.getPaths().forEach((key, pathItem) -> {
            String path = key.replaceAll("\\{(.[^/\\}]*)\\}", ":$1");
            Map<PathItem.HttpMethod, Operation> operations = pathItem.readOperationsMap();
            operations.forEach((httpMethod, operation) -> {
                final Flow flow = createFlow(path, Collections.singleton(HttpMethod.valueOf(httpMethod.name())));
                getVisitors().forEach((Consumer<OAIOperationVisitor>) oaiOperationVisitor -> {
                    Optional<Policy> policy = (Optional<Policy>) oaiOperationVisitor.visit(oai, operation);
                    if (policy.isPresent()) {
                        final Step step = new Step();
                        step.setName(policy.get().getName());
                        step.setEnabled(true);
                        step.setDescription(operation.getSummary() == null ? (operation.getOperationId() == null ? operation.getDescription() : operation.getOperationId()) : operation.getSummary());
                        step.setPolicy(policy.get().getName());
                        String configuration = clearNullValues(policy.get().getConfiguration());
                        step.setConfiguration(configuration);
                        String scope = getScope(configuration);
                        if (scope != null && scope.toLowerCase().equals("response")) {
                            flow.getPost().add(step);
                        } else {
                            flow.getPre().add(step);
                        }
                    }
                });
                allFlows.add(flow);
            });
        });
        apiEntity.setFlows(allFlows);
        if (swaggerDescriptor.isWithPathMapping() && allFlows.size() > 0) {
            apiEntity.setPathMappings(allFlows.stream().map(flow -> flow.getPath()).collect(Collectors.toSet()));
        }
    }
    final String defaultDeclaredPath = "/";
    if (!swaggerDescriptor.isWithPathMapping()) {
        apiEntity.setPathMappings(singleton(defaultDeclaredPath));
    }
    return apiEntity;
}
Also used : Step(io.gravitee.definition.model.flow.Step) GroupService(io.gravitee.rest.api.service.GroupService) java.util(java.util) PathOperator(io.gravitee.definition.model.flow.PathOperator) Flow(io.gravitee.definition.model.flow.Flow) PathItem(io.swagger.v3.oas.models.PathItem) Operation(io.swagger.v3.oas.models.Operation) PolicyOperationVisitorManager(io.gravitee.rest.api.service.impl.swagger.policy.PolicyOperationVisitorManager) Collectors(java.util.stream.Collectors) Operator(io.gravitee.definition.model.flow.Operator) OAIOperationVisitor(io.gravitee.rest.api.service.impl.swagger.visitor.v3.OAIOperationVisitor) Consumer(java.util.function.Consumer) ImportSwaggerDescriptorEntity(io.gravitee.rest.api.model.ImportSwaggerDescriptorEntity) PolicyHelper.clearNullValues(io.gravitee.rest.api.service.validator.PolicyHelper.clearNullValues) Collections.singleton(java.util.Collections.singleton) HttpMethod(io.gravitee.common.http.HttpMethod) DefinitionVersion(io.gravitee.definition.model.DefinitionVersion) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) PolicyHelper.getScope(io.gravitee.rest.api.service.validator.PolicyHelper.getScope) Policy(io.gravitee.policy.api.swagger.Policy) TagService(io.gravitee.rest.api.service.TagService) Policy(io.gravitee.policy.api.swagger.Policy) Operation(io.swagger.v3.oas.models.Operation) Step(io.gravitee.definition.model.flow.Step) OAIOperationVisitor(io.gravitee.rest.api.service.impl.swagger.visitor.v3.OAIOperationVisitor) HttpMethod(io.gravitee.common.http.HttpMethod) Flow(io.gravitee.definition.model.flow.Flow)

Example 10 with SwaggerApiEntity

use of io.gravitee.rest.api.model.api.SwaggerApiEntity in project gravitee-management-rest-api by gravitee-io.

the class SwaggerService_CreateAPITest method shouldPrepareAPIFromSwaggerV3WithPetstoreExpanded.

@Test
public void shouldPrepareAPIFromSwaggerV3WithPetstoreExpanded() throws IOException {
    final SwaggerApiEntity api = prepareInline("io/gravitee/rest/api/management/service/mock/petstore-expanded.yaml", true, true);
    assertEquals("1.0.0", api.getVersion());
    assertEquals("Swagger Petstore", api.getName());
    assertEquals("/api", api.getProxy().getVirtualHosts().get(0).getPath());
    assertEquals("http://petstore.swagger.io/api", api.getProxy().getGroups().iterator().next().getEndpoints().iterator().next().getTarget());
    validatePolicies(api, 2, 4, asList("/pets", "/pets/:id"));
}
Also used : SwaggerApiEntity(io.gravitee.rest.api.model.api.SwaggerApiEntity) Test(org.junit.Test)

Aggregations

SwaggerApiEntity (io.gravitee.rest.api.model.api.SwaggerApiEntity)19 Test (org.junit.Test)17 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)6 HttpMethod (io.gravitee.common.http.HttpMethod)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 io.gravitee.definition.model (io.gravitee.definition.model)2 Flow (io.gravitee.definition.model.flow.Flow)2 Step (io.gravitee.definition.model.flow.Step)2 Policy (io.gravitee.policy.api.swagger.Policy)2 io.gravitee.rest.api.model (io.gravitee.rest.api.model)2 GroupService (io.gravitee.rest.api.service.GroupService)2 TagService (io.gravitee.rest.api.service.TagService)2 PolicyOperationVisitorManager (io.gravitee.rest.api.service.impl.swagger.policy.PolicyOperationVisitorManager)2 OAIOperationVisitor (io.gravitee.rest.api.service.impl.swagger.visitor.v3.OAIOperationVisitor)2 PolicyHelper.clearNullValues (io.gravitee.rest.api.service.validator.PolicyHelper.clearNullValues)2 OpenAPI (io.swagger.v3.oas.models.OpenAPI)2 Operation (io.swagger.v3.oas.models.Operation)2 PathItem (io.swagger.v3.oas.models.PathItem)2 Collections.singleton (java.util.Collections.singleton)2