Search in sources :

Example 1 with SearchableUser

use of io.gravitee.management.idp.api.identity.SearchableUser 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)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 Lifecycle (io.gravitee.common.component.Lifecycle)1 UUID (io.gravitee.common.utils.UUID)1 Path (io.gravitee.definition.model.Path)1 Proxy (io.gravitee.definition.model.Proxy)1 HttpEndpoint (io.gravitee.definition.model.endpoint.HttpEndpoint)1 SearchableUser (io.gravitee.management.idp.api.identity.SearchableUser)1 io.gravitee.management.model (io.gravitee.management.model)1 EventType (io.gravitee.management.model.EventType)1 PageType (io.gravitee.management.model.PageType)1 PageQuery (io.gravitee.management.model.documentation.PageQuery)1 GenericNotificationConfigEntity (io.gravitee.management.model.notification.GenericNotificationConfigEntity)1 SystemRole (io.gravitee.management.model.permissions.SystemRole)1 PlanQuery (io.gravitee.management.model.plan.PlanQuery)1 io.gravitee.management.service (io.gravitee.management.service)1 io.gravitee.management.service.exceptions (io.gravitee.management.service.exceptions)1