Search in sources :

Example 1 with ClientIdAlreadyExistsException

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

the class ApplicationServiceImpl method update.

@Override
public ApplicationEntity update(String applicationId, UpdateApplicationEntity updateApplicationEntity) {
    try {
        LOGGER.debug("Update application {}", applicationId);
        if (updateApplicationEntity.getGroups() != null && !updateApplicationEntity.getGroups().isEmpty()) {
            // throw a NotFoundException if the group doesn't exist
            groupService.findByIds(updateApplicationEntity.getGroups());
        }
        Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
        if (!optApplicationToUpdate.isPresent()) {
            throw new ApplicationNotFoundException(applicationId);
        }
        // If clientId is set, check for uniqueness
        String clientId = updateApplicationEntity.getClientId();
        if (clientId != null && !clientId.trim().isEmpty()) {
            LOGGER.debug("Check that client_id is unique among all applications");
            final Set<Application> applications = applicationRepository.findAll(ApplicationStatus.ACTIVE);
            final Optional<Application> byClientId = applications.stream().filter(application -> clientId.equals(application.getClientId())).findAny();
            if (byClientId.isPresent() && !byClientId.get().getId().equals(optApplicationToUpdate.get().getId())) {
                LOGGER.error("An application already exists with the same client_id");
                throw new ClientIdAlreadyExistsException(clientId);
            }
        }
        Application application = convert(updateApplicationEntity);
        application.setId(applicationId);
        application.setStatus(ApplicationStatus.ACTIVE);
        application.setCreatedAt(optApplicationToUpdate.get().getCreatedAt());
        application.setUpdatedAt(new Date());
        Application updatedApplication = applicationRepository.update(application);
        // Audit
        auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_CREATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
        // Set correct client_id for all subscriptions
        SubscriptionQuery subQuery = new SubscriptionQuery();
        subQuery.setApplication(applicationId);
        subQuery.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED));
        subscriptionService.search(subQuery).forEach(new Consumer<SubscriptionEntity>() {

            @Override
            public void accept(SubscriptionEntity subscriptionEntity) {
                UpdateSubscriptionEntity updateSubscriptionEntity = new UpdateSubscriptionEntity();
                updateSubscriptionEntity.setId(subscriptionEntity.getId());
                updateSubscriptionEntity.setStartingAt(subscriptionEntity.getStartingAt());
                updateSubscriptionEntity.setEndingAt(subscriptionEntity.getEndingAt());
                subscriptionService.update(updateSubscriptionEntity, application.getClientId());
            }
        });
        return convert(Collections.singleton(updatedApplication)).iterator().next();
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update application {}", applicationId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to update application %s", applicationId), ex);
    }
}
Also used : SubscriptionQuery(io.gravitee.management.model.subscription.SubscriptionQuery) 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) UUID(io.gravitee.common.utils.UUID) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) ApplicationRepository(io.gravitee.repository.management.api.ApplicationRepository) Collections.singletonMap(java.util.Collections.singletonMap) ApplicationNotFoundException(io.gravitee.management.service.exceptions.ApplicationNotFoundException) APPLICATION_CREATED(io.gravitee.repository.management.model.Application.AuditEvent.APPLICATION_CREATED) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) SubscriptionNotClosableException(io.gravitee.management.service.exceptions.SubscriptionNotClosableException) Collectors(java.util.stream.Collectors) APPLICATION_ARCHIVED(io.gravitee.repository.management.model.Application.AuditEvent.APPLICATION_ARCHIVED) Consumer(java.util.function.Consumer) ClientIdAlreadyExistsException(io.gravitee.management.service.exceptions.ClientIdAlreadyExistsException) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) ApplicationHook(io.gravitee.management.service.notification.ApplicationHook) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) SubscriptionQuery(io.gravitee.management.model.subscription.SubscriptionQuery) ClientIdAlreadyExistsException(io.gravitee.management.service.exceptions.ClientIdAlreadyExistsException) ApplicationNotFoundException(io.gravitee.management.service.exceptions.ApplicationNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 2 with ClientIdAlreadyExistsException

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

the class ApplicationServiceImpl method create.

@Override
public ApplicationEntity create(NewApplicationEntity newApplicationEntity, String userId) {
    try {
        LOGGER.debug("Create {} for user {}", newApplicationEntity, userId);
        // If clientId is set, check for uniqueness
        String clientId = newApplicationEntity.getClientId();
        if (clientId != null && !clientId.trim().isEmpty()) {
            LOGGER.debug("Check that client_id is unique among all applications");
            final Set<Application> applications = applicationRepository.findAll(ApplicationStatus.ACTIVE);
            final boolean alreadyExistingApp = applications.stream().anyMatch(application -> clientId.equals(application.getClientId()));
            if (alreadyExistingApp) {
                LOGGER.error("An application already exists with the same client_id");
                throw new ClientIdAlreadyExistsException(clientId);
            }
        }
        if (newApplicationEntity.getGroups() != null && !newApplicationEntity.getGroups().isEmpty()) {
            // throw a NotFoundException if the group doesn't exist
            groupService.findByIds(newApplicationEntity.getGroups());
        }
        Application application = convert(newApplicationEntity);
        application.setId(UUID.toString(UUID.random()));
        application.setStatus(ApplicationStatus.ACTIVE);
        // Add Default groups
        Set<String> defaultGroups = groupService.findByEvent(GroupEvent.APPLICATION_CREATE).stream().map(GroupEntity::getId).collect(Collectors.toSet());
        if (!defaultGroups.isEmpty() && application.getGroups() == null) {
            application.setGroups(defaultGroups);
        } else if (!defaultGroups.isEmpty()) {
            application.getGroups().addAll(defaultGroups);
        }
        // Set date fields
        application.setCreatedAt(new Date());
        application.setUpdatedAt(application.getCreatedAt());
        Application createdApplication = applicationRepository.create(application);
        // Audit
        auditService.createApplicationAuditLog(createdApplication.getId(), Collections.emptyMap(), APPLICATION_CREATED, isAuthenticated() ? getAuthenticatedUsername() : userId, createdApplication.getCreatedAt(), null, createdApplication);
        // Add the primary owner of the newly created API
        Membership membership = new Membership(userId, createdApplication.getId(), MembershipReferenceType.APPLICATION);
        membership.setRoles(singletonMap(RoleScope.APPLICATION.getId(), SystemRole.PRIMARY_OWNER.name()));
        membership.setCreatedAt(application.getCreatedAt());
        membership.setUpdatedAt(application.getCreatedAt());
        membershipRepository.create(membership);
        // create the default mail notification
        UserEntity userEntity = userService.findById(userId);
        if (userEntity.getEmail() != null && !userEntity.getEmail().isEmpty()) {
            GenericNotificationConfigEntity notificationConfigEntity = new GenericNotificationConfigEntity();
            notificationConfigEntity.setName("Default Mail Notifications");
            notificationConfigEntity.setReferenceType(HookScope.APPLICATION.name());
            notificationConfigEntity.setReferenceId(createdApplication.getId());
            notificationConfigEntity.setHooks(Arrays.stream(ApplicationHook.values()).map(Enum::name).collect(Collectors.toList()));
            notificationConfigEntity.setNotifier(NotifierServiceImpl.DEFAULT_EMAIL_NOTIFIER_ID);
            notificationConfigEntity.setConfig(userEntity.getEmail());
            genericNotificationConfigService.create(notificationConfigEntity);
        }
        // TODO add membership log
        return convert(createdApplication, userEntity);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to create {} for user {}", newApplicationEntity, userId, ex);
        throw new TechnicalManagementException("An error occurs while trying create " + newApplicationEntity + " for user " + userId, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) ClientIdAlreadyExistsException(io.gravitee.management.service.exceptions.ClientIdAlreadyExistsException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Aggregations

GenericNotificationConfigEntity (io.gravitee.management.model.notification.GenericNotificationConfigEntity)2 ClientIdAlreadyExistsException (io.gravitee.management.service.exceptions.ClientIdAlreadyExistsException)2 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)2 UUID (io.gravitee.common.utils.UUID)1 io.gravitee.management.model (io.gravitee.management.model)1 SystemRole (io.gravitee.management.model.permissions.SystemRole)1 SubscriptionQuery (io.gravitee.management.model.subscription.SubscriptionQuery)1 io.gravitee.management.service (io.gravitee.management.service)1 ApplicationNotFoundException (io.gravitee.management.service.exceptions.ApplicationNotFoundException)1 SubscriptionNotClosableException (io.gravitee.management.service.exceptions.SubscriptionNotClosableException)1 ApplicationHook (io.gravitee.management.service.notification.ApplicationHook)1 HookScope (io.gravitee.management.service.notification.HookScope)1 ApplicationRepository (io.gravitee.repository.management.api.ApplicationRepository)1 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 io.gravitee.repository.management.model (io.gravitee.repository.management.model)1 APPLICATION_ARCHIVED (io.gravitee.repository.management.model.Application.AuditEvent.APPLICATION_ARCHIVED)1 APPLICATION_CREATED (io.gravitee.repository.management.model.Application.AuditEvent.APPLICATION_CREATED)1 java.util (java.util)1 Collections.emptySet (java.util.Collections.emptySet)1