Search in sources :

Example 56 with ApiEntity

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));
}
Also used : Response(javax.ws.rs.core.Response) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Test(org.junit.Test)

Example 57 with ApiEntity

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);
}
Also used : Response(javax.ws.rs.core.Response) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) StatsAnalytics(io.gravitee.rest.api.model.analytics.query.StatsAnalytics) Test(org.junit.Test)

Example 58 with ApiEntity

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;
}
Also used : ApplicationEntity(io.gravitee.rest.api.model.ApplicationEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity)

Example 59 with ApiEntity

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);
}
Also used : ApiEntity(io.gravitee.rest.api.model.api.ApiEntity)

Example 60 with 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);
        }
    }
}
Also used : io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) VirtualHost(io.gravitee.definition.model.VirtualHost) LoggerFactory(org.slf4j.LoggerFactory) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) Proxy(io.gravitee.definition.model.Proxy) Collections.singletonList(java.util.Collections.singletonList) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) Objects.requireNonNull(java.util.Objects.requireNonNull) UpdateApiEntity(io.gravitee.rest.api.model.api.UpdateApiEntity) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) io.gravitee.rest.api.model(io.gravitee.rest.api.model) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collectors.toSet(java.util.stream.Collectors.toSet) UuidString(io.gravitee.rest.api.service.common.UuidString) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DuplicateApiEntity(io.gravitee.rest.api.model.api.DuplicateApiEntity) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) HttpMethod(io.gravitee.common.http.HttpMethod) DefinitionVersion(io.gravitee.definition.model.DefinitionVersion) Buffer(io.vertx.core.buffer.Buffer) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) ApiSerializer(io.gravitee.rest.api.service.jackson.ser.api.ApiSerializer) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) UuidString(io.gravitee.rest.api.service.common.UuidString) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Collections.singletonList(java.util.Collections.singletonList) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Aggregations

ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)273 Test (org.junit.Test)180 Response (javax.ws.rs.core.Response)65 Before (org.junit.Before)46 ApiQuery (io.gravitee.rest.api.model.api.ApiQuery)35 Error (io.gravitee.rest.api.portal.rest.model.Error)32 java.util (java.util)30 Collectors (java.util.stream.Collectors)27 Mockito.doReturn (org.mockito.Mockito.doReturn)27 Mockito (org.mockito.Mockito)25 ArgumentMatchers (org.mockito.ArgumentMatchers)24 UpdateApiEntity (io.gravitee.rest.api.model.api.UpdateApiEntity)23 Assert (org.junit.Assert)22 Collections.singletonList (java.util.Collections.singletonList)21 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)20 IOException (java.io.IOException)20 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)19 Entity (javax.ws.rs.client.Entity)19 HashSet (java.util.HashSet)18 Api (io.gravitee.repository.management.model.Api)17