Search in sources :

Example 86 with Collections

use of java.util.Collections in project CzechIdMng by bcvsolutions.

the class DefaultIdmAuthorizationPolicyService method getDefaultAuthorities.

@Override
@Transactional(readOnly = true)
public Set<GrantedAuthority> getDefaultAuthorities(UUID identityId) {
    IdmRoleDto defaultRole = roleService.getDefaultRole();
    if (defaultRole == null) {
        LOG.debug("Default role not found, no default authorities will be added. Change configuration [{}].", IdmRoleService.PROPERTY_DEFAULT_ROLE);
        return Collections.<GrantedAuthority>emptySet();
    }
    if (defaultRole.isDisabled()) {
        LOG.debug("Default role [{}] is disabled, no default authorities will be added.", defaultRole.getCode());
        return Collections.<GrantedAuthority>emptySet();
    }
    // 
    UUID defaultRoleId = defaultRole.getId();
    Set<GrantedAuthority> defaultAuthorities = new HashSet<>();
    // default role authorities
    defaultAuthorities.addAll(getEnabledRoleAuthorities(identityId, defaultRoleId));
    // all sub roles authorities
    roleCompositionService.findAllSubRoles(defaultRoleId).stream().filter(roleComposition -> {
        IdmRoleDto subRole = DtoUtils.getEmbedded(roleComposition, IdmRoleComposition_.sub);
        return !subRole.isDisabled();
    }).forEach(roleComposition -> {
        defaultAuthorities.addAll(getEnabledRoleAuthorities(identityId, roleComposition.getSub()));
    });
    // 
    LOG.debug("Found [{}] default authorities", defaultAuthorities.size());
    return defaultAuthorities;
}
Also used : DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) Autowired(org.springframework.beans.factory.annotation.Autowired) SiemLoggerManager(eu.bcvsolutions.idm.core.api.audit.service.SiemLoggerManager) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) IdmAuthorizationPolicyFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmAuthorizationPolicyFilter) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) Predicate(javax.persistence.criteria.Predicate) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) IdmAuthorizationPolicyRepository(eu.bcvsolutions.idm.core.model.repository.IdmAuthorizationPolicyRepository) ModuleService(eu.bcvsolutions.idm.core.api.service.ModuleService) EntityEvent(eu.bcvsolutions.idm.core.api.event.EntityEvent) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) IdmRole_(eu.bcvsolutions.idm.core.model.entity.IdmRole_) ImmutableMap(com.google.common.collect.ImmutableMap) IdmRoleComposition_(eu.bcvsolutions.idm.core.model.entity.IdmRoleComposition_) AbstractEventableDtoService(eu.bcvsolutions.idm.core.api.service.AbstractEventableDtoService) IdmRoleService(eu.bcvsolutions.idm.core.api.service.IdmRoleService) Set(java.util.Set) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) IdmRoleCompositionService(eu.bcvsolutions.idm.core.api.service.IdmRoleCompositionService) UUID(java.util.UUID) IdmAuthorizationPolicy(eu.bcvsolutions.idm.core.model.entity.IdmAuthorizationPolicy) Sets(com.google.common.collect.Sets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Objects(java.util.Objects) IdmAuthorizationPolicy_(eu.bcvsolutions.idm.core.model.entity.IdmAuthorizationPolicy_) List(java.util.List) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) IdmAuthorizationPolicyDto(eu.bcvsolutions.idm.core.api.dto.IdmAuthorizationPolicyDto) LocalDate(java.time.LocalDate) Identifiable(eu.bcvsolutions.idm.core.api.domain.Identifiable) IdmAuthorizationPolicyService(eu.bcvsolutions.idm.core.api.service.IdmAuthorizationPolicyService) IdmGroupPermission(eu.bcvsolutions.idm.core.security.api.domain.IdmGroupPermission) Collections(java.util.Collections) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) AuthorizableType(eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType) Transactional(org.springframework.transaction.annotation.Transactional) Assert(org.springframework.util.Assert) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) DefaultGrantedAuthority(eu.bcvsolutions.idm.core.security.api.domain.DefaultGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UUID(java.util.UUID) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 87 with Collections

use of java.util.Collections in project CzechIdMng by bcvsolutions.

the class AbstractProvisioningExecutor method changePassword.

@Override
public List<OperationResult> changePassword(DTO dto, PasswordChangeDto passwordChange) {
    Assert.notNull(dto, "DTO is required.");
    Assert.notNull(dto.getId(), "Password can be changed, when dto is already persisted.");
    Assert.notNull(passwordChange, "Password change dto is required.");
    List<SysProvisioningOperationDto> preparedOperations = new ArrayList<>();
    // 
    EntityAccountFilter filter = this.createEntityAccountFilter();
    filter.setEntityId(dto.getId());
    List<? extends EntityAccountDto> entityAccountList = getEntityAccountService().find(filter, null).getContent();
    if (entityAccountList == null) {
        return Collections.<OperationResult>emptyList();
    }
    // Distinct by accounts
    List<UUID> accountIds = new ArrayList<>();
    entityAccountList.stream().filter(entityAccount -> {
        if (!entityAccount.isOwnership()) {
            return false;
        }
        if (passwordChange.isAll()) {
            // Add all account supports change password
            if (entityAccount.getAccount() == null) {
                return false;
            }
            // Check if system for this account support change password
            AccAccountFilter accountFilter = new AccAccountFilter();
            accountFilter.setSupportChangePassword(Boolean.TRUE);
            accountFilter.setId(entityAccount.getAccount());
            List<AccAccountDto> accountsChecked = accountService.find(accountFilter, null).getContent();
            if (accountsChecked.size() == 1) {
                return true;
            }
            return false;
        } else {
            return passwordChange.getAccounts().contains(entityAccount.getAccount().toString());
        }
    }).forEach(entityAccount -> {
        if (!accountIds.contains(entityAccount.getAccount())) {
            accountIds.add(entityAccount.getAccount());
        }
    });
    // 
    // Is possible that some account has disabled password attributes
    List<OperationResult> notExecutedPasswordChanged = new ArrayList<>();
    // 
    List<AccAccountDto> accounts = new ArrayList<>();
    accountIds.forEach(accountId -> {
        AccAccountDto account = accountService.get(accountId);
        // Skip account in protection
        if (account.isInProtection()) {
            // Skip this iteration
            return;
        }
        // 
        accounts.add(account);
        // find UID from system entity or from account
        SysSystemDto system = DtoUtils.getEmbedded(account, AccAccount_.system);
        if (account.getSystemEntity() == null) {
            throw new SystemEntityNotFoundException(AccResultCode.PROVISIONING_PASSWORD_SYSTEM_ENTITY_NOT_FOUND, String.valueOf(account.getUid()), system.getCode());
        }
        SysSystemEntityDto systemEntity = systemEntityService.get(account.getSystemEntity());
        // 
        // Find mapped attributes (include overloaded attributes)
        List<AttributeMapping> finalAttributes = resolveMappedAttributes(account, dto, system, systemEntity.getEntityType());
        if (CollectionUtils.isEmpty(finalAttributes)) {
            return;
        }
        // We try find __PASSWORD__ attribute in mapped attributes
        AttributeMapping mappedAttribute = finalAttributes.stream().filter((attribute) -> {
            SysSchemaAttributeDto schemaAttributeDto = getSchemaAttribute(attribute);
            return ProvisioningService.PASSWORD_SCHEMA_PROPERTY_NAME.equals(schemaAttributeDto.getName());
        }).findFirst().orElse(null);
        // 
        // get all another passwords, list with all passwords (included primary password marked as __PASSWORD__)
        SysSystemMappingDto systemMappingDto = getMapping(system, systemEntity.getEntityType());
        List<SysSystemAttributeMappingDto> passwordAttributes = attributeMappingService.getAllPasswordAttributes(system.getId(), systemMappingDto.getId());
        // 
        // create account object with all another password
        Map<ProvisioningAttributeDto, Object> accountObjectWithAnotherPassword = new HashMap<>(passwordAttributes.size());
        for (AttributeMapping passwordAttribute : passwordAttributes) {
            // all password attributes contains also main __PASSWORD__ the attribute must be skipped
            if (mappedAttribute != null && mappedAttribute.equals(passwordAttribute)) {
                continue;
            }
            GuardedString transformPassword = transformPassword(passwordChange.getNewPassword(), passwordAttribute, systemEntity.getUid(), dto);
            SysSchemaAttributeDto schemaAttribute = schemaAttributeService.get(passwordAttribute.getSchemaAttribute());
            ProvisioningAttributeDto passwordProvisiongAttributeDto = ProvisioningAttributeDto.createProvisioningAttributeKey(passwordAttribute, schemaAttribute.getName(), schemaAttribute.getClassType());
            accountObjectWithAnotherPassword.put(passwordProvisiongAttributeDto, transformPassword);
        }
        // for this account doesn't exist mapped attribute as password
        if (accountObjectWithAnotherPassword.isEmpty() && mappedAttribute == null) {
            // Beware we cant use AccAccountDto from acc module, in core is checked by this
            notExecutedPasswordChanged.add(new OperationResult.Builder(OperationState.NOT_EXECUTED).setModel(new DefaultResultModel(CoreResultCode.PASSWORD_CHANGE_ACCOUNT_FAILED, ImmutableMap.of(IdmAccountDto.PARAMETER_NAME, createResultAccount(account, system)))).build());
            // for this account is this failed password change
            return;
        }
        // 
        // add all account attributes => standard provisioning
        SysProvisioningOperationDto additionalProvisioningOperation = null;
        // resolve another attributes that must be sent together with password
        List<AttributeMapping> additionalPasswordChangeAttributes = resolveAdditionalPasswordChangeAttributes(account, dto, system, systemEntity.getEntityType());
        if (!additionalPasswordChangeAttributes.isEmpty()) {
            additionalProvisioningOperation = prepareProvisioning(systemEntity, dto, dto.getId(), ProvisioningOperationType.UPDATE, additionalPasswordChangeAttributes);
        }
        // add another password
        if (!accountObjectWithAnotherPassword.isEmpty()) {
            if (additionalProvisioningOperation == null) {
                // if additional operation is null create one
                additionalProvisioningOperation = prepareProvisioningOperationForAdditionalPassword(systemEntity, dto, dto.getId(), ProvisioningOperationType.UPDATE, systemMappingDto, accountObjectWithAnotherPassword);
            } else {
                // if additional operation exists just add all account object with additional passwords
                additionalProvisioningOperation.getProvisioningContext().getAccountObject().putAll(accountObjectWithAnotherPassword);
            }
        }
        // 
        // password change operation
        SysProvisioningOperationDto operation;
        if (provisioningExecutor.getConfiguration().isSendPasswordAttributesTogether() && additionalProvisioningOperation != null) {
            // all attributes including another password attributes will be sent with password one provisioning operation
            operation = additionalProvisioningOperation;
            // 
            if (mappedAttribute != null) {
                // Main password attribute isn't mapped
                // transform password value trough transformation
                GuardedString transformPassword = transformPassword(passwordChange.getNewPassword(), mappedAttribute, systemEntity.getUid(), dto);
                // 
                // add wish for password
                SysSchemaAttributeDto schemaAttributeDto = schemaAttributeService.get(mappedAttribute.getSchemaAttribute());
                ProvisioningAttributeDto passwordAttribute = ProvisioningAttributeDto.createProvisioningAttributeKey(mappedAttribute, schemaAttributeDto.getName(), schemaAttributeDto.getClassType());
                // 
                // newly isn't needed check if password is constant or etc.
                // 
                operation.getProvisioningContext().getAccountObject().put(passwordAttribute, transformPassword);
            }
            // 
            // do provisioning for additional attributes and password
            // together
            preparedOperations.add(operation);
        } else {
            // 
            if (mappedAttribute != null) {
                // Main password attribute isn't mapped
                // transform password value trough transformation
                GuardedString transformPassword = transformPassword(passwordChange.getNewPassword(), mappedAttribute, systemEntity.getUid(), dto);
                // 
                operation = prepareProvisioningForAttribute(systemEntity, mappedAttribute, transformPassword, ProvisioningOperationType.UPDATE, dto);
                preparedOperations.add(operation);
            }
            // do provisioning for additional attributes and passwords in second
            if (additionalProvisioningOperation != null) {
                preparedOperations.add(additionalProvisioningOperation);
            }
        }
    });
    // 
    // execute prepared operations
    List<OperationResult> results = preparedOperations.stream().map(operation -> {
        SysProvisioningOperationDto result = provisioningExecutor.executeSync(operation);
        Map<String, Object> parameters = new LinkedHashMap<String, Object>();
        AccAccountDto account = accounts.stream().filter(a -> {
            return a.getRealUid().equals(result.getSystemEntityUid()) && a.getSystem().equals(operation.getSystem());
        }).findFirst().get();
        SysSystemDto system = DtoUtils.getEmbedded(account, AccAccount_.system);
        // 
        parameters.put(IdmAccountDto.PARAMETER_NAME, createResultAccount(account, system));
        // 
        if (result.getResult().getState() == OperationState.EXECUTED) {
            // Add success changed password account
            return new OperationResult.Builder(OperationState.EXECUTED).setModel(new DefaultResultModel(CoreResultCode.PASSWORD_CHANGE_ACCOUNT_SUCCESS, parameters)).build();
        }
        OperationResult changeResult = new OperationResult.Builder(result.getResult().getState()).setModel(new DefaultResultModel(CoreResultCode.PASSWORD_CHANGE_ACCOUNT_FAILED, parameters)).build();
        changeResult.setCause(result.getResult().getCause());
        changeResult.setCode(result.getResult().getCode());
        return changeResult;
    }).collect(Collectors.toList());
    // 
    // add not executed changed from prepare stage
    results.addAll(notExecutedPasswordChanged);
    return results;
}
Also used : ProvisioningExecutor(eu.bcvsolutions.idm.acc.service.api.ProvisioningExecutor) DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) SysSchemaAttributeDto(eu.bcvsolutions.idm.acc.dto.SysSchemaAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) SysSystemEntityDto(eu.bcvsolutions.idm.acc.dto.SysSystemEntityDto) AccIdentityAccount_(eu.bcvsolutions.idm.acc.entity.AccIdentityAccount_) EntityAccountDto(eu.bcvsolutions.idm.acc.dto.EntityAccountDto) StringUtils(org.apache.commons.lang3.StringUtils) ProvisioningException(eu.bcvsolutions.idm.acc.exception.ProvisioningException) SysSystemAttributeMapping_(eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping_) IdmRoleRequestService(eu.bcvsolutions.idm.core.api.service.IdmRoleRequestService) SysRoleSystemService(eu.bcvsolutions.idm.acc.service.api.SysRoleSystemService) AccAccountDto(eu.bcvsolutions.idm.acc.dto.AccAccountDto) SysSystemEntity_(eu.bcvsolutions.idm.acc.entity.SysSystemEntity_) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) ProvisioningEntityExecutor(eu.bcvsolutions.idm.acc.service.api.ProvisioningEntityExecutor) SysSystemAttributeMapping(eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) SystemOperationType(eu.bcvsolutions.idm.acc.domain.SystemOperationType) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) Set(java.util.Set) PageRequest(org.springframework.data.domain.PageRequest) ProvisioningAttributeDto(eu.bcvsolutions.idm.acc.dto.ProvisioningAttributeDto) SysSchemaObjectClassDto(eu.bcvsolutions.idm.acc.dto.SysSchemaObjectClassDto) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) AttributeMapping(eu.bcvsolutions.idm.acc.domain.AttributeMapping) List(java.util.List) EntityAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.EntityAccountFilter) AccAccountService(eu.bcvsolutions.idm.acc.service.api.AccAccountService) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) CollectionUtils(org.springframework.util.CollectionUtils) AccountType(eu.bcvsolutions.idm.acc.domain.AccountType) Optional(java.util.Optional) IcUidAttribute(eu.bcvsolutions.idm.ic.api.IcUidAttribute) SysRoleSystemDto(eu.bcvsolutions.idm.acc.dto.SysRoleSystemDto) AccAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.AccAccountFilter) SysSchemaObjectClassService(eu.bcvsolutions.idm.acc.service.api.SysSchemaObjectClassService) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) AccResultCode(eu.bcvsolutions.idm.acc.domain.AccResultCode) IcConnectorConfiguration(eu.bcvsolutions.idm.ic.api.IcConnectorConfiguration) MappingContext(eu.bcvsolutions.idm.acc.domain.MappingContext) IcConnectorFacade(eu.bcvsolutions.idm.ic.service.api.IcConnectorFacade) ProvisioningEvent(eu.bcvsolutions.idm.acc.event.ProvisioningEvent) AttributeMappingStrategyType(eu.bcvsolutions.idm.acc.domain.AttributeMappingStrategyType) SysRoleSystem_(eu.bcvsolutions.idm.acc.entity.SysRoleSystem_) ProvisioningEventType(eu.bcvsolutions.idm.acc.domain.ProvisioningEventType) SysSystemEntityService(eu.bcvsolutions.idm.acc.service.api.SysSystemEntityService) IdmAccountDto(eu.bcvsolutions.idm.core.api.dto.IdmAccountDto) HashMap(java.util.HashMap) IcObjectClassImpl(eu.bcvsolutions.idm.ic.impl.IcObjectClassImpl) SysSystemDto(eu.bcvsolutions.idm.acc.dto.SysSystemDto) SysRoleSystemAttribute_(eu.bcvsolutions.idm.acc.entity.SysRoleSystemAttribute_) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) SystemEntityNotFoundException(eu.bcvsolutions.idm.acc.exception.SystemEntityNotFoundException) SysSystemMappingService(eu.bcvsolutions.idm.acc.service.api.SysSystemMappingService) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) ImmutableList(com.google.common.collect.ImmutableList) SystemEntityType(eu.bcvsolutions.idm.acc.domain.SystemEntityType) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) IcConnectorObjectImpl(eu.bcvsolutions.idm.ic.impl.IcConnectorObjectImpl) ProvisioningOperationType(eu.bcvsolutions.idm.acc.domain.ProvisioningOperationType) LinkedHashSet(java.util.LinkedHashSet) SysProvisioningOperationDto(eu.bcvsolutions.idm.acc.dto.SysProvisioningOperationDto) ProvisioningContext(eu.bcvsolutions.idm.acc.domain.ProvisioningContext) Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) SysSystemMappingFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSystemMappingFilter) SysRoleSystemAttributeService(eu.bcvsolutions.idm.acc.service.api.SysRoleSystemAttributeService) SysSchemaObjectClass_(eu.bcvsolutions.idm.acc.entity.SysSchemaObjectClass_) SysSystemService(eu.bcvsolutions.idm.acc.service.api.SysSystemService) IdmRoleService(eu.bcvsolutions.idm.core.api.service.IdmRoleService) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) IcAttribute(eu.bcvsolutions.idm.ic.api.IcAttribute) EventContext(eu.bcvsolutions.idm.core.api.event.EventContext) SysRoleSystemAttributeDto(eu.bcvsolutions.idm.acc.dto.SysRoleSystemAttributeDto) SysSchemaAttributeService(eu.bcvsolutions.idm.acc.service.api.SysSchemaAttributeService) SysSystemAttributeMappingFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSystemAttributeMappingFilter) Contextable(eu.bcvsolutions.idm.core.api.domain.Contextable) AccAccount_(eu.bcvsolutions.idm.acc.entity.AccAccount_) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) SysSystemAttributeMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto) SysSystemMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemMappingDto) ProvisioningService(eu.bcvsolutions.idm.acc.service.api.ProvisioningService) Collections(java.util.Collections) SysSystemAttributeMappingService(eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService) PasswordChangeDto(eu.bcvsolutions.idm.core.api.dto.PasswordChangeDto) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) Assert(org.springframework.util.Assert) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SysSchemaAttributeDto(eu.bcvsolutions.idm.acc.dto.SysSchemaAttributeDto) ArrayList(java.util.ArrayList) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) ProvisioningAttributeDto(eu.bcvsolutions.idm.acc.dto.ProvisioningAttributeDto) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) AccAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.AccAccountFilter) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) UUID(java.util.UUID) SysSystemEntityDto(eu.bcvsolutions.idm.acc.dto.SysSystemEntityDto) SysProvisioningOperationDto(eu.bcvsolutions.idm.acc.dto.SysProvisioningOperationDto) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) SysSystemAttributeMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto) SystemEntityNotFoundException(eu.bcvsolutions.idm.acc.exception.SystemEntityNotFoundException) SysSystemMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemMappingDto) AccAccountDto(eu.bcvsolutions.idm.acc.dto.AccAccountDto) SysSystemDto(eu.bcvsolutions.idm.acc.dto.SysSystemDto) EntityAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.EntityAccountFilter) SysSystemAttributeMapping(eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping) AttributeMapping(eu.bcvsolutions.idm.acc.domain.AttributeMapping) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 88 with Collections

use of java.util.Collections in project beam by apache.

the class BaseFirestoreIT method listCollections.

@Test
@TestDataLayoutHint(DataLayout.Deep)
public final void listCollections() throws Exception {
    // verification and cleanup of nested collections is much slower because each document
    // requires an rpc to find its collections, instead of using the usual size, use 20
    // to keep the test quick
    List<String> collectionIds = IntStream.rangeClosed(1, 20).mapToObj(i -> helper.colId()).collect(Collectors.toList());
    ApiFutures.transform(ApiFutures.allAsList(chunkUpDocIds(collectionIds).map(chunk -> {
        WriteBatch batch = helper.getFs().batch();
        chunk.stream().map(col -> helper.getBaseDocument().collection(col).document()).forEach(ref -> batch.set(ref, ImmutableMap.of("foo", "bar")));
        return batch.commit();
    }).collect(Collectors.toList())), FirestoreTestingHelper.flattenListList(), MoreExecutors.directExecutor()).get(10, TimeUnit.SECONDS);
    PCollection<String> actualCollectionIds = testPipeline.apply(Create.of("")).apply(getListCollectionIdsPTransform(testName.getMethodName())).apply(FirestoreIO.v1().read().listCollectionIds().withRpcQosOptions(rpcQosOptions).build());
    PAssert.that(actualCollectionIds).containsInAnyOrder(collectionIds);
    testPipeline.run(options);
}
Also used : IntStream(java.util.stream.IntStream) BatchGetDocumentsResponse(com.google.firestore.v1.BatchGetDocumentsResponse) Assume.assumeThat(org.junit.Assume.assumeThat) RunQueryRequest(com.google.firestore.v1.RunQueryRequest) Write(com.google.firestore.v1.Write) BeforeClass(org.junit.BeforeClass) TestDataLayoutHint(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.TestDataLayoutHint) CleanupMode(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.CleanupMode) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) BatchGetDocumentsRequest(com.google.firestore.v1.BatchGetDocumentsRequest) PTransform(org.apache.beam.sdk.transforms.PTransform) DocumentGenerator(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.DocumentGenerator) Create(org.apache.beam.sdk.transforms.Create) TestName(org.junit.rules.TestName) TestPipeline(org.apache.beam.sdk.testing.TestPipeline) FirestoreOptions(org.apache.beam.sdk.io.gcp.firestore.FirestoreOptions) Timeout(org.junit.rules.Timeout) ListCollectionIdsRequest(com.google.firestore.v1.ListCollectionIdsRequest) FirestoreTestingHelper.assumeEnvVarSet(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.assumeEnvVarSet) FirestoreTestingHelper.chunkUpDocIds(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.chunkUpDocIds) Before(org.junit.Before) DoFn(org.apache.beam.sdk.transforms.DoFn) AssumptionViolatedException(org.junit.AssumptionViolatedException) MoreExecutors(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors) ApiFutures(com.google.api.core.ApiFutures) GcpOptions(org.apache.beam.sdk.extensions.gcp.options.GcpOptions) PAssert(org.apache.beam.sdk.testing.PAssert) Document(com.google.firestore.v1.Document) Test(org.junit.Test) UUID(java.util.UUID) PCollection(org.apache.beam.sdk.values.PCollection) Collectors(java.util.stream.Collectors) FirestoreIO(org.apache.beam.sdk.io.gcp.firestore.FirestoreIO) TimeUnit(java.util.concurrent.TimeUnit) ListDocumentsRequest(com.google.firestore.v1.ListDocumentsRequest) WriteBatch(com.google.cloud.firestore.WriteBatch) List(java.util.List) Rule(org.junit.Rule) Filter(org.apache.beam.sdk.transforms.Filter) ParDo(org.apache.beam.sdk.transforms.ParDo) DataLayout(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.DataLayout) Matchers.equalTo(org.hamcrest.Matchers.equalTo) RpcQosOptions(org.apache.beam.sdk.io.gcp.firestore.RpcQosOptions) RunQueryResponse(com.google.firestore.v1.RunQueryResponse) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) PartitionQueryRequest(com.google.firestore.v1.PartitionQueryRequest) WriteBatch(com.google.cloud.firestore.WriteBatch) Test(org.junit.Test) TestDataLayoutHint(org.apache.beam.sdk.io.gcp.firestore.it.FirestoreTestingHelper.TestDataLayoutHint)

Example 89 with Collections

use of java.util.Collections in project drools-wb by kiegroup.

the class AbstractDataManagementStrategy method storeData.

/**
 * Store data in required target objects
 */
public void storeData(final FactModelTuple factModelTuple, final TestToolsView.Presenter testToolsPresenter, final ScenarioSimulationContext context, final GridWidget gridWidget) {
    // Instantiate a map of already assigned properties
    final Map<String, List<List<String>>> propertiesToHide = getPropertiesToHide(context.getAbstractScesimGridModelByGridWidget(gridWidget));
    final SortedMap<String, FactModelTree> visibleFacts = factModelTuple.getVisibleFacts();
    final Map<Boolean, List<Map.Entry<String, FactModelTree>>> partitionBy = visibleFacts.entrySet().stream().collect(Collectors.partitioningBy(stringFactModelTreeEntry -> stringFactModelTreeEntry.getValue().isSimple()));
    final SortedMap<String, FactModelTree> complexDataObjects = new TreeMap<>(partitionBy.get(false).stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    final SortedMap<String, FactModelTree> simpleDataObjects = new TreeMap<>(partitionBy.get(true).stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    // Update context
    SortedMap<String, FactModelTree> dataObjectFieldsMap = new TreeMap<>();
    dataObjectFieldsMap.putAll(visibleFacts);
    dataObjectFieldsMap.putAll(factModelTuple.getHiddenFacts());
    context.setDataObjectFieldsMap(dataObjectFieldsMap);
    // Update model
    // Avoid Collections.emptySortedMap() due to "The method emptySortedMap() is undefined for the type Collections" error
    SortedMap<String, FactModelTree> instanceFieldsMap = new TreeMap<>();
    SortedMap<String, FactModelTree> simpleJavaTypeInstanceFieldsMap = new TreeMap<>();
    if (GridWidget.SIMULATION.equals(gridWidget)) {
        instanceFieldsMap = getInstanceMap(complexDataObjects);
        simpleJavaTypeInstanceFieldsMap = getInstanceMap(simpleDataObjects);
        Set<String> dataObjectsInstancesName = new HashSet<>(visibleFacts.keySet());
        dataObjectsInstancesName.addAll(instanceFieldsMap.keySet());
        context.setDataObjectsInstancesName(dataObjectsInstancesName);
        Set<String> simpleJavaTypeInstancesName = new HashSet<>(simpleDataObjects.keySet());
        simpleJavaTypeInstancesName.addAll(simpleJavaTypeInstanceFieldsMap.keySet());
        context.getAbstractScesimGridModelByGridWidget(gridWidget).setSimpleJavaTypeInstancesName(simpleJavaTypeInstancesName);
    }
    // Update right panel
    TestToolsPresenterData testToolsPresenterData = new TestToolsPresenterData(complexDataObjects, simpleDataObjects, instanceFieldsMap, simpleJavaTypeInstanceFieldsMap, factModelTuple.getHiddenFacts(), propertiesToHide, gridWidget);
    testToolsPresenter.populateTestTools(testToolsPresenterData);
}
Also used : ScenarioSimulationModel(org.drools.scenariosimulation.api.model.ScenarioSimulationModel) FactModelTree(org.drools.workbench.screens.scenariosimulation.model.typedescriptor.FactModelTree) FactModelTuple(org.drools.workbench.screens.scenariosimulation.model.typedescriptor.FactModelTuple) GridWidget(org.drools.workbench.screens.scenariosimulation.client.enums.GridWidget) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ExpressionElement(org.drools.scenariosimulation.api.model.ExpressionElement) ScenarioSimulationContext(org.drools.workbench.screens.scenariosimulation.client.commands.ScenarioSimulationContext) AbstractScesimModel(org.drools.scenariosimulation.api.model.AbstractScesimModel) VALUE(org.drools.scenariosimulation.api.utils.ConstantsHolder.VALUE) Map(java.util.Map) AbstractScesimGridModel(org.drools.workbench.screens.scenariosimulation.client.models.AbstractScesimGridModel) ScesimModelDescriptor(org.drools.scenariosimulation.api.model.ScesimModelDescriptor) TestToolsPresenterData(org.drools.workbench.screens.scenariosimulation.client.rightpanel.TestToolsPresenterData) Set(java.util.Set) FactMappingType(org.drools.scenariosimulation.api.model.FactMappingType) Collectors(java.util.stream.Collectors) TestToolsView(org.drools.workbench.screens.scenariosimulation.client.rightpanel.TestToolsView) Objects(java.util.Objects) ScenarioGridColumn(org.drools.workbench.screens.scenariosimulation.client.widgets.ScenarioGridColumn) List(java.util.List) TreeMap(java.util.TreeMap) Collections(java.util.Collections) SortedMap(java.util.SortedMap) AbstractScesimData(org.drools.scenariosimulation.api.model.AbstractScesimData) TreeMap(java.util.TreeMap) FactModelTree(org.drools.workbench.screens.scenariosimulation.model.typedescriptor.FactModelTree) ArrayList(java.util.ArrayList) List(java.util.List) TestToolsPresenterData(org.drools.workbench.screens.scenariosimulation.client.rightpanel.TestToolsPresenterData) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) HashSet(java.util.HashSet)

Example 90 with Collections

use of java.util.Collections in project flow by vaadin.

the class UidlWriterTest method checkAllTypesOfDependencies_npmMode.

@Test
public void checkAllTypesOfDependencies_npmMode() throws Exception {
    UI ui = initializeUIForDependenciesTest(new TestUI());
    UidlWriter uidlWriter = new UidlWriter();
    addInitialComponentDependencies(ui, uidlWriter);
    ui.add(new ComponentWithAllDependencyTypes());
    JsonObject response = uidlWriter.createUidl(ui, false);
    Map<LoadMode, List<JsonObject>> dependenciesMap = Stream.of(LoadMode.values()).map(mode -> response.getArray(mode.name())).flatMap(JsonUtils::<JsonObject>stream).collect(Collectors.toMap(jsonObject -> LoadMode.valueOf(jsonObject.getString(Dependency.KEY_LOAD_MODE)), Collections::singletonList, (list1, list2) -> {
        List<JsonObject> result = new ArrayList<>(list1);
        result.addAll(list2);
        return result;
    }));
    assertThat("Dependencies with all types of load mode should be present in this response", dependenciesMap.size(), is(LoadMode.values().length));
    List<JsonObject> eagerDependencies = dependenciesMap.get(LoadMode.EAGER);
    assertThat("Should have an eager dependency", eagerDependencies, hasSize(1));
    assertThat("Eager dependencies should not have inline contents", eagerDependencies.stream().filter(json -> json.hasKey(Dependency.KEY_CONTENTS)).collect(Collectors.toList()), hasSize(0));
    JsonObject eagerDependency = eagerDependencies.get(0);
    assertEquals("eager.css", eagerDependency.getString(Dependency.KEY_URL));
    assertEquals(Dependency.Type.STYLESHEET, Dependency.Type.valueOf(eagerDependency.getString(Dependency.KEY_TYPE)));
    List<JsonObject> lazyDependencies = dependenciesMap.get(LoadMode.LAZY);
    JsonObject lazyDependency = lazyDependencies.get(0);
    assertEquals("lazy.css", lazyDependency.getString(Dependency.KEY_URL));
    assertEquals(Dependency.Type.STYLESHEET, Dependency.Type.valueOf(lazyDependency.getString(Dependency.KEY_TYPE)));
    List<JsonObject> inlineDependencies = dependenciesMap.get(LoadMode.INLINE);
    assertInlineDependencies(inlineDependencies);
}
Also used : VaadinServletContext(com.vaadin.flow.server.VaadinServletContext) Component(com.vaadin.flow.component.Component) JavaScript(com.vaadin.flow.component.dependency.JavaScript) PendingJavaScriptInvocation(com.vaadin.flow.component.internal.PendingJavaScriptInvocation) Json(elemental.json.Json) JsonArray(elemental.json.JsonArray) Route(com.vaadin.flow.router.Route) Map(java.util.Map) After(org.junit.After) Element(com.vaadin.flow.dom.Element) Is.is(org.hamcrest.core.Is.is) Lookup(com.vaadin.flow.di.Lookup) UI(com.vaadin.flow.component.UI) VaadinSession(com.vaadin.flow.server.VaadinSession) RoutePathProvider(com.vaadin.flow.router.RoutePathProvider) JavaScriptInvocation(com.vaadin.flow.component.internal.UIInternals.JavaScriptInvocation) BootstrapHandlerTest(com.vaadin.flow.server.BootstrapHandlerTest) Collectors(java.util.stream.Collectors) NotThreadSafe(net.jcip.annotations.NotThreadSafe) List(java.util.List) Stream(java.util.stream.Stream) Assert.assertFalse(org.junit.Assert.assertFalse) LoadMode(com.vaadin.flow.shared.ui.LoadMode) ApplicationConstants(com.vaadin.flow.shared.ApplicationConstants) Mockito.mock(org.mockito.Mockito.mock) Dependency(com.vaadin.flow.shared.ui.Dependency) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) Tag(com.vaadin.flow.component.Tag) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ElementFactory(com.vaadin.flow.dom.ElementFactory) RouterLayout(com.vaadin.flow.router.RouterLayout) StyleSheet(com.vaadin.flow.component.dependency.StyleSheet) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) MockServletServiceSessionSetup(com.vaadin.flow.server.MockServletServiceSessionSetup) Mockito.when(org.mockito.Mockito.when) Mockito(org.mockito.Mockito) JsonUtils(com.vaadin.flow.internal.JsonUtils) RoutePathProviderImpl(com.vaadin.flow.server.MockVaadinContext.RoutePathProviderImpl) RouteConfiguration(com.vaadin.flow.router.RouteConfiguration) JsonObject(elemental.json.JsonObject) Collections(java.util.Collections) ParentLayout(com.vaadin.flow.router.ParentLayout) Assert.assertEquals(org.junit.Assert.assertEquals) LoadMode(com.vaadin.flow.shared.ui.LoadMode) UI(com.vaadin.flow.component.UI) JsonObject(elemental.json.JsonObject) List(java.util.List) ArrayList(java.util.ArrayList) BootstrapHandlerTest(com.vaadin.flow.server.BootstrapHandlerTest) Test(org.junit.Test)

Aggregations

Collections (java.util.Collections)113 List (java.util.List)59 ArrayList (java.util.ArrayList)41 Test (org.junit.Test)39 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)34 Arrays (java.util.Arrays)28 HashMap (java.util.HashMap)26 Set (java.util.Set)25 HashSet (java.util.HashSet)23 IOException (java.io.IOException)19 Collection (java.util.Collection)19 Optional (java.util.Optional)19 TimeUnit (java.util.concurrent.TimeUnit)16 URI (java.net.URI)13 Assert (org.junit.Assert)13 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 Before (org.junit.Before)12 Logger (org.slf4j.Logger)12