Search in sources :

Example 1 with Visibility

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

the class PageServiceImpl method update.

@Override
public PageEntity update(String pageId, UpdatePageEntity updatePageEntity, boolean partial) {
    try {
        logger.debug("Update Page {}", pageId);
        Optional<Page> optPageToUpdate = pageRepository.findById(pageId);
        if (!optPageToUpdate.isPresent()) {
            throw new PageNotFoundException(pageId);
        }
        Page pageToUpdate = optPageToUpdate.get();
        Page page = null;
        String pageType = pageToUpdate.getType();
        // create page revision if content has changed only for :
        // - SWAGGER
        // - Markdown
        // - Translation
        boolean createRevision = false;
        if (PageType.LINK.name().equalsIgnoreCase(pageType)) {
            String newResourceRef = updatePageEntity.getContent();
            String actualResourceRef = pageToUpdate.getContent();
            if (newResourceRef != null && !newResourceRef.equals(actualResourceRef)) {
                String resourceType = (updatePageEntity.getConfiguration() != null ? updatePageEntity.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE) : pageToUpdate.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE));
                if (PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) && (updatePageEntity.getContent() != null && updatePageEntity.getContent().isEmpty())) {
                    throw new PageActionException(PageType.LINK, "be created. An external Link must have a URL");
                }
                if ("root".equals(newResourceRef) || PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) || PageConfigurationKeys.LINK_RESOURCE_TYPE_CATEGORY.equals(resourceType)) {
                    updatePageEntity.setPublished(true);
                } else {
                    Optional<Page> optionalRelatedPage = pageRepository.findById(newResourceRef);
                    if (optionalRelatedPage.isPresent()) {
                        Page relatedPage = optionalRelatedPage.get();
                        checkLinkRelatedPageType(relatedPage);
                        updatePageEntity.setPublished(relatedPage.isPublished());
                    }
                }
            } else if (newResourceRef != null && newResourceRef.equals(actualResourceRef)) {
                // can not publish or unpublish a Link. LINK publication state is changed when the related page is updated.
                updatePageEntity.setPublished(pageToUpdate.isPublished());
            }
        }
        if (PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) {
            String parentId = (updatePageEntity.getParentId() != null && !updatePageEntity.getParentId().isEmpty()) ? updatePageEntity.getParentId() : pageToUpdate.getParentId();
            Map<String, String> configuration = updatePageEntity.getConfiguration() != null ? updatePageEntity.getConfiguration() : pageToUpdate.getConfiguration();
            checkTranslationConsistency(parentId, configuration, false);
            boolean hasChanged = pageHasChanged(updatePageEntity, pageToUpdate);
            Optional<Page> optParentPage = this.pageRepository.findById(parentId);
            if (optParentPage.isPresent()) {
                createRevision = isSwaggerOrMarkdown(optParentPage.get().getType()) && hasChanged;
            }
        }
        if (updatePageEntity.getParentId() != null && !updatePageEntity.getParentId().equals(pageToUpdate.getParentId())) {
            checkUpdatedPageSituation(updatePageEntity, pageType, pageId);
            if (PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) {
                Optional<Page> optionalTranslatedPage = pageRepository.findById(updatePageEntity.getParentId());
                if (optionalTranslatedPage.isPresent()) {
                    updatePageEntity.setPublished(optionalTranslatedPage.get().isPublished());
                }
            }
        }
        if (updatePageEntity.getExcludedGroups() != null && !updatePageEntity.getExcludedGroups().isEmpty()) {
            updatePageEntity.setVisibility(Visibility.PRIVATE);
            updatePageEntity.setExcludedAccessControls(true);
            Set<AccessControlEntity> accessControlEntities = updatePageEntity.getAccessControls() != null ? updatePageEntity.getAccessControls() : new HashSet<>();
            accessControlEntities.addAll(updatePageEntity.getExcludedGroups().stream().map((groupId -> {
                AccessControlEntity accessControl = new AccessControlEntity();
                accessControl.setReferenceType("GROUP");
                accessControl.setReferenceId(groupId);
                return accessControl;
            })).collect(Collectors.toSet()));
            updatePageEntity.setAccessControls(accessControlEntities);
            updatePageEntity.setExcludedGroups(updatePageEntity.getExcludedGroups());
        }
        if (partial) {
            page = merge(updatePageEntity, pageToUpdate);
        } else {
            page = convert(updatePageEntity);
        }
        if (page.getSource() != null) {
            try {
                if (pageToUpdate.getSource() != null && pageToUpdate.getSource().getConfiguration() != null) {
                    mergeSensitiveData(this.getFetcher(pageToUpdate.getSource()).getConfiguration(), page);
                }
                fetchPage(page);
            } catch (FetcherException e) {
                throw onUpdateFail(pageId, e);
            }
        } else {
            // set null to remove the value not set to false
            page.setUseAutoFetch(null);
        }
        if (isSwaggerOrMarkdown(pageType)) {
            createRevision = pageHasChanged(pageToUpdate, page);
        }
        page.setId(pageId);
        page.setUpdatedAt(new Date());
        // Copy fields from existing values
        page.setCreatedAt(pageToUpdate.getCreatedAt());
        page.setType(pageType);
        page.setReferenceId(pageToUpdate.getReferenceId());
        page.setReferenceType(pageToUpdate.getReferenceType());
        if (page.getVisibility() == null) {
            page.setVisibility(pageToUpdate.getVisibility());
        }
        onlyOneHomepage(page);
        // we can't unpublish it until the plan is closed
        if (PageReferenceType.API.equals(pageToUpdate.getReferenceType())) {
            if (updatePageEntity.isPublished() != null && !updatePageEntity.isPublished()) {
                Optional<PlanEntity> activePlan = planService.findByApi(pageToUpdate.getReferenceId()).stream().filter(plan -> plan.getGeneralConditions() != null).filter(plan -> pageToUpdate.getId().equals(plan.getGeneralConditions())).filter(plan -> !(PlanStatus.CLOSED.equals(plan.getStatus()) || PlanStatus.STAGING.equals(plan.getStatus()))).findFirst();
                if (activePlan.isPresent()) {
                    throw new PageUsedAsGeneralConditionsException(pageId, page.getName(), "unpublish", activePlan.get().getName());
                }
            }
        }
        // we can't unpublish it
        if (PageReferenceType.ENVIRONMENT.equals(pageToUpdate.getReferenceType())) {
            if (updatePageEntity.isPublished() != null && !updatePageEntity.isPublished()) {
                List<CategoryEntity> categoriesUsingPage = categoryService.findByPage(pageId);
                if (!categoriesUsingPage.isEmpty()) {
                    String categoriesName = categoriesUsingPage.stream().map(CategoryEntity::getName).collect(Collectors.joining(", ", "{ ", " }"));
                    throw new PageUsedByCategoryException(pageId, page.getName(), "unpublish", categoriesName);
                }
            }
        }
        // if order change, reorder all pages
        if (page.getOrder() != pageToUpdate.getOrder()) {
            reorderAndSavePages(page);
            if (createRevision) {
                createPageRevision(page);
            }
            return null;
        } else {
            List<String> messages = validateSafeContent(page);
            Page updatedPage = pageRepository.update(page);
            if ((pageToUpdate.isPublished() != page.isPublished() || !Objects.equals(pageToUpdate.getVisibility(), page.getVisibility())) && !PageType.LINK.name().equalsIgnoreCase(pageType) && !PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) {
                // if just publishing the page, updatePageEntity.getVisibility() will return null. In that case, we must keep the existing visibility status.
                String newVisibility = updatePageEntity.getVisibility() == null ? pageToUpdate.getVisibility() : updatePageEntity.getVisibility().name();
                // update all the related links and translations publication status.
                this.changeRelatedPagesPublicationStatusAndVisibility(pageId, updatePageEntity.isPublished(), newVisibility);
            }
            createAuditLog(PageReferenceType.API.equals(page.getReferenceType()) ? page.getReferenceId() : null, PAGE_UPDATED, page.getUpdatedAt(), pageToUpdate, page);
            if (createRevision) {
                createPageRevision(updatedPage);
            }
            PageEntity pageEntity = convert(updatedPage);
            pageEntity.setMessages(messages);
            // update document in search engine
            if (pageToUpdate.isPublished() && !page.isPublished()) {
                searchEngineService.delete(convert(pageToUpdate), false);
            } else {
                index(pageEntity);
            }
            return pageEntity;
        }
    } catch (TechnicalException ex) {
        throw onUpdateFail(pageId, ex);
    }
}
Also used : GraviteeDescriptorEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) PageConfigurationOAITransformer(io.gravitee.rest.api.service.impl.swagger.transformer.page.PageConfigurationOAITransformer) Arrays.asList(java.util.Arrays.asList) Gson(com.google.gson.Gson) FetcherConfigurationFactory(io.gravitee.rest.api.fetcher.FetcherConfigurationFactory) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) CronSequenceGenerator(org.springframework.scheduling.support.CronSequenceGenerator) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HtmlSanitizer(io.gravitee.rest.api.service.sanitizer.HtmlSanitizer) PageCriteria(io.gravitee.repository.management.api.search.PageCriteria) GraviteeDescriptorPageEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorPageEntity) PluginManager(io.gravitee.plugin.core.api.PluginManager) OAIParser(io.gravitee.rest.api.service.impl.swagger.parser.OAIParser) Collectors(java.util.stream.Collectors) FetcherPlugin(io.gravitee.plugin.fetcher.FetcherPlugin) MediaType(io.gravitee.common.http.MediaType) Stream(java.util.stream.Stream) Visibility(io.gravitee.rest.api.model.Visibility) CollectionUtils(org.springframework.util.CollectionUtils) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) PAGE(io.gravitee.repository.management.model.Audit.AuditProperties.PAGE) ApplicationContextAware(org.springframework.context.ApplicationContextAware) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) AuditEvent(io.gravitee.repository.management.model.Page.AuditEvent) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) Pageable(io.gravitee.rest.api.model.common.Pageable) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) EntrypointsOAITransformer(io.gravitee.rest.api.service.impl.swagger.transformer.entrypoints.EntrypointsOAITransformer) Value(org.springframework.beans.factory.annotation.Value) SwaggerTransformer(io.gravitee.rest.api.service.impl.swagger.transformer.SwaggerTransformer) NotificationTemplateService(io.gravitee.rest.api.service.notification.NotificationTemplateService) PageRepository(io.gravitee.repository.management.api.PageRepository) io.gravitee.rest.api.model(io.gravitee.rest.api.model) UuidString(io.gravitee.rest.api.service.common.UuidString) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) OAIDescriptor(io.gravitee.rest.api.service.swagger.OAIDescriptor) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) io.gravitee.fetcher.api(io.gravitee.fetcher.api) io.gravitee.repository.management.model(io.gravitee.repository.management.model) SwaggerDescriptor(io.gravitee.rest.api.service.swagger.SwaggerDescriptor) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) GraviteeDescriptorPageEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorPageEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString)

Example 2 with Visibility

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

the class PageServiceImpl method createPage.

private PageEntity createPage(String apiId, NewPageEntity newPageEntity, String environmentId, String pageId) {
    try {
        logger.debug("Create page {} for API {}", newPageEntity, apiId);
        String id = pageId != null && UUID.fromString(pageId) != null ? pageId : UuidString.generateRandom();
        PageType newPageType = newPageEntity.getType();
        // handle default visibility
        if (newPageEntity.getVisibility() == null) {
            newPageEntity.setVisibility(Visibility.PUBLIC);
        }
        // create page revision only for :
        // - SWAGGER
        // - Markdown
        // - Translation
        boolean createRevision = false;
        // Useful when import api with pages in old version
        if (newPageEntity.getExcludedGroups() != null && !newPageEntity.getExcludedGroups().isEmpty()) {
            newPageEntity.setVisibility(Visibility.PRIVATE);
            newPageEntity.setExcludedAccessControls(true);
            newPageEntity.setAccessControls(newPageEntity.getExcludedGroups().stream().map((groupId -> {
                AccessControlEntity accessControl = new AccessControlEntity();
                accessControl.setReferenceType("GROUP");
                accessControl.setReferenceId(groupId);
                return accessControl;
            })).collect(Collectors.toSet()));
        }
        if (PageType.TRANSLATION.equals(newPageType)) {
            checkTranslationConsistency(newPageEntity.getParentId(), newPageEntity.getConfiguration(), true);
            Optional<Page> optTranslatedPage = this.pageRepository.findById(newPageEntity.getParentId());
            if (optTranslatedPage.isPresent()) {
                newPageEntity.setPublished(optTranslatedPage.get().isPublished());
                // create revision only for Swagger & Markdown page
                createRevision = isSwaggerOrMarkdown(optTranslatedPage.get().getType());
            }
        }
        if (PageType.FOLDER.equals(newPageType)) {
            checkFolderConsistency(newPageEntity);
        }
        if (PageType.LINK.equals(newPageType)) {
            String resourceType = newPageEntity.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE);
            String content = newPageEntity.getContent();
            if (content == null || content.isEmpty()) {
                throw new PageActionException(PageType.LINK, "be created. It must have a URL, a page Id or a category Id");
            }
            if ("root".equals(content) || PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) || PageConfigurationKeys.LINK_RESOURCE_TYPE_CATEGORY.equals(resourceType)) {
                newPageEntity.setPublished(true);
            } else {
                Optional<Page> optionalRelatedPage = pageRepository.findById(content);
                if (optionalRelatedPage.isPresent()) {
                    Page relatedPage = optionalRelatedPage.get();
                    checkLinkRelatedPageType(relatedPage);
                    newPageEntity.setPublished(relatedPage.isPublished());
                    newPageEntity.setVisibility(Visibility.valueOf(relatedPage.getVisibility()));
                }
            }
        }
        if (PageType.SWAGGER == newPageType || PageType.MARKDOWN == newPageType) {
            checkMarkdownOrSwaggerConsistency(newPageEntity, newPageType);
            createRevision = true;
        }
        Page page = convert(newPageEntity);
        if (page.getSource() != null) {
            fetchPage(page);
        }
        page.setId(id);
        if (StringUtils.isEmpty(apiId)) {
            page.setReferenceId(environmentId);
            page.setReferenceType(PageReferenceType.ENVIRONMENT);
        } else {
            page.setReferenceId(apiId);
            page.setReferenceType(PageReferenceType.API);
        }
        // Set date fields
        page.setCreatedAt(new Date());
        page.setUpdatedAt(page.getCreatedAt());
        List<String> messages = validateSafeContent(page);
        Page createdPage = this.pageRepository.create(page);
        if (createRevision) {
            createPageRevision(createdPage);
        }
        // only one homepage is allowed
        onlyOneHomepage(page);
        createAuditLog(PageReferenceType.API.equals(page.getReferenceType()) ? page.getReferenceId() : null, PAGE_CREATED, page.getCreatedAt(), null, page);
        PageEntity pageEntity = convert(createdPage);
        if (messages != null && messages.size() > 0) {
            pageEntity.setMessages(messages);
        }
        // add document in search engine
        index(pageEntity);
        return pageEntity;
    } catch (TechnicalException | FetcherException ex) {
        logger.error("An error occurs while trying to create {}", newPageEntity, ex);
        throw new TechnicalManagementException("An error occurs while trying create " + newPageEntity, ex);
    }
}
Also used : GraviteeDescriptorEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) PageConfigurationOAITransformer(io.gravitee.rest.api.service.impl.swagger.transformer.page.PageConfigurationOAITransformer) Arrays.asList(java.util.Arrays.asList) Gson(com.google.gson.Gson) FetcherConfigurationFactory(io.gravitee.rest.api.fetcher.FetcherConfigurationFactory) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) CronSequenceGenerator(org.springframework.scheduling.support.CronSequenceGenerator) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HtmlSanitizer(io.gravitee.rest.api.service.sanitizer.HtmlSanitizer) PageCriteria(io.gravitee.repository.management.api.search.PageCriteria) GraviteeDescriptorPageEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorPageEntity) PluginManager(io.gravitee.plugin.core.api.PluginManager) OAIParser(io.gravitee.rest.api.service.impl.swagger.parser.OAIParser) Collectors(java.util.stream.Collectors) FetcherPlugin(io.gravitee.plugin.fetcher.FetcherPlugin) MediaType(io.gravitee.common.http.MediaType) Stream(java.util.stream.Stream) Visibility(io.gravitee.rest.api.model.Visibility) CollectionUtils(org.springframework.util.CollectionUtils) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) PAGE(io.gravitee.repository.management.model.Audit.AuditProperties.PAGE) ApplicationContextAware(org.springframework.context.ApplicationContextAware) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) AuditEvent(io.gravitee.repository.management.model.Page.AuditEvent) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) Pageable(io.gravitee.rest.api.model.common.Pageable) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) EntrypointsOAITransformer(io.gravitee.rest.api.service.impl.swagger.transformer.entrypoints.EntrypointsOAITransformer) Value(org.springframework.beans.factory.annotation.Value) SwaggerTransformer(io.gravitee.rest.api.service.impl.swagger.transformer.SwaggerTransformer) NotificationTemplateService(io.gravitee.rest.api.service.notification.NotificationTemplateService) PageRepository(io.gravitee.repository.management.api.PageRepository) io.gravitee.rest.api.model(io.gravitee.rest.api.model) UuidString(io.gravitee.rest.api.service.common.UuidString) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) OAIDescriptor(io.gravitee.rest.api.service.swagger.OAIDescriptor) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) io.gravitee.fetcher.api(io.gravitee.fetcher.api) io.gravitee.repository.management.model(io.gravitee.repository.management.model) SwaggerDescriptor(io.gravitee.rest.api.service.swagger.SwaggerDescriptor) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) GraviteeDescriptorPageEntity(io.gravitee.rest.api.model.descriptor.GraviteeDescriptorPageEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Gson (com.google.gson.Gson)2 MediaType (io.gravitee.common.http.MediaType)2 io.gravitee.fetcher.api (io.gravitee.fetcher.api)2 PluginManager (io.gravitee.plugin.core.api.PluginManager)2 FetcherPlugin (io.gravitee.plugin.fetcher.FetcherPlugin)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)2 PageRepository (io.gravitee.repository.management.api.PageRepository)2 PageCriteria (io.gravitee.repository.management.api.search.PageCriteria)2 PageableBuilder (io.gravitee.repository.management.api.search.builder.PageableBuilder)2 io.gravitee.repository.management.model (io.gravitee.repository.management.model)2 PAGE (io.gravitee.repository.management.model.Audit.AuditProperties.PAGE)2 AuditEvent (io.gravitee.repository.management.model.Page.AuditEvent)2 FetcherConfigurationFactory (io.gravitee.rest.api.fetcher.FetcherConfigurationFactory)2 io.gravitee.rest.api.model (io.gravitee.rest.api.model)2 Visibility (io.gravitee.rest.api.model.Visibility)2