use of io.gravitee.rest.api.model.api.ApiEntity in project gravitee-management-rest-api by gravitee-io.
the class ApplicationSubscriptionsResourceTest method shouldCreateSubscription.
@Test
public void shouldCreateSubscription() {
reset(apiService, planService, subscriptionService, userService);
NewSubscriptionEntity newSubscriptionEntity = new NewSubscriptionEntity();
newSubscriptionEntity.setApplication(APPLICATION);
newSubscriptionEntity.setPlan(PLAN);
newSubscriptionEntity.setRequest("request");
when(planService.findById(any())).thenReturn(mock(PlanEntity.class));
SubscriptionEntity createdSubscription = new SubscriptionEntity();
createdSubscription.setId(SUBSCRIPTION);
when(subscriptionService.create(any())).thenReturn(createdSubscription);
when(userService.findById(any(), anyBoolean())).thenReturn(mock(UserEntity.class));
ApiEntity foundApi = new ApiEntity();
foundApi.setPrimaryOwner(mock(PrimaryOwnerEntity.class));
when(apiService.findById(any())).thenReturn(foundApi);
final Response response = envTarget().path(APPLICATION).path("subscriptions").queryParam("plan", PLAN).request().post(Entity.json(newSubscriptionEntity));
assertEquals(CREATED_201, response.getStatus());
assertEquals(envTarget().path(APPLICATION).path("subscriptions").path(SUBSCRIPTION).getUri().toString(), response.getHeaders().getFirst(HttpHeaders.LOCATION));
}
use of io.gravitee.rest.api.model.api.ApiEntity in project gravitee-management-rest-api by gravitee-io.
the class EnvironmentAnalyticsResourceTest method shouldGetCountAnalyticsWhenNotAdminAndApi.
@Test
public void shouldGetCountAnalyticsWhenNotAdminAndApi() {
ApiEntity api = new ApiEntity();
api.setId("apiId");
when(apiService.findByUser(any(), any(), eq(false))).thenReturn(Collections.singleton(api));
when(permissionService.hasPermission(API_ANALYTICS, api.getId(), READ)).thenReturn(true);
Response response = envTarget().queryParam("type", "count").queryParam("field", "api").queryParam("interval", 1000).queryParam("to", 1000).request().get();
assertThat(response).isNotNull();
assertThat(response.getStatus()).isEqualTo(HttpStatusCode.OK_200);
StatsAnalytics analytics = response.readEntity(StatsAnalytics.class);
assertThat(analytics.getAvg()).isNull();
assertThat(analytics.getCount()).isEqualTo(1);
}
use of io.gravitee.rest.api.model.api.ApiEntity in project gravitee-management-rest-api by gravitee-io.
the class PermissionsFilter method hasPermission.
protected boolean hasPermission(ContainerRequestContext requestContext, String username, Permission permission) {
Map<String, char[]> memberPermissions;
switch(permission.value().getScope()) {
case ORGANIZATION:
memberPermissions = membershipService.getUserMemberPermissions(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), username);
return roleService.hasPermission(memberPermissions, permission.value().getPermission(), permission.acls());
case ENVIRONMENT:
memberPermissions = membershipService.getUserMemberPermissions(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), username);
return roleService.hasPermission(memberPermissions, permission.value().getPermission(), permission.acls());
case APPLICATION:
ApplicationEntity application = getApplication(requestContext);
memberPermissions = membershipService.getUserMemberPermissions(application, username);
return roleService.hasPermission(memberPermissions, permission.value().getPermission(), permission.acls());
case API:
ApiEntity api = getApi(requestContext);
memberPermissions = membershipService.getUserMemberPermissions(api, username);
return roleService.hasPermission(memberPermissions, permission.value().getPermission(), permission.acls());
default:
sendSecurityError();
}
return false;
}
use of io.gravitee.rest.api.model.api.ApiEntity in project gravitee-management-rest-api by gravitee-io.
the class ApiMetadataServiceImpl method checkReferenceMetadataFormat.
@Override
protected void checkReferenceMetadataFormat(MetadataFormat format, String value, MetadataReferenceType referenceType, String referenceId) {
final ApiEntity apiEntity = apiService.findById(referenceId);
metadataService.checkMetadataFormat(format, value, referenceType, apiEntity);
}
use of io.gravitee.rest.api.model.api.ApiEntity in project gravitee-management-rest-api by gravitee-io.
the class ApiDuplicatorServiceImpl method updateApiReferences.
private void updateApiReferences(ApiEntity createdOrUpdatedApiEntity, JsonNode jsonNode, String organizationId, String environmentId, // FIXME: This whole method should be split in 2 (creation and update) and this flag should be removed
boolean isUpdate) throws JsonProcessingException {
// Members
final JsonNode membersToImport = jsonNode.path("members");
if (membersToImport != null && membersToImport.isArray()) {
// get current members of the api
Set<MemberToImport> membersAlreadyPresent = membershipService.getMembersByReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId()).stream().map(member -> {
UserEntity userEntity = userService.findById(member.getId());
return new MemberToImport(userEntity.getSource(), userEntity.getSourceId(), member.getRoles().stream().map(RoleEntity::getId).collect(Collectors.toList()), null);
}).collect(toSet());
// get the current PO
RoleEntity poRole = roleService.findPrimaryOwnerRoleByOrganization(organizationId, RoleScope.API);
if (poRole != null) {
String poRoleId = poRole.getId();
MemberToImport currentPo = membersAlreadyPresent.stream().filter(memberToImport -> memberToImport.getRoles().contains(poRoleId)).findFirst().orElse(new MemberToImport());
List<String> roleUsedInTransfert = null;
MemberToImport futurePO = null;
// upsert members
for (final JsonNode memberNode : membersToImport) {
MemberToImport memberToImport = objectMapper.readValue(memberNode.toString(), MemberToImport.class);
String roleToAdd = memberToImport.getRole();
List<String> rolesToImport = memberToImport.getRoles();
if (roleToAdd != null && !roleToAdd.isEmpty()) {
if (rolesToImport == null) {
rolesToImport = new ArrayList<>();
memberToImport.setRoles(rolesToImport);
}
Optional<RoleEntity> optRoleToAddEntity = roleService.findByScopeAndName(RoleScope.API, roleToAdd);
if (optRoleToAddEntity.isPresent()) {
rolesToImport.add(optRoleToAddEntity.get().getId());
} else {
LOGGER.warn("Role {} does not exist", roleToAdd);
}
}
if (rolesToImport != null) {
rolesToImport.sort(Comparator.naturalOrder());
}
boolean presentWithSameRole = memberToImport.getRoles() != null && !memberToImport.getRoles().isEmpty() && membersAlreadyPresent.stream().anyMatch(m -> {
m.getRoles().sort(Comparator.naturalOrder());
return (m.getRoles().equals(memberToImport.getRoles()) && (m.getSourceId().equals(memberToImport.getSourceId()) && m.getSource().equals(memberToImport.getSource())));
});
// - not the current PO
if (!presentWithSameRole && (memberToImport.getRoles() != null && !memberToImport.getRoles().isEmpty() && !memberToImport.getRoles().contains(poRoleId)) && !(memberToImport.getSourceId().equals(currentPo.getSourceId()) && memberToImport.getSource().equals(currentPo.getSource()))) {
try {
UserEntity userEntity = userService.findBySource(memberToImport.getSource(), memberToImport.getSourceId(), false);
rolesToImport.forEach(role -> membershipService.addRoleToMemberOnReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId(), MembershipMemberType.USER, userEntity.getId(), role));
} catch (UserNotFoundException unfe) {
}
}
// get the future role of the current PO
if (currentPo.getSourceId().equals(memberToImport.getSourceId()) && currentPo.getSource().equals(memberToImport.getSource()) && !rolesToImport.contains(poRoleId)) {
roleUsedInTransfert = rolesToImport;
}
if (rolesToImport.contains(poRoleId)) {
futurePO = memberToImport;
}
}
// transfer the ownership
if (futurePO != null && !(currentPo.getSource().equals(futurePO.getSource()) && currentPo.getSourceId().equals(futurePO.getSourceId()))) {
try {
UserEntity userEntity = userService.findBySource(futurePO.getSource(), futurePO.getSourceId(), false);
List<RoleEntity> roleEntity = null;
if (roleUsedInTransfert != null && !roleUsedInTransfert.isEmpty()) {
roleEntity = roleUsedInTransfert.stream().map(roleService::findById).collect(Collectors.toList());
}
membershipService.transferApiOwnership(createdOrUpdatedApiEntity.getId(), new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER), roleEntity);
} catch (UserNotFoundException unfe) {
}
}
}
}
if (isUpdate) {
// Pages
final JsonNode pagesDefinition = jsonNode.path("pages");
if (pagesDefinition != null && pagesDefinition.isArray()) {
List<PageEntity> pagesList = objectMapper.readValue(pagesDefinition.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, PageEntity.class));
pageService.createOrUpdatePages(pagesList, environmentId, createdOrUpdatedApiEntity.getId());
}
}
// Plans
final JsonNode plansDefinition = jsonNode.path("plans");
if (plansDefinition != null && plansDefinition.isArray()) {
List<PlanEntity> plansList = objectMapper.readValue(plansDefinition.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, PlanEntity.class));
plansList.forEach(planEntity -> {
planEntity.setApi(createdOrUpdatedApiEntity.getId());
planEntity.setId(UuidString.generateForEnvironment(environmentId, createdOrUpdatedApiEntity.getId(), planEntity.getId()));
planService.createOrUpdatePlan(planEntity, environmentId);
});
}
// Metadata
final JsonNode metadataDefinition = jsonNode.path("metadata");
if (metadataDefinition != null && metadataDefinition.isArray()) {
try {
for (JsonNode metadataNode : metadataDefinition) {
UpdateApiMetadataEntity updateApiMetadataEntity = objectMapper.readValue(metadataNode.toString(), UpdateApiMetadataEntity.class);
updateApiMetadataEntity.setApiId(createdOrUpdatedApiEntity.getId());
apiMetadataService.update(updateApiMetadataEntity);
}
} catch (Exception ex) {
LOGGER.error("An error occurs while creating API metadata", ex);
throw new TechnicalManagementException("An error occurs while creating API Metadata", ex);
}
}
}
Aggregations