Search in sources :

Example 6 with TechnicalManagementException

use of io.gravitee.management.service.exceptions.TechnicalManagementException 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 7 with TechnicalManagementException

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

the class ApplicationServiceImpl method findById.

@Override
public ApplicationEntity findById(String applicationId) {
    try {
        LOGGER.debug("Find application by ID: {}", applicationId);
        Optional<Application> application = applicationRepository.findById(applicationId);
        if (application.isPresent()) {
            Optional<Membership> primaryOwnerMembership = membershipRepository.findByReferenceAndRole(MembershipReferenceType.APPLICATION, applicationId, RoleScope.APPLICATION, SystemRole.PRIMARY_OWNER.name()).stream().findFirst();
            if (!primaryOwnerMembership.isPresent()) {
                LOGGER.error("The Application {} doesn't have any primary owner.", applicationId);
                throw new TechnicalException("The Application " + applicationId + " doesn't have any primary owner.");
            }
            return convert(application.get(), userService.findById(primaryOwnerMembership.get().getUserId()));
        }
        throw new ApplicationNotFoundException(applicationId);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find an application using its ID {}", applicationId, ex);
        throw new TechnicalManagementException("An error occurs while trying to find an application using its ID " + applicationId, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ApplicationNotFoundException(io.gravitee.management.service.exceptions.ApplicationNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 8 with TechnicalManagementException

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

the class ApplicationServiceImpl method findAll.

@Override
public Set<ApplicationEntity> findAll() {
    try {
        LOGGER.debug("Find all applications");
        final Set<Application> applications = applicationRepository.findAll(ApplicationStatus.ACTIVE);
        if (applications == null || applications.isEmpty()) {
            return emptySet();
        }
        return this.convert(applications);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find all applications", ex);
        throw new TechnicalManagementException("An error occurs while trying to find all applications", ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 9 with TechnicalManagementException

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

the class ApplicationServiceImpl method archive.

@Override
public void archive(String applicationId) {
    try {
        LOGGER.debug("Delete application {}", applicationId);
        Optional<Application> optApplication = applicationRepository.findById(applicationId);
        if (!optApplication.isPresent()) {
            throw new ApplicationNotFoundException(applicationId);
        }
        Application application = optApplication.get();
        Application previousApplication = new Application(application);
        Collection<SubscriptionEntity> subscriptions = subscriptionService.findByApplicationAndPlan(applicationId, null);
        subscriptions.forEach(subscription -> {
            Set<ApiKeyEntity> apiKeys = apiKeyService.findBySubscription(subscription.getId());
            apiKeys.forEach(apiKey -> {
                try {
                    apiKeyService.delete(apiKey.getKey());
                } catch (TechnicalManagementException tme) {
                    LOGGER.error("An error occurs while deleting API Key {}", apiKey.getKey(), tme);
                }
            });
            try {
                subscriptionService.close(subscription.getId());
            } catch (SubscriptionNotClosableException snce) {
                // Subscription can not be closed because it is already closed or not yet accepted
                LOGGER.debug("The subscription can not be closed: {}", snce.getMessage());
            }
        });
        // Archive the application
        application.setUpdatedAt(new Date());
        application.setStatus(ApplicationStatus.ARCHIVED);
        applicationRepository.update(application);
        // Audit
        auditService.createApplicationAuditLog(application.getId(), Collections.emptyMap(), APPLICATION_ARCHIVED, application.getUpdatedAt(), previousApplication, application);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to delete application {}", applicationId, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to delete application %s", applicationId), ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) SubscriptionNotClosableException(io.gravitee.management.service.exceptions.SubscriptionNotClosableException) ApplicationNotFoundException(io.gravitee.management.service.exceptions.ApplicationNotFoundException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 10 with TechnicalManagementException

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

the class EmailServiceImpl method sendEmailNotification.

public void sendEmailNotification(final EmailNotification emailNotification) {
    if (enabled) {
        try {
            final MimeMessageHelper mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, StandardCharsets.UTF_8.name());
            final Template template = freemarkerConfiguration.getTemplate(emailNotification.getTemplate());
            final String content = processTemplateIntoString(template, emailNotification.getParams());
            final String from = isNull(emailNotification.getFrom()) || emailNotification.getFrom().isEmpty() ? defaultFrom : emailNotification.getFrom();
            if (isEmpty(emailNotification.getFromName())) {
                mailMessage.setFrom(from);
            } else {
                mailMessage.setFrom(from, emailNotification.getFromName());
            }
            mailMessage.setTo(emailNotification.getTo());
            if (emailNotification.isCopyToSender() && emailNotification.getFrom() != null) {
                mailMessage.setBcc(emailNotification.getFrom());
            }
            mailMessage.setSubject(format(subject, emailNotification.getSubject()));
            final String html = addResourcesInMessage(mailMessage, content);
            LOGGER.debug("Sending an email to: {}\nSubject: {}\nMessage: {}", emailNotification.getTo(), emailNotification.getSubject(), html);
            mailSender.send(mailMessage.getMimeMessage());
        } catch (final Exception ex) {
            LOGGER.error("Error while sending email notification", ex);
            throw new TechnicalManagementException("Error while sending email notification", ex);
        }
    }
}
Also used : FreeMarkerTemplateUtils.processTemplateIntoString(org.springframework.ui.freemarker.FreeMarkerTemplateUtils.processTemplateIntoString) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) Template(freemarker.template.Template)

Aggregations

TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)90 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)83 Logger (org.slf4j.Logger)17 LoggerFactory (org.slf4j.LoggerFactory)17 Autowired (org.springframework.beans.factory.annotation.Autowired)17 Component (org.springframework.stereotype.Component)17 Collectors (java.util.stream.Collectors)13 java.util (java.util)11 Date (java.util.Date)11 AuditService (io.gravitee.management.service.AuditService)10 IdGenerator (io.gravitee.common.utils.IdGenerator)9 io.gravitee.management.model (io.gravitee.management.model)9 User (io.gravitee.repository.management.model.User)9 ApiRatingUnavailableException (io.gravitee.management.service.exceptions.ApiRatingUnavailableException)8 UserNotFoundException (io.gravitee.management.service.exceptions.UserNotFoundException)8 Metadata (io.gravitee.repository.management.model.Metadata)8 Rating (io.gravitee.repository.management.model.Rating)8 DuplicateMetadataNameException (io.gravitee.management.service.exceptions.DuplicateMetadataNameException)7 ApiService (io.gravitee.management.service.ApiService)6 MetadataService (io.gravitee.management.service.MetadataService)6