Search in sources :

Example 1 with Path

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

the class ApiServiceImpl method createOrUpdateWithDefinition.

@Override
public ApiEntity createOrUpdateWithDefinition(final ApiEntity apiEntity, String apiDefinition, String userId) {
    try {
        final UpdateApiEntity importedApi = objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(apiDefinition, UpdateApiEntity.class);
        // Initialize with a default path
        if (importedApi.getPaths() == null || importedApi.getPaths().isEmpty()) {
            Path path = new Path();
            path.setPath("/");
            importedApi.setPaths(Collections.singletonMap("/", path));
        }
        // create group if not exist & replace groupName by groupId
        if (importedApi.getGroups() != null) {
            Set<String> groupNames = new HashSet<>(importedApi.getGroups());
            importedApi.getGroups().clear();
            for (String name : groupNames) {
                List<GroupEntity> groupEntities = groupService.findByName(name);
                GroupEntity group;
                if (groupEntities.isEmpty()) {
                    NewGroupEntity newGroupEntity = new NewGroupEntity();
                    newGroupEntity.setName(name);
                    group = groupService.create(newGroupEntity);
                } else {
                    group = groupEntities.get(0);
                }
                importedApi.getGroups().add(group.getId());
            }
        }
        ApiEntity createdOrUpdatedApiEntity;
        Set<MemberToImport> members;
        if (apiEntity == null || apiEntity.getId() == null) {
            createdOrUpdatedApiEntity = create0(importedApi, userId);
            members = Collections.emptySet();
        } else {
            createdOrUpdatedApiEntity = update(apiEntity.getId(), importedApi);
            members = membershipService.getMembers(MembershipReferenceType.API, apiEntity.getId(), RoleScope.API).stream().map(member -> new MemberToImport(member.getUsername(), member.getRole())).collect(Collectors.toSet());
        }
        // Read the whole definition
        final JsonNode jsonNode = objectMapper.readTree(apiDefinition);
        // Members
        final JsonNode membersDefinition = jsonNode.path("members");
        if (membersDefinition != null && membersDefinition.isArray()) {
            MemberEntity memberAsPrimaryOwner = null;
            for (final JsonNode memberNode : membersDefinition) {
                MemberToImport memberEntity = objectMapper.readValue(memberNode.toString(), MemberToImport.class);
                Collection<SearchableUser> idpUsers = identityService.search(memberEntity.getUsername());
                if (!idpUsers.isEmpty()) {
                    SearchableUser user = idpUsers.iterator().next();
                    if (!members.contains(memberEntity) || members.stream().anyMatch(m -> m.getUsername().equals(memberEntity.getUsername()) && !m.getRole().equals(memberEntity.getRole()))) {
                        MemberEntity membership = membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId()), new MembershipService.MembershipUser(user.getId(), user.getReference()), new MembershipService.MembershipRole(RoleScope.API, memberEntity.getRole()));
                        if (SystemRole.PRIMARY_OWNER.name().equals(memberEntity.getRole())) {
                            // Get the identifier of the primary owner
                            memberAsPrimaryOwner = membership;
                        }
                    }
                }
            }
            // Transfer ownership if necessary
            if (memberAsPrimaryOwner != null && !userId.equals(memberAsPrimaryOwner.getId())) {
                membershipService.transferApiOwnership(createdOrUpdatedApiEntity.getId(), new MembershipService.MembershipUser(memberAsPrimaryOwner.getId(), null), null);
            }
        }
        // Pages
        final JsonNode pagesDefinition = jsonNode.path("pages");
        if (pagesDefinition != null && pagesDefinition.isArray()) {
            for (final JsonNode pageNode : pagesDefinition) {
                PageQuery query = new PageQuery.Builder().api(createdOrUpdatedApiEntity.getId()).name(pageNode.get("name").asText()).type(PageType.valueOf(pageNode.get("type").asText())).build();
                List<PageEntity> pageEntities = pageService.search(query);
                if (pageEntities == null || pageEntities.isEmpty()) {
                    pageService.createApiPage(createdOrUpdatedApiEntity.getId(), objectMapper.readValue(pageNode.toString(), NewPageEntity.class));
                } else if (pageEntities.size() == 1) {
                    UpdatePageEntity updatePageEntity = objectMapper.readValue(pageNode.toString(), UpdatePageEntity.class);
                    pageService.update(pageEntities.get(0).getId(), updatePageEntity);
                } else {
                    LOGGER.error("Not able to identify the page to update: {}. Too much page with the same name", pageNode.get("name").asText());
                    throw new TechnicalManagementException("Not able to identify the page to update: " + pageNode.get("name").asText() + ". Too much page with the same name");
                }
            }
        }
        // Plans
        final JsonNode plansDefinition = jsonNode.path("plans");
        if (plansDefinition != null && plansDefinition.isArray()) {
            for (JsonNode planNode : plansDefinition) {
                PlanQuery query = new PlanQuery.Builder().api(createdOrUpdatedApiEntity.getId()).name(planNode.get("name").asText()).security(PlanSecurityType.valueOf(planNode.get("security").asText())).build();
                List<PlanEntity> planEntities = planService.search(query);
                if (planEntities == null || planEntities.isEmpty()) {
                    NewPlanEntity newPlanEntity = objectMapper.readValue(planNode.toString(), NewPlanEntity.class);
                    newPlanEntity.setApi(createdOrUpdatedApiEntity.getId());
                    planService.create(newPlanEntity);
                } else if (planEntities.size() == 1) {
                    UpdatePlanEntity updatePlanEntity = objectMapper.readValue(planNode.toString(), UpdatePlanEntity.class);
                    planService.update(updatePlanEntity);
                } else {
                    LOGGER.error("Not able to identify the plan to update: {}. Too much plan with the same name", planNode.get("name").asText());
                    throw new TechnicalManagementException("Not able to identify the plan to update: " + planNode.get("name").asText() + ". Too much plan with the same name");
                }
            }
        }
        return createdOrUpdatedApiEntity;
    } catch (final IOException e) {
        LOGGER.error("An error occurs while trying to JSON deserialize the API {}", apiDefinition, e);
    }
    return null;
}
Also used : PlanQuery(io.gravitee.management.model.plan.PlanQuery) java.util(java.util) HookScope(io.gravitee.management.service.notification.HookScope) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) PageQuery(io.gravitee.management.model.documentation.PageQuery) Visibility(io.gravitee.repository.management.model.Visibility) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Proxy(io.gravitee.definition.model.Proxy) Value(org.springframework.beans.factory.annotation.Value) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) EventType(io.gravitee.management.model.EventType) ApiSynchronizationProcessor(io.gravitee.management.service.processor.ApiSynchronizationProcessor) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) ApiRepository(io.gravitee.repository.management.api.ApiRepository) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) Lifecycle(io.gravitee.common.component.Lifecycle) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) Logger(org.slf4j.Logger) ApiHook(io.gravitee.management.service.notification.ApiHook) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) Path(io.gravitee.definition.model.Path) PageType(io.gravitee.management.model.PageType) DatatypeConverter(javax.xml.bind.DatatypeConverter) PlanQuery(io.gravitee.management.model.plan.PlanQuery) PageQuery(io.gravitee.management.model.documentation.PageQuery) JsonNode(com.fasterxml.jackson.databind.JsonNode) Path(io.gravitee.definition.model.Path) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) IOException(java.io.IOException)

Example 2 with Path

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

the class ApiServiceImpl method create.

@Override
public ApiEntity create(NewApiEntity newApiEntity, String userId) throws ApiAlreadyExistsException {
    UpdateApiEntity apiEntity = new UpdateApiEntity();
    apiEntity.setName(newApiEntity.getName());
    apiEntity.setDescription(newApiEntity.getDescription());
    apiEntity.setVersion(newApiEntity.getVersion());
    // check the existence of groups
    if (newApiEntity.getGroups() != null && !newApiEntity.getGroups().isEmpty()) {
        try {
            groupService.findByIds(newApiEntity.getGroups());
        } catch (GroupsNotFoundException gnfe) {
            throw new InvalidDataException("Groups [" + newApiEntity.getGroups() + "] does not exist");
        }
    }
    apiEntity.setGroups(newApiEntity.getGroups());
    Proxy proxy = new Proxy();
    proxy.setContextPath(newApiEntity.getContextPath());
    proxy.setEndpoints(new LinkedHashSet<>());
    proxy.getEndpoints().add(new HttpEndpoint("default", newApiEntity.getEndpoint()));
    apiEntity.setProxy(proxy);
    List<String> declaredPaths = (newApiEntity.getPaths() != null) ? newApiEntity.getPaths() : new ArrayList<>();
    if (!declaredPaths.contains("/")) {
        declaredPaths.add(0, "/");
    }
    // Initialize with a default path and provided paths
    Map<String, Path> paths = declaredPaths.stream().map(sPath -> {
        Path path = new Path();
        path.setPath(sPath);
        return path;
    }).collect(Collectors.toMap(Path::getPath, path -> path));
    apiEntity.setPaths(paths);
    return create0(apiEntity, userId);
}
Also used : Path(io.gravitee.definition.model.Path) PlanQuery(io.gravitee.management.model.plan.PlanQuery) java.util(java.util) HookScope(io.gravitee.management.service.notification.HookScope) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) PageQuery(io.gravitee.management.model.documentation.PageQuery) Visibility(io.gravitee.repository.management.model.Visibility) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Proxy(io.gravitee.definition.model.Proxy) Value(org.springframework.beans.factory.annotation.Value) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) EventType(io.gravitee.management.model.EventType) ApiSynchronizationProcessor(io.gravitee.management.service.processor.ApiSynchronizationProcessor) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) ApiRepository(io.gravitee.repository.management.api.ApiRepository) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) Lifecycle(io.gravitee.common.component.Lifecycle) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) Logger(org.slf4j.Logger) ApiHook(io.gravitee.management.service.notification.ApiHook) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) Path(io.gravitee.definition.model.Path) PageType(io.gravitee.management.model.PageType) DatatypeConverter(javax.xml.bind.DatatypeConverter) Proxy(io.gravitee.definition.model.Proxy) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint)

Example 3 with Path

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

the class ApiService_ExportAsJsonTest method setUp.

@Before
public void setUp() throws TechnicalException {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    Api api = new Api();
    api.setId(API_ID);
    api.setDescription("Gravitee.io");
    when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
    PageEntity page = new PageEntity();
    page.setName("My Title");
    page.setOrder(1);
    page.setType(PageType.MARKDOWN.toString());
    page.setContent("Read the doc");
    when(pageService.findApiPagesByApi(API_ID)).thenReturn(Collections.singletonList(new PageListItem()));
    when(pageService.findById(any())).thenReturn(page);
    Membership membership = new Membership();
    membership.setUserId("johndoe");
    membership.setReferenceId(API_ID);
    membership.setReferenceType(MembershipReferenceType.API);
    membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
    when(membershipRepository.findByReferenceAndRole(eq(MembershipReferenceType.API), eq(API_ID), any(), any())).thenReturn(Collections.singleton(membership));
    MemberEntity memberEntity = new MemberEntity();
    memberEntity.setUsername(membership.getUserId());
    memberEntity.setRole(SystemRole.PRIMARY_OWNER.name());
    when(membershipService.getMembers(eq(MembershipReferenceType.API), eq(API_ID), eq(RoleScope.API))).thenReturn(Collections.singleton(memberEntity));
    UserEntity userEntity = new UserEntity();
    userEntity.setUsername(memberEntity.getId());
    when(userService.findByUsername(memberEntity.getId(), false)).thenReturn(userEntity);
    api.setGroups(Collections.singleton("my-group"));
    GroupEntity groupEntity = new GroupEntity();
    groupEntity.setId("my-group");
    groupEntity.setName("My Group");
    when(groupService.findByIds(api.getGroups())).thenReturn(Collections.singleton(groupEntity));
    PlanEntity publishedPlan = new PlanEntity();
    publishedPlan.setId("plan-id");
    publishedPlan.setApis(Collections.singleton(API_ID));
    publishedPlan.setDescription("free plan");
    publishedPlan.setType(PlanType.API);
    publishedPlan.setSecurity(PlanSecurityType.API_KEY);
    publishedPlan.setValidation(PlanValidationType.AUTO);
    publishedPlan.setStatus(PlanStatus.PUBLISHED);
    Map<String, Path> paths = new HashMap<>();
    Path path = new Path();
    path.setPath("/");
    io.gravitee.definition.model.Rule rule = new io.gravitee.definition.model.Rule();
    rule.setEnabled(true);
    rule.setMethods(Collections.singletonList(HttpMethod.GET));
    Policy policy = new Policy();
    policy.setName("rate-limit");
    String ls = System.lineSeparator();
    policy.setConfiguration("{" + ls + "          \"rate\": {" + ls + "            \"limit\": 1," + ls + "            \"periodTime\": 1," + ls + "            \"periodTimeUnit\": \"SECONDS\"" + ls + "          }" + ls + "        }");
    rule.setPolicy(policy);
    path.setRules(Collections.singletonList(rule));
    paths.put("/", path);
    publishedPlan.setPaths(paths);
    PlanEntity closedPlan = new PlanEntity();
    closedPlan.setId("closedPlan-id");
    closedPlan.setApis(Collections.singleton(API_ID));
    closedPlan.setDescription("free closedPlan");
    closedPlan.setType(PlanType.API);
    closedPlan.setSecurity(PlanSecurityType.API_KEY);
    closedPlan.setValidation(PlanValidationType.AUTO);
    closedPlan.setStatus(PlanStatus.CLOSED);
    closedPlan.setPaths(paths);
    Set<PlanEntity> set = new HashSet<>();
    set.add(publishedPlan);
    set.add(closedPlan);
    when(planService.findByApi(API_ID)).thenReturn(set);
}
Also used : Path(io.gravitee.definition.model.Path) Policy(io.gravitee.definition.model.Policy) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Membership(io.gravitee.repository.management.model.Membership) PropertyFilter(com.fasterxml.jackson.databind.ser.PropertyFilter) ApiPermissionFilter(io.gravitee.management.service.jackson.filter.ApiPermissionFilter) io.gravitee.management.model(io.gravitee.management.model) Api(io.gravitee.repository.management.model.Api) Before(org.junit.Before)

Example 4 with Path

use of io.gravitee.definition.model.Path in project gravitee-gateway by gravitee-io.

the class ApiPathResolverTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    final Map<String, Path> paths = new HashMap<>();
    paths.putAll(new HashMap<String, Path>() {

        {
            Path p1 = new Path();
            p1.setPath("/");
            put(p1.getPath(), p1);
            Path p2 = new Path();
            p2.setPath("/products");
            put(p2.getPath(), p2);
            Path p3 = new Path();
            p3.setPath("/stores");
            put(p3.getPath(), p3);
            Path p4 = new Path();
            p4.setPath("/stores/:storeId");
            put(p4.getPath(), p4);
            Path p5 = new Path();
            p5.setPath("/[0-9,;]+");
            put(p5.getPath(), p5);
            Path p6 = new Path();
            p6.setPath("/Stores/:storeId");
            put(p6.getPath(), p6);
        }
    });
    // API 1
    Proxy proxy = new Proxy();
    proxy.setContextPath("/");
    when(api.getProxy()).thenReturn(proxy);
    when(api.getPaths()).thenReturn(paths);
    pathResolver = new ApiPathResolverImpl(api);
    // API 2
    Proxy proxy2 = new Proxy();
    proxy2.setContextPath("/v1/products");
    when(api2.getProxy()).thenReturn(proxy2);
    when(api2.getPaths()).thenReturn(paths);
    pathResolver2 = new ApiPathResolverImpl(api2);
}
Also used : Path(io.gravitee.definition.model.Path) Proxy(io.gravitee.definition.model.Proxy) HashMap(java.util.HashMap) ApiPathResolverImpl(io.gravitee.gateway.handlers.api.path.impl.ApiPathResolverImpl) Before(org.junit.Before)

Example 5 with Path

use of io.gravitee.definition.model.Path in project gravitee-gateway by gravitee-io.

the class PlanPolicyChainResolver method calculate.

@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
    if (streamType == StreamType.ON_REQUEST) {
        String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
        String application = (String) executionContext.getAttribute(ExecutionContext.ATTR_APPLICATION);
        // String user = (String) executionContext.getAttribute(ExecutionContext.ATTR_USER_ID);
        // request.metrics().setUserId(user);
        request.metrics().setPlan(plan);
        request.metrics().setApplication(application);
        Plan apiPlan = api.getPlan(plan);
        // The call is probably not relative to the same API.
        if (plan != null && apiPlan != null) {
            Map<String, Path> paths = api.getPlan(plan).getPaths();
            if (paths != null && !paths.isEmpty()) {
                // For 1.0.0, there is only a single root path defined
                // Must be reconsidered when user will be able to manage policies at the plan level by himself
                Path rootPath = paths.values().iterator().next();
                return rootPath.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
            }
        } else {
            logger.warn("No plan has been selected to process request {}. Returning an unauthorized HTTP status (401)", request.id());
            return null;
        }
    }
    return Collections.emptyList();
}
Also used : Path(io.gravitee.definition.model.Path) PolicyChain(io.gravitee.gateway.policy.impl.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) RequestPolicyChain(io.gravitee.gateway.policy.impl.RequestPolicyChain) Autowired(org.springframework.beans.factory.annotation.Autowired) Plan(io.gravitee.gateway.handlers.api.definition.Plan) ResponsePolicyChain(io.gravitee.gateway.policy.impl.ResponsePolicyChain) Collectors(java.util.stream.Collectors) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) Objects(java.util.Objects) List(java.util.List) Response(io.gravitee.gateway.api.Response) Request(io.gravitee.gateway.api.Request) Map(java.util.Map) Api(io.gravitee.gateway.handlers.api.definition.Api) Path(io.gravitee.definition.model.Path) io.gravitee.gateway.policy(io.gravitee.gateway.policy) PolicyResult(io.gravitee.policy.api.PolicyResult) Collections(java.util.Collections) Plan(io.gravitee.gateway.handlers.api.definition.Plan)

Aggregations

Path (io.gravitee.definition.model.Path)6 Proxy (io.gravitee.definition.model.Proxy)3 io.gravitee.management.model (io.gravitee.management.model)3 IOException (java.io.IOException)3 Collectors (java.util.stream.Collectors)3 Autowired (org.springframework.beans.factory.annotation.Autowired)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 Lifecycle (io.gravitee.common.component.Lifecycle)2 UUID (io.gravitee.common.utils.UUID)2 HttpEndpoint (io.gravitee.definition.model.endpoint.HttpEndpoint)2 Plan (io.gravitee.gateway.handlers.api.definition.Plan)2 SearchableUser (io.gravitee.management.idp.api.identity.SearchableUser)2 EventType (io.gravitee.management.model.EventType)2 PageType (io.gravitee.management.model.PageType)2 PageQuery (io.gravitee.management.model.documentation.PageQuery)2 GenericNotificationConfigEntity (io.gravitee.management.model.notification.GenericNotificationConfigEntity)2