Search in sources :

Example 61 with TechnicalManagementException

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

the class ApiKeyServiceImpl method renew.

@Override
public ApiKeyEntity renew(String subscription) {
    try {
        LOGGER.debug("Renew API Key for subscription {}", subscription);
        ApiKey newApiKey = generateForSubscription(subscription);
        newApiKey = apiKeyRepository.create(newApiKey);
        Instant expirationInst = newApiKey.getCreatedAt().toInstant().plus(Duration.ofHours(2));
        Date expirationDate = Date.from(expirationInst);
        // Previously generated keys should be set as revoked
        // Get previously generated keys to set their expiration date
        Set<ApiKey> oldKeys = apiKeyRepository.findBySubscription(subscription);
        for (ApiKey oldKey : oldKeys) {
            if (!oldKey.equals(newApiKey)) {
                setExpiration(expirationDate, oldKey);
            }
        }
        // TODO: Send a notification to the application owner
        // Audit
        final PlanEntity plan = planService.findById(newApiKey.getPlan());
        auditService.createApiAuditLog(plan.getApis().iterator().next(), Collections.singletonMap(API_KEY, newApiKey.getKey()), APIKEY_RENEWED, newApiKey.getCreatedAt(), null, newApiKey);
        return convert(newApiKey);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to renew an API Key for {}", subscription, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to renew an API Key for %s", subscription), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Instant(java.time.Instant) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 62 with TechnicalManagementException

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

the class ApiMetadataServiceImpl method findAllByApi.

@Override
public List<ApiMetadataEntity> findAllByApi(final String apiId) {
    try {
        LOGGER.debug("Find all metadata by api ID {}", apiId);
        final List<MetadataEntity> defaultMetadata = metadataService.findAllDefault();
        final List<String> defaultMetadataKeys = defaultMetadata.stream().map(MetadataEntity::getKey).collect(toList());
        final List<Metadata> apiMetadata = metadataRepository.findByReferenceTypeAndReferenceId(MetadataReferenceType.API, apiId);
        final List<ApiMetadataEntity> allMetadata = new ArrayList<>();
        allMetadata.addAll(defaultMetadata.stream().map(metadata -> {
            final Optional<Metadata> optApiMetadata = apiMetadata.stream().filter(metadataEntity -> metadata.getKey().equals(metadataEntity.getKey())).findAny();
            return convert(optApiMetadata, metadata, null);
        }).collect(toList()));
        allMetadata.addAll(apiMetadata.stream().filter(metadata -> !defaultMetadataKeys.contains(metadata.getKey())).map(metadata -> convert(metadata, apiId)).collect(toList()));
        return allMetadata;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurred while trying to find all metadata by API", ex);
        throw new TechnicalManagementException("An error occurred while trying to find all metadata by API", ex);
    }
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) ApiService(io.gravitee.management.service.ApiService) DuplicateMetadataNameException(io.gravitee.management.service.exceptions.DuplicateMetadataNameException) ApiMetadataService(io.gravitee.management.service.ApiMetadataService) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) Autowired(org.springframework.beans.factory.annotation.Autowired) AuditService(io.gravitee.management.service.AuditService) MetadataRepository(io.gravitee.repository.management.api.MetadataRepository) ApiMetadataNotFoundException(io.gravitee.management.service.exceptions.ApiMetadataNotFoundException) METADATA_UPDATED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_UPDATED) MetadataService(io.gravitee.management.service.MetadataService) IdGenerator(io.gravitee.common.utils.IdGenerator) Component(org.springframework.stereotype.Component) Collectors.toList(java.util.stream.Collectors.toList) METADATA_DELETED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_DELETED) Metadata(io.gravitee.repository.management.model.Metadata) io.gravitee.management.model(io.gravitee.management.model) METADATA_CREATED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_CREATED) MetadataReferenceType(io.gravitee.repository.management.model.MetadataReferenceType) METADATA(io.gravitee.repository.management.model.Audit.AuditProperties.METADATA) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Metadata(io.gravitee.repository.management.model.Metadata) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 63 with TechnicalManagementException

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

the class ApiMetadataServiceImpl method create.

@Override
public ApiMetadataEntity create(final NewApiMetadataEntity metadataEntity) {
    final ApiEntity apiEntity = apiService.findById(metadataEntity.getApiId());
    // if no format defined, we just set String format
    if (metadataEntity.getFormat() == null) {
        metadataEntity.setFormat(MetadataFormat.STRING);
    }
    // First we prevent the duplicate metadata name
    final Optional<ApiMetadataEntity> optionalMetadata = findAllByApi(apiEntity.getId()).stream().filter(metadata -> metadataEntity.getName().equalsIgnoreCase(metadata.getName())).findAny();
    if (optionalMetadata.isPresent()) {
        throw new DuplicateMetadataNameException(optionalMetadata.get().getName());
    }
    metadataService.checkMetadataFormat(metadataEntity.getFormat(), metadataEntity.getValue());
    try {
        final Metadata metadata = convertForAPI(metadataEntity);
        final Date now = new Date();
        metadata.setCreatedAt(now);
        metadata.setUpdatedAt(now);
        metadataRepository.create(metadata);
        // Audit
        auditService.createApiAuditLog(apiEntity.getId(), Collections.singletonMap(METADATA, metadata.getKey()), METADATA_CREATED, metadata.getCreatedAt(), null, metadata);
        return convert(metadata, metadataEntity.getApiId());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurred while trying to create metadata {} on API {}", metadataEntity.getName(), metadataEntity.getApiId(), ex);
        throw new TechnicalManagementException("An error occurred while trying to create metadata " + metadataEntity.getName() + " on API " + metadataEntity.getApiId(), ex);
    }
}
Also used : java.util(java.util) Logger(org.slf4j.Logger) ApiService(io.gravitee.management.service.ApiService) DuplicateMetadataNameException(io.gravitee.management.service.exceptions.DuplicateMetadataNameException) ApiMetadataService(io.gravitee.management.service.ApiMetadataService) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException) Autowired(org.springframework.beans.factory.annotation.Autowired) AuditService(io.gravitee.management.service.AuditService) MetadataRepository(io.gravitee.repository.management.api.MetadataRepository) ApiMetadataNotFoundException(io.gravitee.management.service.exceptions.ApiMetadataNotFoundException) METADATA_UPDATED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_UPDATED) MetadataService(io.gravitee.management.service.MetadataService) IdGenerator(io.gravitee.common.utils.IdGenerator) Component(org.springframework.stereotype.Component) Collectors.toList(java.util.stream.Collectors.toList) METADATA_DELETED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_DELETED) Metadata(io.gravitee.repository.management.model.Metadata) io.gravitee.management.model(io.gravitee.management.model) METADATA_CREATED(io.gravitee.repository.management.model.Metadata.AuditEvent.METADATA_CREATED) MetadataReferenceType(io.gravitee.repository.management.model.MetadataReferenceType) METADATA(io.gravitee.repository.management.model.Audit.AuditProperties.METADATA) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) DuplicateMetadataNameException(io.gravitee.management.service.exceptions.DuplicateMetadataNameException) Metadata(io.gravitee.repository.management.model.Metadata) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 64 with TechnicalManagementException

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

the class ApplicationServiceImpl method findByUser.

@Override
public Set<ApplicationEntity> findByUser(String username) {
    try {
        LOGGER.debug("Find applications for user {}", username);
        // find applications where the user is a member
        List<String> appIds = membershipRepository.findByUserAndReferenceType(username, MembershipReferenceType.APPLICATION).stream().map(Membership::getReferenceId).collect(Collectors.toList());
        final Set<Application> applications = applicationRepository.findByIds(appIds).stream().filter(app -> ApplicationStatus.ACTIVE.equals(app.getStatus())).collect(Collectors.toSet());
        // find applications which be part of the same group as the user
        List<String> groupIds = membershipRepository.findByUserAndReferenceType(username, MembershipReferenceType.GROUP).stream().filter(m -> m.getRoles().keySet().contains(RoleScope.APPLICATION.getId())).map(Membership::getReferenceId).collect(Collectors.toList());
        applications.addAll(applicationRepository.findByGroups(groupIds, ApplicationStatus.ACTIVE));
        if (applications.isEmpty()) {
            return emptySet();
        }
        return this.convert(applications);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find applications for user {}", username, ex);
        throw new TechnicalManagementException("An error occurs while trying to find applications for user " + username, 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) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 65 with TechnicalManagementException

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

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