Search in sources :

Example 21 with ApplicationListItem

use of io.gravitee.rest.api.model.application.ApplicationListItem in project gravitee-management-rest-api by gravitee-io.

the class ApiServiceImpl method findApisByUser.

private List<Api> findApisByUser(String userId, ApiQuery apiQuery, boolean portal) {
    // get all public apis
    List<Api> publicApis;
    if (portal) {
        publicApis = apiRepository.search(queryToCriteria(apiQuery).visibility(PUBLIC).build());
    } else {
        publicApis = emptyList();
    }
    List<Api> userApis = emptyList();
    List<Api> groupApis = emptyList();
    List<Api> subscribedApis = emptyList();
    // for others API, user must be authenticated
    if (userId != null) {
        // get user apis
        final String[] userApiIds = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.API).stream().map(MembershipEntity::getReferenceId).filter(apiId -> {
            if (apiQuery != null && !CollectionUtils.isEmpty(apiQuery.getIds())) {
                // We already have api ids to focus on.
                return apiQuery.getIds().contains(apiId);
            } else {
                return true;
            }
        }).toArray(String[]::new);
        if (userApiIds.length > 0) {
            userApis = apiRepository.search(queryToCriteria(apiQuery).ids(userApiIds).build());
        }
        // get user groups apis
        final String[] groupIds = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.GROUP).stream().filter(m -> {
            final RoleEntity roleInGroup = roleService.findById(m.getRoleId());
            if (!portal) {
                return (m.getRoleId() != null && roleInGroup.getScope().equals(RoleScope.API) && canManageApi(roleInGroup.getPermissions()));
            }
            return m.getRoleId() != null && roleInGroup.getScope().equals(RoleScope.API);
        }).map(MembershipEntity::getReferenceId).toArray(String[]::new);
        if (groupIds.length > 0 && groupIds[0] != null) {
            groupApis = apiRepository.search(queryToCriteria(apiQuery).groups(groupIds).build());
        }
        // get user subscribed apis, useful when an API becomes private and an app owner is not anymore in members.
        if (portal) {
            final Set<String> applications = applicationService.findByUser(userId).stream().map(ApplicationListItem::getId).collect(toSet());
            if (!applications.isEmpty()) {
                final SubscriptionQuery query = new SubscriptionQuery();
                query.setApplications(applications);
                final Collection<SubscriptionEntity> subscriptions = subscriptionService.search(query);
                if (subscriptions != null && !subscriptions.isEmpty()) {
                    subscribedApis = apiRepository.search(queryToCriteria(apiQuery).ids(subscriptions.stream().map(SubscriptionEntity::getApi).distinct().toArray(String[]::new)).build());
                }
            }
        }
    }
    List<Api> allApis = new ArrayList<>();
    allApis.addAll(publicApis);
    allApis.addAll(userApis);
    allApis.addAll(groupApis);
    allApis.addAll(subscribedApis);
    return allApis.stream().distinct().collect(toList());
}
Also used : ApiHook(io.gravitee.rest.api.service.notification.ApiHook) EndpointDiscoveryService(io.gravitee.definition.model.services.discovery.EndpointDiscoveryService) Optional.of(java.util.Optional.of) Page(io.gravitee.common.data.domain.Page) Sortable(io.gravitee.rest.api.model.common.Sortable) HookScope(io.gravitee.rest.api.service.notification.HookScope) Autowired(org.springframework.beans.factory.annotation.Autowired) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) ApiCriteria(io.gravitee.repository.management.api.search.ApiCriteria) Matcher(java.util.regex.Matcher) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) JsonNode(com.fasterxml.jackson.databind.JsonNode) EntrypointReferenceType(io.gravitee.rest.api.model.EntrypointReferenceType) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) CollectionUtils(org.springframework.util.CollectionUtils) HealthCheckService(io.gravitee.definition.model.services.healthcheck.HealthCheckService) DatatypeConverter(javax.xml.bind.DatatypeConverter) java.util(java.util) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) ApiPrimaryOwnerMode(io.gravitee.rest.api.model.settings.ApiPrimaryOwnerMode) DRAFT(io.gravitee.rest.api.model.WorkflowState.DRAFT) NotificationTemplateService(io.gravitee.rest.api.service.notification.NotificationTemplateService) DefaultMetadataUpgrader(io.gravitee.rest.api.service.impl.upgrade.DefaultMetadataUpgrader) SWAGGER(io.gravitee.rest.api.model.PageType.SWAGGER) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) PUBLIC(io.gravitee.repository.management.model.Visibility.PUBLIC) PageableImpl(io.gravitee.rest.api.model.common.PageableImpl) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) IOException(java.io.IOException) io.gravitee.definition.model(io.gravitee.definition.model) io.gravitee.rest.api.model.api(io.gravitee.rest.api.model.api) CronTrigger(org.springframework.scheduling.support.CronTrigger) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) GenericNotificationConfigEntity(io.gravitee.rest.api.model.notification.GenericNotificationConfigEntity) io.gravitee.repository.management.model(io.gravitee.repository.management.model) StringReader(java.io.StringReader) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) REVIEW(io.gravitee.rest.api.model.WorkflowType.REVIEW) Plan(io.gravitee.definition.model.Plan) API(io.gravitee.rest.api.model.WorkflowReferenceType.API) Properties(io.gravitee.definition.model.Properties) URL(java.net.URL) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ApiRepository(io.gravitee.repository.management.api.ApiRepository) Lifecycle(io.gravitee.common.component.Lifecycle) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApiQualityRuleRepository(io.gravitee.repository.management.api.ApiQualityRuleRepository) Predicate(java.util.function.Predicate) ApiLifecycleState(io.gravitee.repository.management.model.ApiLifecycleState) MetadataFormat(io.gravitee.rest.api.model.MetadataFormat) Collectors(java.util.stream.Collectors) ApiFieldExclusionFilter(io.gravitee.repository.management.api.search.ApiFieldExclusionFilter) Key(io.gravitee.rest.api.model.parameters.Key) Api(io.gravitee.repository.management.model.Api) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) APIV1toAPIV2Converter(io.gravitee.rest.api.service.migration.APIV1toAPIV2Converter) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery) Pattern(java.util.regex.Pattern) ApiHeaderEntity(io.gravitee.rest.api.model.api.header.ApiHeaderEntity) NotNull(org.jetbrains.annotations.NotNull) SystemRole(io.gravitee.rest.api.model.permissions.SystemRole) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) io.gravitee.rest.api.service(io.gravitee.rest.api.service) TagReferenceType(io.gravitee.rest.api.model.TagReferenceType) Pageable(io.gravitee.rest.api.model.common.Pageable) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) ApiPermission(io.gravitee.rest.api.model.permissions.ApiPermission) Visibility(io.gravitee.repository.management.model.Visibility) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) EventType(io.gravitee.rest.api.model.EventType) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Comparator.comparing(java.util.Comparator.comparing) PUBLISH_API(io.gravitee.rest.api.model.EventType.PUBLISH_API) ApiSynchronizationProcessor(io.gravitee.rest.api.service.processor.ApiSynchronizationProcessor) Step(io.gravitee.definition.model.flow.Step) AlertReferenceType(io.gravitee.rest.api.model.alert.AlertReferenceType) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FileInputStream(java.io.FileInputStream) AlertTriggerEntity(io.gravitee.rest.api.model.alert.AlertTriggerEntity) Component(org.springframework.stereotype.Component) INLINE(io.gravitee.rest.api.model.ImportSwaggerDescriptorEntity.Type.INLINE) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) AuditEvent(io.gravitee.repository.management.model.Workflow.AuditEvent) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) Collections(java.util.Collections) Api(io.gravitee.repository.management.model.Api) UuidString(io.gravitee.rest.api.service.common.UuidString) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery)

Example 22 with ApplicationListItem

use of io.gravitee.rest.api.model.application.ApplicationListItem in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionsResourceTest method shouldGetSubscriptionsForApi.

@Test
public void shouldGetSubscriptionsForApi() {
    final ApplicationListItem application = new ApplicationListItem();
    application.setId(APPLICATION);
    doReturn(newSet(application)).when(applicationService).findByUser(any());
    final Response response = target().queryParam("apiId", API).request().get();
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    SubscriptionsResponse subscriptionResponse = response.readEntity(SubscriptionsResponse.class);
    assertEquals(2, subscriptionResponse.getData().size());
}
Also used : Response(javax.ws.rs.core.Response) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) Test(org.junit.Test)

Example 23 with ApplicationListItem

use of io.gravitee.rest.api.model.application.ApplicationListItem in project gravitee-management-rest-api by gravitee-io.

the class FilteringServiceImpl method getEntitiesOrderByNumberOfSubscriptions.

/**
 * Filters and sorts input entities by number of subscriptions.
 *
 * @param items    Can be {@link ApiEntity} or {@link ApplicationListItem}
 * @param excluded If set to true, only entities without subscriptions are returned. Else, only entities with subscriptions are returned.
 * @return a {@link FilteredEntities} object with the filtered and sorted list of items and a metadata map.
 */
@Override
public <T extends FilterableItem> FilteredEntities<T> getEntitiesOrderByNumberOfSubscriptions(Collection<T> items, Boolean excluded, boolean isAsc) {
    if (items == null || items.isEmpty()) {
        return new FilteredEntities<>(Collections.emptyList(), new HashMap<>());
    }
    Function<SubscriptionEntity, String> getItemFunction;
    if (items.toArray()[0] instanceof ApiEntity) {
        getItemFunction = (SubscriptionEntity sub) -> sub.getApi();
    } else if (items.toArray()[0] instanceof ApplicationListItem) {
        getItemFunction = (SubscriptionEntity sub) -> sub.getApplication();
    } else {
        throw new IllegalStateException("Only ApiEntity and ApplicationListItem are allowed");
    }
    // find all subscribed items
    SubscriptionQuery subscriptionQuery = new SubscriptionQuery();
    subscriptionQuery.setApis(items.stream().map(FilterableItem::getId).collect(Collectors.toList()));
    subscriptionQuery.setStatuses(Arrays.asList(SubscriptionStatus.ACCEPTED, SubscriptionStatus.PAUSED));
    // group by items
    Map<String, Long> subscribedItemsWithCount = subscriptionService.search(subscriptionQuery).stream().collect(Collectors.groupingBy(getItemFunction, Collectors.counting()));
    // link an item with its nb of subscriptions
    Map<FilterableItem, Long> itemsWithCount = new HashMap<>();
    Map<String, Map<String, Object>> itemsMetadata = new HashMap<>();
    Map<String, Object> subscriptionsMetadata = new HashMap<>();
    itemsMetadata.put("subscriptions", subscriptionsMetadata);
    items.forEach(item -> {
        Long itemSubscriptionsCount = subscribedItemsWithCount.get(item.getId());
        if ((excluded == null) || (!excluded && itemSubscriptionsCount != null) || (excluded && itemSubscriptionsCount == null)) {
            // creation of a map which will be sorted to retrieve items in the right order
            itemsWithCount.put(item, itemSubscriptionsCount == null ? 0L : itemSubscriptionsCount);
            // creation of a metadata map
            subscriptionsMetadata.put(item.getId(), itemSubscriptionsCount == null ? 0L : itemSubscriptionsCount);
        }
    });
    // order the list
    Comparator<Map.Entry<FilterableItem, Long>> comparingByValue = Map.Entry.comparingByValue();
    if (!isAsc) {
        comparingByValue = comparingByValue.reversed();
    }
    return new FilteredEntities(itemsWithCount.entrySet().stream().sorted(Map.Entry.<FilterableItem, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey(Comparator.comparing(FilterableItem::getName, String.CASE_INSENSITIVE_ORDER)))).map(Map.Entry::getKey).collect(Collectors.toList()), itemsMetadata);
}
Also used : ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) TopApiEntity(io.gravitee.rest.api.model.TopApiEntity) SubscriptionEntity(io.gravitee.rest.api.model.SubscriptionEntity) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) FilteredEntities(io.gravitee.rest.api.model.filtering.FilteredEntities) FilterableItem(io.gravitee.rest.api.model.filtering.FilterableItem)

Example 24 with ApplicationListItem

use of io.gravitee.rest.api.model.application.ApplicationListItem in project gravitee-management-rest-api by gravitee-io.

the class ApplicationAlertServiceTest method shouldHandleNotificationTemplateUpdatedEventEmptyNotification.

@Test
public void shouldHandleNotificationTemplateUpdatedEventEmptyNotification() throws Exception {
    NotificationTemplateEntity notificationTemplate = new NotificationTemplateEntity();
    notificationTemplate.setHook(AlertHook.CONSUMER_RESPONSE_TIME.name());
    notificationTemplate.setTitle("notification-template-title");
    notificationTemplate.setContent("notification-template-content");
    NotificationTemplateEvent notificationTemplateEvent = new NotificationTemplateEvent("org-id", notificationTemplate);
    final SimpleEvent<ApplicationAlertEventType, Object> event = new SimpleEvent<>(ApplicationAlertEventType.NOTIFICATION_TEMPLATE_UPDATE, notificationTemplateEvent);
    ApplicationListItem app1 = new ApplicationListItem();
    app1.setId("app1");
    ApplicationListItem app2 = new ApplicationListItem();
    app2.setId("app2");
    when(applicationService.findByOrganization("org-id")).thenReturn(new HashSet<>(Arrays.asList(app1, app2)));
    final AlertTriggerEntity alertTrigger = mock(AlertTriggerEntity.class);
    when(alertTrigger.getType()).thenReturn("METRICS_AGGREGATION");
    when(alertService.findByReferenceAndReferenceIds(AlertReferenceType.APPLICATION, Arrays.asList("app1", "app2"))).thenReturn(Collections.singletonList(alertTrigger));
    when(alertTrigger.getNotifications()).thenReturn(Collections.emptyList());
    cut.handleEvent(event);
    verify(alertService, times(0)).update(any());
}
Also used : ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) NotificationTemplateEvent(io.gravitee.rest.api.model.notification.NotificationTemplateEvent) SimpleEvent(io.gravitee.common.event.impl.SimpleEvent) ApplicationAlertEventType(io.gravitee.rest.api.model.alert.ApplicationAlertEventType) NotificationTemplateEntity(io.gravitee.rest.api.model.notification.NotificationTemplateEntity) UpdateAlertTriggerEntity(io.gravitee.rest.api.model.alert.UpdateAlertTriggerEntity) NewAlertTriggerEntity(io.gravitee.rest.api.model.alert.NewAlertTriggerEntity) AlertTriggerEntity(io.gravitee.rest.api.model.alert.AlertTriggerEntity) Test(org.junit.Test)

Example 25 with ApplicationListItem

use of io.gravitee.rest.api.model.application.ApplicationListItem in project gravitee-management-rest-api by gravitee-io.

the class ApplicationAlertServiceTest method shouldHandleNotificationTemplateUpdatedEventStatusAlert.

@Test
public void shouldHandleNotificationTemplateUpdatedEventStatusAlert() throws Exception {
    NotificationTemplateEntity notificationTemplate = new NotificationTemplateEntity();
    notificationTemplate.setHook(AlertHook.CONSUMER_HTTP_STATUS.name());
    notificationTemplate.setTitle("notification-template-title");
    notificationTemplate.setContent("notification-template-content");
    NotificationTemplateEvent notificationTemplateEvent = new NotificationTemplateEvent("org-id", notificationTemplate);
    final SimpleEvent<ApplicationAlertEventType, Object> event = new SimpleEvent<>(ApplicationAlertEventType.NOTIFICATION_TEMPLATE_UPDATE, notificationTemplateEvent);
    ApplicationListItem app1 = new ApplicationListItem();
    app1.setId("app1");
    ApplicationListItem app2 = new ApplicationListItem();
    app2.setId("app2");
    when(applicationService.findByOrganization("org-id")).thenReturn(new HashSet<>(Arrays.asList(app1, app2)));
    final AlertTriggerEntity alertTrigger = mock(AlertTriggerEntity.class);
    when(alertTrigger.getType()).thenReturn("METRICS_RATE");
    when(alertService.findByReferenceAndReferenceIds(AlertReferenceType.APPLICATION, Arrays.asList("app1", "app2"))).thenReturn(Collections.singletonList(alertTrigger));
    Notification notification = new Notification();
    notification.setType("default-email");
    notification.setConfiguration("");
    when(alertTrigger.getNotifications()).thenReturn(Collections.singletonList(notification));
    JsonNode emailNode = JsonNodeFactory.instance.objectNode().put("to", "to").put("from", "from").put("subject", "subject").put("body", "body");
    when(mapper.readTree(notification.getConfiguration())).thenReturn(emailNode);
    cut.handleEvent(event);
    ArgumentCaptor<UpdateAlertTriggerEntity> updatingCaptor = ArgumentCaptor.forClass(UpdateAlertTriggerEntity.class);
    verify(alertService, times(1)).update(updatingCaptor.capture());
    final UpdateAlertTriggerEntity updating = updatingCaptor.getValue();
    assertThat(updating.getNotifications().get(0).getConfiguration()).contains("notification-template-content");
    assertThat(updating.getNotifications().get(0).getConfiguration()).contains("notification-template-title");
}
Also used : UpdateAlertTriggerEntity(io.gravitee.rest.api.model.alert.UpdateAlertTriggerEntity) SimpleEvent(io.gravitee.common.event.impl.SimpleEvent) NotificationTemplateEntity(io.gravitee.rest.api.model.notification.NotificationTemplateEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode) UpdateAlertTriggerEntity(io.gravitee.rest.api.model.alert.UpdateAlertTriggerEntity) NewAlertTriggerEntity(io.gravitee.rest.api.model.alert.NewAlertTriggerEntity) AlertTriggerEntity(io.gravitee.rest.api.model.alert.AlertTriggerEntity) Notification(io.gravitee.notifier.api.Notification) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) NotificationTemplateEvent(io.gravitee.rest.api.model.notification.NotificationTemplateEvent) ApplicationAlertEventType(io.gravitee.rest.api.model.alert.ApplicationAlertEventType) Test(org.junit.Test)

Aggregations

ApplicationListItem (io.gravitee.rest.api.model.application.ApplicationListItem)29 Test (org.junit.Test)16 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)11 Response (javax.ws.rs.core.Response)9 SubscriptionEntity (io.gravitee.rest.api.model.SubscriptionEntity)8 SubscriptionQuery (io.gravitee.rest.api.model.subscription.SubscriptionQuery)7 ApplicationEntity (io.gravitee.rest.api.model.ApplicationEntity)6 Collectors (java.util.stream.Collectors)6 ApplicationService (io.gravitee.rest.api.service.ApplicationService)5 java.util (java.util)5 MediaType (io.gravitee.common.http.MediaType)4 FilterableItem (io.gravitee.rest.api.model.filtering.FilterableItem)4 Inject (javax.inject.Inject)4 Before (org.junit.Before)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 SimpleEvent (io.gravitee.common.event.impl.SimpleEvent)3 UserEntity (io.gravitee.rest.api.model.UserEntity)3 AlertTriggerEntity (io.gravitee.rest.api.model.alert.AlertTriggerEntity)3 ApiQuery (io.gravitee.rest.api.model.api.ApiQuery)3 Application (io.gravitee.rest.api.portal.rest.model.Application)3