Search in sources :

Example 41 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class RoleServiceImpl method create.

@Override
public RoleEntity create(final NewRoleEntity roleEntity) {
    try {
        Role role = convert(roleEntity);
        if (roleRepository.findById(role.getScope(), role.getName()).isPresent()) {
            throw new RoleAlreadyExistsException(role.getScope(), role.getName());
        }
        role.setCreatedAt(new Date());
        role.setUpdatedAt(role.getCreatedAt());
        RoleEntity entity = convert(roleRepository.create(role));
        auditService.createPortalAuditLog(Collections.singletonMap(ROLE, role.getScope() + ":" + role.getName()), ROLE_CREATED, role.getCreatedAt(), null, role);
        if (entity.isDefaultRole()) {
            toggleDefaultRole(convert(roleEntity.getScope()), entity.getName());
        }
        return entity;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to create role {}", roleEntity.getName(), ex);
        throw new TechnicalManagementException("An error occurs while trying to create role " + roleEntity.getName(), ex);
    }
}
Also used : Role(io.gravitee.repository.management.model.Role) UpdateRoleEntity(io.gravitee.management.model.UpdateRoleEntity) NewRoleEntity(io.gravitee.management.model.NewRoleEntity) RoleEntity(io.gravitee.management.model.RoleEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) RoleAlreadyExistsException(io.gravitee.management.service.exceptions.RoleAlreadyExistsException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 42 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class RoleServiceImpl method update.

@Override
public RoleEntity update(final UpdateRoleEntity roleEntity) {
    if (isReserved(roleEntity.getName())) {
        throw new RoleReservedNameException(SystemRole.ADMIN.name());
    }
    RoleScope scope = convert(roleEntity.getScope());
    try {
        Optional<Role> optRole = roleRepository.findById(scope, roleEntity.getName());
        if (!optRole.isPresent()) {
            throw new RoleNotFoundException(scope, roleEntity.getName());
        }
        Role role = optRole.get();
        Role updatedRole = convert(roleEntity);
        updatedRole.setCreatedAt(role.getCreatedAt());
        RoleEntity entity = convert(roleRepository.update(updatedRole));
        auditService.createPortalAuditLog(Collections.singletonMap(ROLE, role.getScope() + ":" + role.getName()), ROLE_UPDATED, updatedRole.getUpdatedAt(), role, updatedRole);
        if (entity.isDefaultRole()) {
            toggleDefaultRole(scope, entity.getName());
        }
        return entity;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update role {}", roleEntity.getName(), ex);
        throw new TechnicalManagementException("An error occurs while trying to update role " + roleEntity.getName(), ex);
    }
}
Also used : Role(io.gravitee.repository.management.model.Role) UpdateRoleEntity(io.gravitee.management.model.UpdateRoleEntity) NewRoleEntity(io.gravitee.management.model.NewRoleEntity) RoleEntity(io.gravitee.management.model.RoleEntity) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) RoleScope(io.gravitee.repository.management.model.RoleScope) RoleReservedNameException(io.gravitee.management.service.exceptions.RoleReservedNameException) RoleNotFoundException(io.gravitee.management.service.exceptions.RoleNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 43 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method create.

@Override
public SubscriptionEntity create(NewSubscriptionEntity newSubscriptionEntity) {
    String plan = newSubscriptionEntity.getPlan();
    String application = newSubscriptionEntity.getApplication();
    try {
        logger.debug("Create a new subscription for plan {} and application {}", plan, application);
        PlanEntity planEntity = planService.findById(plan);
        if (planEntity.getStatus() == PlanStatus.CLOSED) {
            throw new PlanAlreadyClosedException(plan);
        }
        if (planEntity.getStatus() == PlanStatus.STAGING) {
            throw new PlanNotYetPublishedException(plan);
        }
        if (planEntity.getSecurity() == PlanSecurityType.KEY_LESS) {
            throw new PlanNotSubscribableException("A key_less plan is not subscribable !");
        }
        ApplicationEntity applicationEntity = applicationService.findById(application);
        // Check existing subscriptions
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().applications(Collections.singleton(application)).apis(planEntity.getApis()).build());
        if (!subscriptions.isEmpty()) {
            Predicate<Subscription> onlyValidSubs = subscription -> subscription.getStatus() != Subscription.Status.REJECTED && subscription.getStatus() != Subscription.Status.CLOSED;
            // First, check that there is no subscription to the same plan
            long subscriptionCount = subscriptions.stream().filter(onlyValidSubs).filter(subscription -> subscription.getPlan().equals(plan)).count();
            if (subscriptionCount > 0) {
                throw new PlanAlreadySubscribedException(plan);
            }
            // Check that there is no existing subscription based on an OAuth2 or JWT plan
            if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
                long count = subscriptions.stream().filter(onlyValidSubs).map(Subscription::getPlan).distinct().map(plan1 -> planService.findById(plan1)).filter(subPlan -> subPlan.getSecurity() == PlanSecurityType.OAUTH2 || subPlan.getSecurity() == PlanSecurityType.JWT).count();
                if (count > 0) {
                    throw new PlanNotSubscribableException("An other OAuth2 or JWT plan is already subscribed by the same application.");
                }
            }
        }
        if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
            // Check that the application contains a client_id
            if (applicationEntity.getClientId() == null || applicationEntity.getClientId().trim().isEmpty()) {
                throw new PlanNotSubscribableException("A client_id is required to subscribe to an OAuth2 or JWT plan.");
            }
        }
        Subscription subscription = new Subscription();
        subscription.setPlan(plan);
        subscription.setId(UUID.toString(UUID.random()));
        subscription.setApplication(application);
        subscription.setCreatedAt(new Date());
        subscription.setUpdatedAt(subscription.getCreatedAt());
        subscription.setStatus(Subscription.Status.PENDING);
        subscription.setRequest(newSubscriptionEntity.getRequest());
        subscription.setSubscribedBy(getAuthenticatedUser().getUsername());
        subscription.setClientId(applicationEntity.getClientId());
        String apiId = planEntity.getApis().iterator().next();
        subscription.setApi(apiId);
        subscription = subscriptionRepository.create(subscription);
        createAudit(apiId, application, SUBSCRIPTION_CREATED, subscription.getCreatedAt(), null, subscription);
        final ApiModelEntity api = apiService.findByIdForTemplates(apiId);
        final PrimaryOwnerEntity apiOwner = api.getPrimaryOwner();
        // final PrimaryOwnerEntity appOwner = applicationEntity.getPrimaryOwner();
        String portalUrl = environment.getProperty("portalURL");
        String subscriptionsUrl = "";
        if (portalUrl != null) {
            if (portalUrl.endsWith("/")) {
                portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
            }
            subscriptionsUrl = portalUrl + "/#!/management/apis/" + api.getId() + "/subscriptions/" + subscription.getId();
        }
        final Map<String, Object> params = new NotificationParamsBuilder().api(api).plan(planEntity).application(applicationEntity).owner(apiOwner).subscription(convert(subscription)).subscriptionsUrl(subscriptionsUrl).build();
        if (PlanValidationType.AUTO == planEntity.getValidation()) {
            ProcessSubscriptionEntity process = new ProcessSubscriptionEntity();
            process.setId(subscription.getId());
            process.setAccepted(true);
            process.setStartingAt(new Date());
            // Do process
            return process(process, SUBSCRIPTION_SYSTEM_VALIDATOR);
        } else {
            notifierService.trigger(ApiHook.SUBSCRIPTION_NEW, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_NEW, application, params);
            return convert(subscription);
        }
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to subscribe to the plan {}", plan, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to subscribe to the plan %s", plan), ex);
    }
}
Also used : SubscriptionQuery(io.gravitee.management.model.subscription.SubscriptionQuery) java.util(java.util) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Autowired(org.springframework.beans.factory.annotation.Autowired) Subscription(io.gravitee.repository.management.model.Subscription) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) io.gravitee.management.model(io.gravitee.management.model) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) AuditEvent(io.gravitee.repository.management.model.Subscription.AuditEvent) API(io.gravitee.repository.management.model.Audit.AuditProperties.API) APPLICATION(io.gravitee.repository.management.model.Audit.AuditProperties.APPLICATION) Logger(org.slf4j.Logger) Pageable(io.gravitee.management.model.common.Pageable) Metadata(io.gravitee.management.model.pagedresult.Metadata) ApiHook(io.gravitee.management.service.notification.ApiHook) SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) Predicate(java.util.function.Predicate) Audit(io.gravitee.repository.management.model.Audit) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) io.gravitee.management.service(io.gravitee.management.service) ApplicationHook(io.gravitee.management.service.notification.ApplicationHook) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Subscription(io.gravitee.repository.management.model.Subscription)

Example 44 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method process.

@Override
public SubscriptionEntity process(ProcessSubscriptionEntity processSubscription, String userId) {
    try {
        logger.debug("Subscription {} processed by {}", processSubscription.getId(), userId);
        Optional<Subscription> optSubscription = subscriptionRepository.findById(processSubscription.getId());
        if (!optSubscription.isPresent()) {
            throw new SubscriptionNotFoundException(processSubscription.getId());
        }
        Subscription subscription = optSubscription.get();
        Subscription previousSubscription = new Subscription(subscription);
        if (subscription.getStatus() != Subscription.Status.PENDING) {
            throw new SubscriptionAlreadyProcessedException(subscription.getId());
        }
        PlanEntity planEntity = planService.findById(subscription.getPlan());
        if (planEntity.getStatus() == PlanStatus.CLOSED) {
            throw new PlanAlreadyClosedException(planEntity.getId());
        }
        subscription.setProcessedBy(userId);
        subscription.setProcessedAt(new Date());
        if (processSubscription.isAccepted()) {
            subscription.setStatus(Subscription.Status.ACCEPTED);
            subscription.setStartingAt((processSubscription.getStartingAt() != null) ? processSubscription.getStartingAt() : new Date());
            subscription.setEndingAt(processSubscription.getEndingAt());
            subscription.setReason(processSubscription.getReason());
        } else {
            subscription.setStatus(Subscription.Status.REJECTED);
            subscription.setReason(processSubscription.getReason());
            subscription.setClosedAt(new Date());
        }
        subscription = subscriptionRepository.update(subscription);
        final ApplicationEntity application = applicationService.findById(subscription.getApplication());
        final PlanEntity plan = planService.findById(subscription.getPlan());
        final String apiId = plan.getApis().iterator().next();
        final ApiModelEntity api = apiService.findByIdForTemplates(apiId);
        final PrimaryOwnerEntity owner = application.getPrimaryOwner();
        createAudit(apiId, subscription.getApplication(), SUBSCRIPTION_UPDATED, subscription.getUpdatedAt(), previousSubscription, subscription);
        SubscriptionEntity subscriptionEntity = convert(subscription);
        final Map<String, Object> params = new NotificationParamsBuilder().owner(owner).application(application).api(api).plan(plan).subscription(subscriptionEntity).build();
        if (subscription.getStatus() == Subscription.Status.ACCEPTED) {
            notifierService.trigger(ApiHook.SUBSCRIPTION_ACCEPTED, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_ACCEPTED, application.getId(), params);
        } else {
            notifierService.trigger(ApiHook.SUBSCRIPTION_REJECTED, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_REJECTED, application.getId(), params);
        }
        if (plan.getSecurity() == PlanSecurityType.API_KEY && subscription.getStatus() == Subscription.Status.ACCEPTED) {
            apiKeyService.generate(subscription.getId());
        }
        return subscriptionEntity;
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to process subscription {} by {}", processSubscription.getId(), userId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to process subscription %s by %s", processSubscription.getId(), userId), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Subscription(io.gravitee.repository.management.model.Subscription)

Example 45 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method update.

@Override
public SubscriptionEntity update(UpdateSubscriptionEntity updateSubscription, String clientId) {
    try {
        logger.debug("Update subscription {}", updateSubscription.getId());
        Optional<Subscription> optSubscription = subscriptionRepository.findById(updateSubscription.getId());
        if (!optSubscription.isPresent()) {
            throw new SubscriptionNotFoundException(updateSubscription.getId());
        }
        Subscription subscription = optSubscription.get();
        if (subscription.getStatus() == Subscription.Status.ACCEPTED) {
            Subscription previousSubscription = new Subscription(subscription);
            subscription.setUpdatedAt(new Date());
            subscription.setStartingAt(updateSubscription.getStartingAt());
            subscription.setEndingAt(updateSubscription.getEndingAt());
            if (clientId != null) {
                subscription.setClientId(clientId);
            }
            subscription = subscriptionRepository.update(subscription);
            final PlanEntity plan = planService.findById(subscription.getPlan());
            createAudit(plan.getApis().iterator().next(), subscription.getApplication(), SUBSCRIPTION_UPDATED, subscription.getUpdatedAt(), previousSubscription, subscription);
            // Update the expiration date for not yet revoked api-keys relative to this subscription
            Date endingAt = subscription.getEndingAt();
            if (plan.getSecurity() == PlanSecurityType.API_KEY && endingAt != null) {
                Set<ApiKeyEntity> apiKeys = apiKeyService.findBySubscription(subscription.getId());
                Date now = new Date();
                for (ApiKeyEntity apiKey : apiKeys) {
                    Date expireAt = apiKey.getExpireAt();
                    if (!apiKey.isRevoked() && (expireAt == null || expireAt.equals(now) || expireAt.before(now))) {
                        apiKey.setExpireAt(endingAt);
                        apiKeyService.update(apiKey);
                    }
                }
            }
            return convert(subscription);
        }
        throw new SubscriptionNotUpdatableException(updateSubscription.getId());
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to update subscription {}", updateSubscription.getId(), ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to update subscription %s", updateSubscription.getId()), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Subscription(io.gravitee.repository.management.model.Subscription)

Aggregations

TechnicalException (io.gravitee.repository.exceptions.TechnicalException)102 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)80 Logger (org.slf4j.Logger)22 LoggerFactory (org.slf4j.LoggerFactory)22 Autowired (org.springframework.beans.factory.annotation.Autowired)22 Component (org.springframework.stereotype.Component)20 java.util (java.util)18 Collectors (java.util.stream.Collectors)18 io.gravitee.management.model (io.gravitee.management.model)16 AuditService (io.gravitee.management.service.AuditService)12 UUID (io.gravitee.common.utils.UUID)11 Date (java.util.Date)11 IdGenerator (io.gravitee.common.utils.IdGenerator)9 IOException (java.io.IOException)9 io.gravitee.management.service (io.gravitee.management.service)8 ApiRatingUnavailableException (io.gravitee.management.service.exceptions.ApiRatingUnavailableException)8 Metadata (io.gravitee.repository.management.model.Metadata)8 Rating (io.gravitee.repository.management.model.Rating)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7