Search in sources :

Example 6 with TechnicalException

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

the class ApiServiceImpl method convert.

private Set<ApiEntity> convert(Set<Api> apis, boolean readDefinition) throws TechnicalException {
    if (apis == null || apis.isEmpty()) {
        return Collections.emptySet();
    }
    // find primary owners usernames of each apis
    Set<Membership> memberships = membershipRepository.findByReferencesAndRole(MembershipReferenceType.API, apis.stream().map(Api::getId).collect(Collectors.toList()), RoleScope.API, SystemRole.PRIMARY_OWNER.name());
    int poMissing = apis.size() - memberships.size();
    if (poMissing > 0) {
        Set<String> apiIds = apis.stream().map(Api::getId).collect(Collectors.toSet());
        Set<String> apiMembershipsIds = memberships.stream().map(Membership::getReferenceId).collect(Collectors.toSet());
        apiIds.removeAll(apiMembershipsIds);
        Optional<String> optionalApisAsString = apiIds.stream().reduce((a, b) -> a + " / " + b);
        String apisAsString = "?";
        if (optionalApisAsString.isPresent())
            apisAsString = optionalApisAsString.get();
        LOGGER.error("{} apis has no identified primary owners in this list {}.", poMissing, apisAsString);
        throw new TechnicalManagementException(poMissing + " apis has no identified primary owners in this list " + apisAsString + ".");
    }
    Map<String, String> apiToUser = new HashMap<>(memberships.size());
    memberships.forEach(membership -> apiToUser.put(membership.getReferenceId(), membership.getUserId()));
    Map<String, UserEntity> userIdToUserEntity = new HashMap<>(memberships.size());
    userService.findByIds(memberships.stream().map(Membership::getUserId).collect(Collectors.toList())).forEach(userEntity -> userIdToUserEntity.put(userEntity.getId(), userEntity));
    return apis.stream().map(publicApi -> this.convert(publicApi, userIdToUserEntity.get(apiToUser.get(publicApi.getId())), readDefinition)).collect(Collectors.toSet());
}
Also used : PlanQuery(io.gravitee.management.model.plan.PlanQuery) 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) PageQuery(io.gravitee.management.model.documentation.PageQuery) Visibility(io.gravitee.repository.management.model.Visibility) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Proxy(io.gravitee.definition.model.Proxy) Value(org.springframework.beans.factory.annotation.Value) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) EventType(io.gravitee.management.model.EventType) ApiSynchronizationProcessor(io.gravitee.management.service.processor.ApiSynchronizationProcessor) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) ApiRepository(io.gravitee.repository.management.api.ApiRepository) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) Lifecycle(io.gravitee.common.component.Lifecycle) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) Logger(org.slf4j.Logger) ApiHook(io.gravitee.management.service.notification.ApiHook) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) Path(io.gravitee.definition.model.Path) PageType(io.gravitee.management.model.PageType) DatatypeConverter(javax.xml.bind.DatatypeConverter) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint)

Example 7 with TechnicalException

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

the class ApiServiceImpl method checkContextPath.

private void checkContextPath(String newContextPath, final String apiId) throws TechnicalException {
    if (newContextPath.charAt(newContextPath.length() - 1) == '/') {
        newContextPath = newContextPath.substring(0, newContextPath.length() - 1);
    }
    final int indexOfEndOfNewSubContextPath = newContextPath.lastIndexOf('/', 1);
    final String newSubContextPath = newContextPath.substring(0, indexOfEndOfNewSubContextPath <= 0 ? newContextPath.length() : indexOfEndOfNewSubContextPath) + '/';
    final boolean contextPathExists = apiRepository.findAll().stream().filter(api -> !api.getId().equals(apiId)).anyMatch(api -> {
        final String contextPath = convert(api, null, true).getProxy().getContextPath();
        final int indexOfEndOfSubContextPath = contextPath.lastIndexOf('/', 1);
        final String subContextPath = contextPath.substring(0, indexOfEndOfSubContextPath <= 0 ? contextPath.length() : indexOfEndOfSubContextPath) + '/';
        return subContextPath.startsWith(newSubContextPath) || newSubContextPath.startsWith(subContextPath);
    });
    if (contextPathExists) {
        throw new ApiContextPathAlreadyExistsException(newSubContextPath);
    }
}
Also used : PlanQuery(io.gravitee.management.model.plan.PlanQuery) 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) PageQuery(io.gravitee.management.model.documentation.PageQuery) Visibility(io.gravitee.repository.management.model.Visibility) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Proxy(io.gravitee.definition.model.Proxy) Value(org.springframework.beans.factory.annotation.Value) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) EventType(io.gravitee.management.model.EventType) ApiSynchronizationProcessor(io.gravitee.management.service.processor.ApiSynchronizationProcessor) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) ApiRepository(io.gravitee.repository.management.api.ApiRepository) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) Lifecycle(io.gravitee.common.component.Lifecycle) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) Logger(org.slf4j.Logger) ApiHook(io.gravitee.management.service.notification.ApiHook) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) Path(io.gravitee.definition.model.Path) PageType(io.gravitee.management.model.PageType) DatatypeConverter(javax.xml.bind.DatatypeConverter) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint)

Example 8 with TechnicalException

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

the class ApiServiceImpl method deployLastPublishedAPI.

private ApiEntity deployLastPublishedAPI(String apiId, String userId, EventType eventType) throws TechnicalException {
    Set<EventEntity> events = eventService.findByApi(apiId);
    Optional<EventEntity> optEvent = events.stream().filter(event -> EventType.PUBLISH_API.equals(event.getType())).sorted((e1, e2) -> e2.getCreatedAt().compareTo(e1.getCreatedAt())).findFirst();
    try {
        if (optEvent.isPresent()) {
            EventEntity event = optEvent.get();
            JsonNode node = objectMapper.readTree(event.getPayload());
            Api lastPublishedAPI = objectMapper.convertValue(node, Api.class);
            lastPublishedAPI.setLifecycleState(convert(eventType));
            lastPublishedAPI.setUpdatedAt(new Date());
            lastPublishedAPI.setDeployedAt(new Date());
            Map<String, String> properties = new HashMap<>();
            properties.put(Event.EventProperties.API_ID.getValue(), lastPublishedAPI.getId());
            properties.put(Event.EventProperties.USER.getValue(), userId);
            // Clear useless field for history
            lastPublishedAPI.setPicture(null);
            // And create event
            eventService.create(eventType, objectMapper.writeValueAsString(lastPublishedAPI), properties);
            return convert(Collections.singleton(lastPublishedAPI), true).iterator().next();
        } else {
            if (events.size() == 0) {
                // this is the first time we start the api without previously deployed id.
                // let's do it.
                this.deploy(apiId, userId, EventType.PUBLISH_API);
                return deployLastPublishedAPI(apiId, userId, eventType);
            }
            throw new TechnicalException("No event found for API " + apiId);
        }
    } catch (Exception e) {
        LOGGER.error("An error occurs while trying to deploy last published API {}", apiId, e);
        throw new TechnicalException("An error occurs while trying to deploy last published API " + apiId, e);
    }
}
Also used : PlanQuery(io.gravitee.management.model.plan.PlanQuery) 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) PageQuery(io.gravitee.management.model.documentation.PageQuery) Visibility(io.gravitee.repository.management.model.Visibility) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Proxy(io.gravitee.definition.model.Proxy) Value(org.springframework.beans.factory.annotation.Value) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) EventType(io.gravitee.management.model.EventType) ApiSynchronizationProcessor(io.gravitee.management.service.processor.ApiSynchronizationProcessor) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) ApiRepository(io.gravitee.repository.management.api.ApiRepository) io.gravitee.management.model(io.gravitee.management.model) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity) SystemRole(io.gravitee.management.model.permissions.SystemRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) Lifecycle(io.gravitee.common.component.Lifecycle) SearchableUser(io.gravitee.management.idp.api.identity.SearchableUser) Logger(org.slf4j.Logger) ApiHook(io.gravitee.management.service.notification.ApiHook) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) Component(org.springframework.stereotype.Component) io.gravitee.repository.management.model(io.gravitee.repository.management.model) io.gravitee.management.service(io.gravitee.management.service) Path(io.gravitee.definition.model.Path) PageType(io.gravitee.management.model.PageType) DatatypeConverter(javax.xml.bind.DatatypeConverter) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) JsonNode(com.fasterxml.jackson.databind.JsonNode) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 9 with TechnicalException

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

the class ApiServiceImpl method create0.

private ApiEntity create0(UpdateApiEntity api, String userId) throws ApiAlreadyExistsException {
    try {
        LOGGER.debug("Create {} for user {}", api, userId);
        String id = UUID.toString(UUID.random());
        Optional<Api> checkApi = apiRepository.findById(id);
        if (checkApi.isPresent()) {
            throw new ApiAlreadyExistsException(id);
        }
        // Format context-path and check if context path is unique
        checkContextPath(api.getProxy().getContextPath());
        Api repoApi = convert(id, api);
        if (repoApi != null) {
            repoApi.setId(id);
            // Set date fields
            repoApi.setCreatedAt(new Date());
            repoApi.setUpdatedAt(repoApi.getCreatedAt());
            // Be sure that lifecycle is set to STOPPED by default and visibility is private
            repoApi.setLifecycleState(LifecycleState.STOPPED);
            repoApi.setVisibility(Visibility.PRIVATE);
            // Add Default groups
            Set<String> defaultGroups = groupService.findByEvent(GroupEvent.API_CREATE).stream().map(GroupEntity::getId).collect(Collectors.toSet());
            if (!defaultGroups.isEmpty() && repoApi.getGroups() == null) {
                repoApi.setGroups(defaultGroups);
            } else if (!defaultGroups.isEmpty()) {
                repoApi.getGroups().addAll(defaultGroups);
            }
            Api createdApi = apiRepository.create(repoApi);
            // Audit
            auditService.createApiAuditLog(createdApi.getId(), Collections.emptyMap(), API_CREATED, createdApi.getCreatedAt(), null, createdApi);
            // Add the primary owner of the newly created API
            UserEntity primaryOwner = userService.findById(userId);
            Membership membership = new Membership(primaryOwner.getId(), createdApi.getId(), MembershipReferenceType.API);
            membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
            membership.setCreatedAt(repoApi.getCreatedAt());
            membership.setUpdatedAt(repoApi.getCreatedAt());
            membershipRepository.create(membership);
            // create the default mail notification
            if (primaryOwner.getEmail() != null && !primaryOwner.getEmail().isEmpty()) {
                GenericNotificationConfigEntity notificationConfigEntity = new GenericNotificationConfigEntity();
                notificationConfigEntity.setName("Default Mail Notifications");
                notificationConfigEntity.setReferenceType(HookScope.API.name());
                notificationConfigEntity.setReferenceId(createdApi.getId());
                notificationConfigEntity.setHooks(Arrays.stream(ApiHook.values()).map(Enum::name).collect(Collectors.toList()));
                notificationConfigEntity.setNotifier(NotifierServiceImpl.DEFAULT_EMAIL_NOTIFIER_ID);
                notificationConfigEntity.setConfig(primaryOwner.getEmail());
                genericNotificationConfigService.create(notificationConfigEntity);
            }
            // TODO add membership log
            return convert(createdApi, primaryOwner, true);
        } else {
            LOGGER.error("Unable to create API {} because of previous error.");
            throw new TechnicalManagementException("Unable to create API " + id);
        }
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to create {} for user {}", api, userId, ex);
        throw new TechnicalManagementException("An error occurs while trying create " + api + " for user " + userId, ex);
    }
}
Also used : TechnicalException(io.gravitee.repository.exceptions.TechnicalException) GenericNotificationConfigEntity(io.gravitee.management.model.notification.GenericNotificationConfigEntity)

Example 10 with TechnicalException

use of io.gravitee.repository.exceptions.TechnicalException 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)

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