Search in sources :

Example 31 with TechnicalManagementException

use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.

the class EnvironmentServiceImpl method initialize.

@Override
public void initialize() {
    Environment defaultEnvironment = new Environment();
    defaultEnvironment.setId(GraviteeContext.getDefaultEnvironment());
    defaultEnvironment.setName("Default environment");
    defaultEnvironment.setDescription("Default environment");
    defaultEnvironment.setOrganizationId(GraviteeContext.getDefaultOrganization());
    try {
        environmentRepository.create(defaultEnvironment);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to create default environment", ex);
        throw new TechnicalManagementException("An error occurs while trying to create default environment", ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Environment(io.gravitee.repository.management.model.Environment) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 32 with TechnicalManagementException

use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.

the class FetcherServiceImpl method findAll.

@Override
public Set<FetcherEntity> findAll(boolean onlyFilesFetchers) {
    try {
        Set<FetcherPlugin> fetcherDefinitions = super.list();
        if (onlyFilesFetchers) {
            Class<?> filesFetcherClass = FilesFetcher.class;
            fetcherDefinitions = fetcherDefinitions.stream().filter(fetcherPlugin -> filesFetcherClass.isAssignableFrom(fetcherPlugin.fetcher())).collect(Collectors.toSet());
        }
        return fetcherDefinitions.stream().map(fetcherDefinition -> convert(fetcherDefinition, false)).collect(Collectors.toSet());
    } catch (Exception ex) {
        logger.error("An error occurs while trying to list all fetchers", ex);
        throw new TechnicalManagementException("An error occurs while trying to list all fetchers", ex);
    }
}
Also used : FetcherService(io.gravitee.rest.api.service.FetcherService) Component(org.springframework.stereotype.Component) Plugin(io.gravitee.plugin.core.api.Plugin) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) FilesFetcher(io.gravitee.fetcher.api.FilesFetcher) Set(java.util.Set) PluginEntity(io.gravitee.rest.api.model.PluginEntity) FetcherEntity(io.gravitee.rest.api.model.FetcherEntity) Collectors(java.util.stream.Collectors) FetcherPlugin(io.gravitee.plugin.fetcher.FetcherPlugin) FetcherPlugin(io.gravitee.plugin.fetcher.FetcherPlugin) FilesFetcher(io.gravitee.fetcher.api.FilesFetcher) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 33 with TechnicalManagementException

use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.

the class ApiDuplicatorServiceImpl method updateApiReferences.

private void updateApiReferences(ApiEntity createdOrUpdatedApiEntity, JsonNode jsonNode, String organizationId, String environmentId, // FIXME: This whole method should be split in 2 (creation and update) and this flag should be removed
boolean isUpdate) throws JsonProcessingException {
    // Members
    final JsonNode membersToImport = jsonNode.path("members");
    if (membersToImport != null && membersToImport.isArray()) {
        // get current members of the api
        Set<MemberToImport> membersAlreadyPresent = membershipService.getMembersByReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId()).stream().map(member -> {
            UserEntity userEntity = userService.findById(member.getId());
            return new MemberToImport(userEntity.getSource(), userEntity.getSourceId(), member.getRoles().stream().map(RoleEntity::getId).collect(Collectors.toList()), null);
        }).collect(toSet());
        // get the current PO
        RoleEntity poRole = roleService.findPrimaryOwnerRoleByOrganization(organizationId, RoleScope.API);
        if (poRole != null) {
            String poRoleId = poRole.getId();
            MemberToImport currentPo = membersAlreadyPresent.stream().filter(memberToImport -> memberToImport.getRoles().contains(poRoleId)).findFirst().orElse(new MemberToImport());
            List<String> roleUsedInTransfert = null;
            MemberToImport futurePO = null;
            // upsert members
            for (final JsonNode memberNode : membersToImport) {
                MemberToImport memberToImport = objectMapper.readValue(memberNode.toString(), MemberToImport.class);
                String roleToAdd = memberToImport.getRole();
                List<String> rolesToImport = memberToImport.getRoles();
                if (roleToAdd != null && !roleToAdd.isEmpty()) {
                    if (rolesToImport == null) {
                        rolesToImport = new ArrayList<>();
                        memberToImport.setRoles(rolesToImport);
                    }
                    Optional<RoleEntity> optRoleToAddEntity = roleService.findByScopeAndName(RoleScope.API, roleToAdd);
                    if (optRoleToAddEntity.isPresent()) {
                        rolesToImport.add(optRoleToAddEntity.get().getId());
                    } else {
                        LOGGER.warn("Role {} does not exist", roleToAdd);
                    }
                }
                if (rolesToImport != null) {
                    rolesToImport.sort(Comparator.naturalOrder());
                }
                boolean presentWithSameRole = memberToImport.getRoles() != null && !memberToImport.getRoles().isEmpty() && membersAlreadyPresent.stream().anyMatch(m -> {
                    m.getRoles().sort(Comparator.naturalOrder());
                    return (m.getRoles().equals(memberToImport.getRoles()) && (m.getSourceId().equals(memberToImport.getSourceId()) && m.getSource().equals(memberToImport.getSource())));
                });
                // - not the current PO
                if (!presentWithSameRole && (memberToImport.getRoles() != null && !memberToImport.getRoles().isEmpty() && !memberToImport.getRoles().contains(poRoleId)) && !(memberToImport.getSourceId().equals(currentPo.getSourceId()) && memberToImport.getSource().equals(currentPo.getSource()))) {
                    try {
                        UserEntity userEntity = userService.findBySource(memberToImport.getSource(), memberToImport.getSourceId(), false);
                        rolesToImport.forEach(role -> membershipService.addRoleToMemberOnReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId(), MembershipMemberType.USER, userEntity.getId(), role));
                    } catch (UserNotFoundException unfe) {
                    }
                }
                // get the future role of the current PO
                if (currentPo.getSourceId().equals(memberToImport.getSourceId()) && currentPo.getSource().equals(memberToImport.getSource()) && !rolesToImport.contains(poRoleId)) {
                    roleUsedInTransfert = rolesToImport;
                }
                if (rolesToImport.contains(poRoleId)) {
                    futurePO = memberToImport;
                }
            }
            // transfer the ownership
            if (futurePO != null && !(currentPo.getSource().equals(futurePO.getSource()) && currentPo.getSourceId().equals(futurePO.getSourceId()))) {
                try {
                    UserEntity userEntity = userService.findBySource(futurePO.getSource(), futurePO.getSourceId(), false);
                    List<RoleEntity> roleEntity = null;
                    if (roleUsedInTransfert != null && !roleUsedInTransfert.isEmpty()) {
                        roleEntity = roleUsedInTransfert.stream().map(roleService::findById).collect(Collectors.toList());
                    }
                    membershipService.transferApiOwnership(createdOrUpdatedApiEntity.getId(), new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER), roleEntity);
                } catch (UserNotFoundException unfe) {
                }
            }
        }
    }
    if (isUpdate) {
        // Pages
        final JsonNode pagesDefinition = jsonNode.path("pages");
        if (pagesDefinition != null && pagesDefinition.isArray()) {
            List<PageEntity> pagesList = objectMapper.readValue(pagesDefinition.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, PageEntity.class));
            pageService.createOrUpdatePages(pagesList, environmentId, createdOrUpdatedApiEntity.getId());
        }
    }
    // Plans
    final JsonNode plansDefinition = jsonNode.path("plans");
    if (plansDefinition != null && plansDefinition.isArray()) {
        List<PlanEntity> plansList = objectMapper.readValue(plansDefinition.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, PlanEntity.class));
        plansList.forEach(planEntity -> {
            planEntity.setApi(createdOrUpdatedApiEntity.getId());
            planEntity.setId(UuidString.generateForEnvironment(environmentId, createdOrUpdatedApiEntity.getId(), planEntity.getId()));
            planService.createOrUpdatePlan(planEntity, environmentId);
        });
    }
    // Metadata
    final JsonNode metadataDefinition = jsonNode.path("metadata");
    if (metadataDefinition != null && metadataDefinition.isArray()) {
        try {
            for (JsonNode metadataNode : metadataDefinition) {
                UpdateApiMetadataEntity updateApiMetadataEntity = objectMapper.readValue(metadataNode.toString(), UpdateApiMetadataEntity.class);
                updateApiMetadataEntity.setApiId(createdOrUpdatedApiEntity.getId());
                apiMetadataService.update(updateApiMetadataEntity);
            }
        } catch (Exception ex) {
            LOGGER.error("An error occurs while creating API metadata", ex);
            throw new TechnicalManagementException("An error occurs while creating API Metadata", ex);
        }
    }
}
Also used : io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) VirtualHost(io.gravitee.definition.model.VirtualHost) LoggerFactory(org.slf4j.LoggerFactory) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) Proxy(io.gravitee.definition.model.Proxy) Collections.singletonList(java.util.Collections.singletonList) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) Objects.requireNonNull(java.util.Objects.requireNonNull) UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) io.gravitee.rest.api.model(io.gravitee.rest.api.model) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collectors.toSet(java.util.stream.Collectors.toSet) 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) DuplicateApiEntity(io.gravitee.rest.api.model.api.DuplicateApiEntity) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) HttpMethod(io.gravitee.common.http.HttpMethod) DefinitionVersion(io.gravitee.definition.model.DefinitionVersion) Buffer(io.vertx.core.buffer.Buffer) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) ApiSerializer(io.gravitee.rest.api.service.jackson.ser.api.ApiSerializer) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) UuidString(io.gravitee.rest.api.service.common.UuidString) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Collections.singletonList(java.util.Collections.singletonList) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 34 with TechnicalManagementException

use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.

the class ApiDuplicatorServiceImpl method createWithImportedDefinition.

@Override
public ApiEntity createWithImportedDefinition(String apiDefinitionOrURL, String userId, String organizationId, String environmentId) {
    String apiDefinition = fetchApiDefinitionContentFromURL(apiDefinitionOrURL);
    try {
        // Read the whole definition
        final JsonNode jsonNode = objectMapper.readTree(apiDefinition);
        UpdateApiEntity importedApi = convertToEntity(apiDefinition, jsonNode);
        ApiEntity createdApiEntity = apiService.createWithApiDefinition(importedApi, userId, jsonNode);
        createPageAndMedia(createdApiEntity, jsonNode, environmentId);
        updateApiReferences(createdApiEntity, jsonNode, organizationId, environmentId, false);
        return createdApiEntity;
    } catch (JsonProcessingException e) {
        LOGGER.error("An error occurs while trying to JSON deserialize the API {}", apiDefinition, e);
        throw new TechnicalManagementException("An error occurs while trying to JSON deserialize the API definition.");
    }
}
Also used : UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) DuplicateApiEntity(io.gravitee.rest.api.model.api.DuplicateApiEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode) UuidString(io.gravitee.rest.api.service.common.UuidString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 35 with TechnicalManagementException

use of io.gravitee.rest.api.service.exceptions.TechnicalManagementException in project gravitee-management-rest-api by gravitee-io.

the class ApiDuplicatorServiceImpl method updateWithImportedDefinition.

@Override
public ApiEntity updateWithImportedDefinition(String apiId, String apiDefinitionOrURL, String userId, String organizationId, String environmentId) {
    String apiDefinition = fetchApiDefinitionContentFromURL(apiDefinitionOrURL);
    try {
        // Read the whole definition
        final JsonNode jsonNode = objectMapper.readTree(apiDefinition);
        UpdateApiEntity importedApi = convertToEntity(apiDefinition, jsonNode);
        ApiEntity updatedApiEntity = apiService.update(apiId, importedApi, false);
        updateApiReferences(updatedApiEntity, jsonNode, organizationId, environmentId, true);
        return updatedApiEntity;
    } catch (JsonProcessingException e) {
        LOGGER.error("An error occurs while trying to JSON deserialize the API {}", apiDefinition, e);
        throw new TechnicalManagementException("An error occurs while trying to JSON deserialize the API definition.");
    }
}
Also used : UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) DuplicateApiEntity(io.gravitee.rest.api.model.api.DuplicateApiEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode) UuidString(io.gravitee.rest.api.service.common.UuidString) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Aggregations

TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)149 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)120 UuidString (io.gravitee.rest.api.service.common.UuidString)26 Date (java.util.Date)23 Component (org.springframework.stereotype.Component)18 Logger (org.slf4j.Logger)17 LoggerFactory (org.slf4j.LoggerFactory)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)16 Collectors (java.util.stream.Collectors)13 Autowired (org.springframework.beans.factory.annotation.Autowired)13 IOException (java.io.IOException)12 JsonNode (com.fasterxml.jackson.databind.JsonNode)11 Rating (io.gravitee.repository.management.model.Rating)9 ApiRatingUnavailableException (io.gravitee.rest.api.service.exceptions.ApiRatingUnavailableException)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 Dictionary (io.gravitee.repository.management.model.Dictionary)8 AuditService (io.gravitee.rest.api.service.AuditService)8 java.util (java.util)8 Theme (io.gravitee.repository.management.model.Theme)6 List (java.util.List)6