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());
}
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());
}
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);
}
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());
}
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");
}
Aggregations