use of io.gravitee.rest.api.model.subscription.SubscriptionQuery in project gravitee-management-rest-api by gravitee-io.
the class ApplicationSubscribersResource method getSubscriberApisByApplicationId.
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response getSubscriberApisByApplicationId(@BeanParam PaginationParam paginationParam, @PathParam("applicationId") String applicationId, @QueryParam("statuses") List<SubscriptionStatus> statuses) {
String currentUser = getAuthenticatedUserOrNull();
Collection<ApplicationListItem> userApplications = applicationService.findByUser(currentUser);
Optional<ApplicationListItem> optionalApplication = userApplications.stream().filter(a -> a.getId().equals(applicationId)).findFirst();
if (optionalApplication.isPresent()) {
SubscriptionQuery subscriptionQuery = new SubscriptionQuery();
subscriptionQuery.setApplication(applicationId);
subscriptionQuery.setStatuses(statuses);
ApplicationListItem application = optionalApplication.get();
if (!application.getPrimaryOwner().getId().equals(currentUser)) {
Set<ApiEntity> userApis = this.apiService.findPublishedByUser(currentUser);
if (userApis == null || userApis.isEmpty()) {
return createListResponse(Collections.emptyList(), paginationParam);
}
subscriptionQuery.setApis(userApis.stream().map(ApiEntity::getId).collect(Collectors.toList()));
}
Map<String, Long> nbHitsByApp = getNbHitsByApplication(applicationId);
Collection<SubscriptionEntity> subscriptions = subscriptionService.search(subscriptionQuery);
List<Api> subscribersApis = subscriptions.stream().map(SubscriptionEntity::getApi).distinct().map(api -> apiService.findById(api)).map(apiMapper::convert).sorted((o1, o2) -> compareApp(nbHitsByApp, o1, o2)).collect(Collectors.toList());
return createListResponse(subscribersApis, paginationParam);
}
throw new ApplicationNotFoundException(applicationId);
}
use of io.gravitee.rest.api.model.subscription.SubscriptionQuery in project gravitee-management-rest-api by gravitee-io.
the class ApiSubscribersResource method getApiSubscribers.
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "List subscribers for the API", notes = "User must have the MANAGE_SUBSCRIPTIONS permission to use this service")
@ApiResponses({ @ApiResponse(code = 200, message = "Paged result of API subscribers", response = ApplicationEntity.class, responseContainer = "List"), @ApiResponse(code = 500, message = "Internal server error") })
public Collection<ApplicationEntity> getApiSubscribers() {
if (!hasPermission(RolePermission.API_SUBSCRIPTION, api, RolePermissionAction.READ) && !hasPermission(RolePermission.API_LOG, api, RolePermissionAction.READ)) {
throw new ForbiddenAccessException();
}
SubscriptionQuery subscriptionQuery = new SubscriptionQuery();
subscriptionQuery.setApi(api);
Collection<SubscriptionEntity> subscriptions = subscriptionService.search(subscriptionQuery);
return subscriptions.stream().map(SubscriptionEntity::getApplication).distinct().map(application -> applicationService.findById(application)).sorted((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName())).collect(Collectors.toList());
}
use of io.gravitee.rest.api.model.subscription.SubscriptionQuery in project gravitee-management-rest-api by gravitee-io.
the class ApplicationSubscriptionsResource method getApplicationSubscriptions.
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "List subscriptions for the application", notes = "User must have the READ_SUBSCRIPTION permission to use this service")
@ApiResponses({ @ApiResponse(code = 200, message = "Paged result of application's subscriptions", response = PagedResult.class), @ApiResponse(code = 500, message = "Internal server error") })
@Permissions({ @Permission(value = RolePermission.APPLICATION_SUBSCRIPTION, acls = RolePermissionAction.READ) })
public PagedResult<SubscriptionEntity> getApplicationSubscriptions(@BeanParam SubscriptionParam subscriptionParam, @Valid @BeanParam Pageable pageable, @ApiParam(allowableValues = "keys", value = "Expansion of data to return in subscriptions") @QueryParam("expand") List<String> expand) {
// Transform query parameters to a subscription query
SubscriptionQuery subscriptionQuery = subscriptionParam.toQuery();
subscriptionQuery.setApplication(application);
Page<SubscriptionEntity> subscriptions = subscriptionService.search(subscriptionQuery, pageable.toPageable());
if (expand != null && !expand.isEmpty()) {
for (String e : expand) {
switch(e) {
case "keys":
subscriptions.getContent().forEach(subscriptionEntity -> {
final List<String> keys = apiKeyService.findBySubscription(subscriptionEntity.getId()).stream().filter(apiKeyEntity -> !apiKeyEntity.isExpired() && !apiKeyEntity.isRevoked()).map(ApiKeyEntity::getKey).collect(Collectors.toList());
subscriptionEntity.setKeys(keys);
});
break;
default:
break;
}
}
}
PagedResult<SubscriptionEntity> result = new PagedResult<>(subscriptions, pageable.getSize());
result.setMetadata(subscriptionService.getMetadata(subscriptions.getContent()).getMetadata());
return result;
}
use of io.gravitee.rest.api.model.subscription.SubscriptionQuery 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.subscription.SubscriptionQuery 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 (ApplicationStatus.ARCHIVED.equals(optApplicationToUpdate.get().getStatus())) {
throw new ApplicationArchivedException(optApplicationToUpdate.get().getName());
}
// Check that only one settings is defined
if (updateApplicationEntity.getSettings().getApp() != null && updateApplicationEntity.getSettings().getoAuthClient() != null) {
throw new InvalidApplicationTypeException();
}
// Check that a type is defined
if (updateApplicationEntity.getSettings().getApp() == null && updateApplicationEntity.getSettings().getoAuthClient() == null) {
throw new InvalidApplicationTypeException();
}
// Update application metadata
Map<String, String> metadata = new HashMap<>();
// Update a simple application
if (optApplicationToUpdate.get().getType() == ApplicationType.SIMPLE && updateApplicationEntity.getSettings().getApp() != null) {
// If clientId is set, check for uniqueness
String clientId = updateApplicationEntity.getSettings().getApp().getClientId();
if (clientId != null && !clientId.trim().isEmpty()) {
LOGGER.debug("Check that client_id is unique among all applications");
final Set<Application> applications = applicationRepository.findAllByEnvironment(GraviteeContext.getCurrentEnvironment(), ApplicationStatus.ACTIVE);
final Optional<Application> byClientId = applications.stream().filter(app -> app.getMetadata() != null && clientId.equals(app.getMetadata().get("client_id"))).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);
}
}
} else {
// Check that client registration is enabled
checkClientRegistrationEnabled();
checkClientSettings(updateApplicationEntity.getSettings().getoAuthClient());
// Update an OAuth client
final String registrationPayload = optApplicationToUpdate.get().getMetadata().get("registration_payload");
if (registrationPayload != null) {
ClientRegistrationResponse registrationResponse = clientRegistrationService.update(registrationPayload, updateApplicationEntity);
if (registrationResponse != null) {
try {
metadata.put("client_id", registrationResponse.getClientId());
metadata.put("registration_payload", mapper.writeValueAsString(registrationResponse));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
}
Application application = convert(updateApplicationEntity);
application.setId(applicationId);
application.setEnvironmentId(optApplicationToUpdate.get().getEnvironmentId());
application.setStatus(ApplicationStatus.ACTIVE);
application.setType(optApplicationToUpdate.get().getType());
application.setCreatedAt(optApplicationToUpdate.get().getCreatedAt());
application.setUpdatedAt(new Date());
metadata.forEach((key, value) -> application.getMetadata().put(key, value));
Application updatedApplication = applicationRepository.update(application);
// Audit
auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_UPDATED, 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.getMetadata().get("client_id"));
}
});
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);
}
}
Aggregations