Search in sources :

Example 96 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class Neo4jService method findNodeId.

public String findNodeId(String neo4JConfiguration, CustomEntityTemplate cet, Map<String, Object> fields) throws ELException, BusinessException {
    final Set<CustomEntityTemplateUniqueConstraint> trustedQueries = cet.getNeo4JStorageConfiguration().getUniqueConstraints().stream().filter(customEntityTemplateUniqueConstraint -> customEntityTemplateUniqueConstraint.getTrustScore().equals(100)).filter(uniqueConstraint -> isApplicableConstraint(fields, uniqueConstraint)).collect(Collectors.toSet());
    for (CustomEntityTemplateUniqueConstraint trustedQuery : trustedQueries) {
        final Set<String> strings = neo4jDao.executeUniqueConstraint(neo4JConfiguration, trustedQuery, fields, cet.getCode());
        if (strings.size() == 1) {
            return strings.iterator().next();
        }
    }
    final Map<String, CustomFieldTemplate> cfts = fields.keySet().stream().map(code -> customFieldsCache.getCustomFieldTemplate(code, cet.getAppliesTo())).collect(Collectors.toMap(BusinessEntity::getCode, Function.identity()));
    Map<String, Object> uniqueFields = new HashMap<>();
    validateAndConvertCustomFields(cfts, fields, uniqueFields, true);
    if (uniqueFields.isEmpty()) {
        return null;
    }
    return neo4jDao.findNodeId(neo4JConfiguration, cet.getCode(), uniqueFields);
}
Also used : CustomRelationshipTemplateService(org.meveo.service.custom.CustomRelationshipTemplateService) CrossStorageTransaction(org.meveo.persistence.CrossStorageTransaction) CustomPersistenceService(org.meveo.persistence.CustomPersistenceService) Date(java.util.Date) ELException(org.meveo.elresolver.ELException) LoggerFactory(org.slf4j.LoggerFactory) RepositoryService(org.meveo.service.storage.RepositoryService) StringUtils(org.meveo.commons.utils.StringUtils) ScriptInstanceService(org.meveo.service.script.ScriptInstanceService) CustomEntityTemplateUniqueConstraint(org.meveo.model.crm.CustomEntityTemplateUniqueConstraint) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) Future(java.util.concurrent.Future) Repository(org.meveo.model.storage.Repository) Matcher(java.util.regex.Matcher) TransactionAttributeType(javax.ejb.TransactionAttributeType) MeveoJpa(org.meveo.jpa.MeveoJpa) Asynchronous(javax.ejb.Asynchronous) CustomFieldValue(org.meveo.model.crm.custom.CustomFieldValue) Map(java.util.Map) CETUtils(org.meveo.api.CETUtils) AsyncResult(javax.ejb.AsyncResult) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) Value(org.neo4j.driver.v1.Value) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApplicationProvider(org.meveo.util.ApplicationProvider) ElementNotFoundException(org.meveo.admin.exception.ElementNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) Neo4jRelationship(org.meveo.persistence.neo4j.graph.Neo4jRelationship) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Instant(java.time.Instant) Transaction(org.neo4j.driver.v1.Transaction) Collectors(java.util.stream.Collectors) Entity(javax.ws.rs.client.Entity) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) Node(org.neo4j.driver.v1.types.Node) List(java.util.List) Response(javax.ws.rs.core.Response) CustomFieldStorageTypeEnum(org.meveo.model.crm.custom.CustomFieldStorageTypeEnum) HttpURLConnection(org.apache.commons.httpclient.util.HttpURLConnection) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Entry(java.util.Map.Entry) CustomFieldsCacheContainerProvider(org.meveo.cache.CustomFieldsCacheContainerProvider) Optional(java.util.Optional) CustomEntityTemplateUtils(org.meveo.service.custom.CustomEntityTemplateUtils) Pattern(java.util.regex.Pattern) StatementResult(org.neo4j.driver.v1.StatementResult) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException) BusinessEntity(org.meveo.model.BusinessEntity) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) NODE_ID(org.meveo.persistence.neo4j.base.Neo4jDao.NODE_ID) EntityReferenceWrapper(org.meveo.model.crm.EntityReferenceWrapper) BasicAuthentication(org.jboss.resteasy.client.jaxrs.BasicAuthentication) PersistenceActionResult(org.meveo.persistence.PersistenceActionResult) HashMap(java.util.HashMap) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Updated(org.meveo.event.qualifier.Updated) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Record(org.neo4j.driver.v1.Record) HashSet(java.util.HashSet) Inject(javax.inject.Inject) JacksonUtil(org.meveo.model.persistence.JacksonUtil) Removed(org.meveo.event.qualifier.Removed) Provider(org.meveo.model.crm.Provider) CustomFieldTemplateService(org.meveo.service.crm.impl.CustomFieldTemplateService) MeveoValueExpressionWrapper(org.meveo.service.base.MeveoValueExpressionWrapper) TransactionAttribute(javax.ejb.TransactionAttribute) Neo4jDao(org.meveo.persistence.neo4j.base.Neo4jDao) Event(javax.enterprise.event.Event) InvalidCustomFieldException(org.meveo.exceptions.InvalidCustomFieldException) Logger(org.slf4j.Logger) DBStorageType(org.meveo.model.persistence.DBStorageType) Created(org.meveo.event.qualifier.Created) EntityManagerWrapper(org.meveo.jpa.EntityManagerWrapper) CustomFieldTypeEnum(org.meveo.model.crm.custom.CustomFieldTypeEnum) Neo4jEntity(org.meveo.persistence.neo4j.graph.Neo4jEntity) CustomFieldIndexTypeEnum(org.meveo.model.crm.custom.CustomFieldIndexTypeEnum) InternalNode(org.neo4j.driver.internal.InternalNode) Relationship(org.neo4j.driver.v1.types.Relationship) Comparator(java.util.Comparator) Collections(java.util.Collections) EntityRef(org.meveo.persistence.scheduler.EntityRef) Values(org.neo4j.driver.v1.Values) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CustomEntityTemplateUniqueConstraint(org.meveo.model.crm.CustomEntityTemplateUniqueConstraint) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate)

Example 97 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class Neo4jService method createEntityReferences.

/**
 * @param neo4JConfiguration
 * @param cet
 * @param fieldValues
 * @param cetFields
 * @param fields
 * @return
 * @throws BusinessException
 */
private Map<EntityRef, String> createEntityReferences(String neo4JConfiguration, CustomEntityTemplate cet, Map<String, Object> fieldValues, Map<String, CustomFieldTemplate> cetFields, Map<String, Object> fields) throws BusinessException {
    /* Collect entity references */
    final List<CustomFieldTemplate> entityReferences = cetFields.values().stream().filter(// Entity references
    customFieldTemplate -> customFieldTemplate.getFieldType().equals(CustomFieldTypeEnum.ENTITY)).filter(// Value is provided
    customFieldTemplate -> fieldValues.get(customFieldTemplate.getCode()) != null).collect(Collectors.toList());
    /* Create referenced nodes and collect relationships to create */
    // Map where the id of the target node is the key and the label of relationship is the value
    Map<EntityRef, String> relationshipsToCreate = new HashMap<>();
    for (CustomFieldTemplate entityReference : entityReferences) {
        Object referencedCetValue = fieldValues.get(entityReference.getCode());
        String referencedCetCode = entityReference.getEntityClazzCetCode();
        CustomEntityTemplate referencedCet = customFieldsCache.getCustomEntityTemplate(referencedCetCode);
        if (referencedCetValue instanceof EntityReferenceWrapper) {
            EntityReferenceWrapper wrapper = (EntityReferenceWrapper) referencedCetValue;
            if (wrapper.getUuid() == null) {
                continue;
            }
        }
        Collection<Object> values;
        if (entityReference.getStorageType().equals(CustomFieldStorageTypeEnum.LIST)) {
            if (!(referencedCetValue instanceof Collection)) {
                throw new BusinessException("Value for CFT " + entityReference.getCode() + " of CET " + cet.getCode() + " should be a collection");
            }
            values = ((Collection<Object>) referencedCetValue);
            if (referencedCet.getNeo4JStorageConfiguration() != null && referencedCet.getNeo4JStorageConfiguration().isPrimitiveEntity()) {
                fields.put(entityReference.getCode(), new ArrayList<>());
            }
        } else {
            values = Collections.singletonList(referencedCetValue);
        }
        for (Object value : values) {
            Set<EntityRef> relatedPersistedEntities = new HashSet<>();
            if (referencedCet.getNeo4JStorageConfiguration() != null && referencedCet.getNeo4JStorageConfiguration().isPrimitiveEntity()) {
                Map<String, Object> valueMap = new HashMap<>();
                valueMap.put("value", value);
                // If there is no unique constraints defined, directly merge node
                if (referencedCet.getNeo4JStorageConfiguration().getUniqueConstraints().isEmpty()) {
                    List<String> additionalLabels = getAdditionalLabels(referencedCet);
                    executePrePersist(neo4JConfiguration, referencedCet, valueMap);
                    String createdNodeId = neo4jDao.mergeNode(neo4JConfiguration, referencedCetCode, valueMap, valueMap, valueMap, additionalLabels, null);
                    if (createdNodeId != null) {
                        relatedPersistedEntities.add(new EntityRef(createdNodeId, referencedCet.getCode()));
                    }
                } else {
                    PersistenceActionResult persistenceResult = addCetNode(neo4JConfiguration, referencedCetCode, valueMap);
                    relatedPersistedEntities.addAll(persistenceResult.getPersistedEntities());
                }
                if (entityReference.getStorageType().equals(CustomFieldStorageTypeEnum.LIST)) {
                    ((List<Object>) fields.get(entityReference.getCode())).add(valueMap.get("value"));
                } else {
                    fields.put(entityReference.getCode(), valueMap.get("value"));
                }
            } else {
                // Referenced CET is not primitive
                if (value instanceof Map && referencedCet.getAvailableStorages().contains(DBStorageType.NEO4J)) {
                    Map<String, Object> valueMap = (Map<String, Object>) value;
                    PersistenceActionResult persistenceResult = addCetNode(neo4JConfiguration, referencedCet, valueMap);
                    relatedPersistedEntities.addAll(persistenceResult.getPersistedEntities());
                } else if (value instanceof String) {
                    // If entity reference's value is a string and the entity reference is not primitive, then the value is likely the UUID of the referenced node
                    handleUuidReference(neo4JConfiguration, cet, relationshipsToCreate, entityReference, referencedCet, value);
                } else if (value instanceof EntityReferenceWrapper) {
                    handleUuidReference(neo4JConfiguration, cet, relationshipsToCreate, entityReference, referencedCet, ((EntityReferenceWrapper) value).getUuid());
                } else if (value instanceof Collection) {
                    for (Object item : (Collection<?>) value) {
                        if (item instanceof String) {
                            handleUuidReference(neo4JConfiguration, cet, relationshipsToCreate, entityReference, referencedCet, value);
                        }
                    }
                } else if (referencedCet.getAvailableStorages().contains(DBStorageType.NEO4J)) {
                    throw new IllegalArgumentException("CET " + referencedCetCode + " should be a primitive entity");
                }
            }
            if (relatedPersistedEntities != null) {
                String relationshipName = Optional.ofNullable(entityReference.getRelationshipName()).orElseGet(() -> entityReference.getRelationship() != null ? entityReference.getRelationship().getName() : null);
                if (relationshipName == null) {
                    throw new BusinessException(entityReference.getAppliesTo() + "#" + entityReference.getCode() + ": Relationship name must be provided !");
                }
                for (EntityRef entityRef : relatedPersistedEntities) {
                    relationshipsToCreate.put(entityRef, relationshipName);
                }
            }
        }
    }
    return relationshipsToCreate;
}
Also used : CustomRelationshipTemplateService(org.meveo.service.custom.CustomRelationshipTemplateService) CrossStorageTransaction(org.meveo.persistence.CrossStorageTransaction) CustomPersistenceService(org.meveo.persistence.CustomPersistenceService) Date(java.util.Date) ELException(org.meveo.elresolver.ELException) LoggerFactory(org.slf4j.LoggerFactory) RepositoryService(org.meveo.service.storage.RepositoryService) StringUtils(org.meveo.commons.utils.StringUtils) ScriptInstanceService(org.meveo.service.script.ScriptInstanceService) CustomEntityTemplateUniqueConstraint(org.meveo.model.crm.CustomEntityTemplateUniqueConstraint) CustomRelationshipTemplate(org.meveo.model.customEntities.CustomRelationshipTemplate) Future(java.util.concurrent.Future) Repository(org.meveo.model.storage.Repository) Matcher(java.util.regex.Matcher) TransactionAttributeType(javax.ejb.TransactionAttributeType) MeveoJpa(org.meveo.jpa.MeveoJpa) Asynchronous(javax.ejb.Asynchronous) CustomFieldValue(org.meveo.model.crm.custom.CustomFieldValue) Map(java.util.Map) CETUtils(org.meveo.api.CETUtils) AsyncResult(javax.ejb.AsyncResult) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) Value(org.neo4j.driver.v1.Value) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApplicationProvider(org.meveo.util.ApplicationProvider) ElementNotFoundException(org.meveo.admin.exception.ElementNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap) CustomEntityInstance(org.meveo.model.customEntities.CustomEntityInstance) Neo4jRelationship(org.meveo.persistence.neo4j.graph.Neo4jRelationship) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Instant(java.time.Instant) Transaction(org.neo4j.driver.v1.Transaction) Collectors(java.util.stream.Collectors) Entity(javax.ws.rs.client.Entity) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) Node(org.neo4j.driver.v1.types.Node) List(java.util.List) Response(javax.ws.rs.core.Response) CustomFieldStorageTypeEnum(org.meveo.model.crm.custom.CustomFieldStorageTypeEnum) HttpURLConnection(org.apache.commons.httpclient.util.HttpURLConnection) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Entry(java.util.Map.Entry) CustomFieldsCacheContainerProvider(org.meveo.cache.CustomFieldsCacheContainerProvider) Optional(java.util.Optional) CustomEntityTemplateUtils(org.meveo.service.custom.CustomEntityTemplateUtils) Pattern(java.util.regex.Pattern) StatementResult(org.neo4j.driver.v1.StatementResult) NoSuchRecordException(org.neo4j.driver.v1.exceptions.NoSuchRecordException) BusinessEntity(org.meveo.model.BusinessEntity) PaginationConfiguration(org.meveo.admin.util.pagination.PaginationConfiguration) RemoteAuthenticationException(org.meveo.export.RemoteAuthenticationException) JpaAmpNewTx(org.meveo.jpa.JpaAmpNewTx) NODE_ID(org.meveo.persistence.neo4j.base.Neo4jDao.NODE_ID) EntityReferenceWrapper(org.meveo.model.crm.EntityReferenceWrapper) BasicAuthentication(org.jboss.resteasy.client.jaxrs.BasicAuthentication) PersistenceActionResult(org.meveo.persistence.PersistenceActionResult) HashMap(java.util.HashMap) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Updated(org.meveo.event.qualifier.Updated) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Record(org.neo4j.driver.v1.Record) HashSet(java.util.HashSet) Inject(javax.inject.Inject) JacksonUtil(org.meveo.model.persistence.JacksonUtil) Removed(org.meveo.event.qualifier.Removed) Provider(org.meveo.model.crm.Provider) CustomFieldTemplateService(org.meveo.service.crm.impl.CustomFieldTemplateService) MeveoValueExpressionWrapper(org.meveo.service.base.MeveoValueExpressionWrapper) TransactionAttribute(javax.ejb.TransactionAttribute) Neo4jDao(org.meveo.persistence.neo4j.base.Neo4jDao) Event(javax.enterprise.event.Event) InvalidCustomFieldException(org.meveo.exceptions.InvalidCustomFieldException) Logger(org.slf4j.Logger) DBStorageType(org.meveo.model.persistence.DBStorageType) Created(org.meveo.event.qualifier.Created) EntityManagerWrapper(org.meveo.jpa.EntityManagerWrapper) CustomFieldTypeEnum(org.meveo.model.crm.custom.CustomFieldTypeEnum) Neo4jEntity(org.meveo.persistence.neo4j.graph.Neo4jEntity) CustomFieldIndexTypeEnum(org.meveo.model.crm.custom.CustomFieldIndexTypeEnum) InternalNode(org.neo4j.driver.internal.InternalNode) Relationship(org.neo4j.driver.v1.types.Relationship) Comparator(java.util.Comparator) Collections(java.util.Collections) EntityRef(org.meveo.persistence.scheduler.EntityRef) Values(org.neo4j.driver.v1.Values) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) BusinessException(org.meveo.admin.exception.BusinessException) CustomEntityTemplate(org.meveo.model.customEntities.CustomEntityTemplate) EntityReferenceWrapper(org.meveo.model.crm.EntityReferenceWrapper) CustomFieldTemplate(org.meveo.model.crm.CustomFieldTemplate) Collection(java.util.Collection) PersistenceActionResult(org.meveo.persistence.PersistenceActionResult) List(java.util.List) ArrayList(java.util.ArrayList) EntityRef(org.meveo.persistence.scheduler.EntityRef) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 98 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class KeycloakAdminClientService method getUserRepresentationByUsername.

/**
 * As the search function from keycloack doesn't perform exact search, we need to browse results to pick the exact username
 *
 * @param usersResource Users resource
 * @param username Username
 * @return User information
 * @throws BusinessException business exception.
 * @author akadid abdelmounaim
 * @lastModifiedVersion 5.0
 */
public UserRepresentation getUserRepresentationByUsername(UsersResource usersResource, String username) throws BusinessException {
    UserRepresentation userRepresentation = null;
    List<UserRepresentation> userRepresentations = usersResource.search(username, null, null, null, null, null);
    for (UserRepresentation userRepresentationListItem : userRepresentations) {
        if (username.equalsIgnoreCase(userRepresentationListItem.getUsername())) {
            userRepresentation = userRepresentationListItem;
        }
    }
    if (userRepresentation == null) {
        throw new BusinessException("Unable to find user on keycloack.");
    }
    return userRepresentation;
}
Also used : BusinessException(org.meveo.admin.exception.BusinessException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 99 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class KeycloakAdminClientService method createUser.

/**
 * Creates a user in keycloak. Also assigns the role.
 *
 * @param httpServletRequest http request
 * @param postData posted data to API
 * @param provider provider code to be added as attribute
 * @return user created id.
 * @throws BusinessException business exception
 * @throws EntityDoesNotExistsException entity does not exist exception.
 * @lastModifiedVersion 5.0.1
 */
public String createUser(HttpServletRequest httpServletRequest, UserDto postData, String provider) throws BusinessException, EntityDoesNotExistsException {
    KeycloakSecurityContext session = (KeycloakSecurityContext) httpServletRequest.getAttribute(KeycloakSecurityContext.class.getName());
    KeycloakAdminClientConfig keycloakAdminClientConfig = loadConfig();
    Keycloak keycloak = getKeycloakClient(session, keycloakAdminClientConfig);
    // Define user
    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setEmailVerified(true);
    if (!StringUtils.isBlank(postData.getUsername())) {
        user.setUsername(postData.getUsername());
    } else {
        user.setUsername(postData.getEmail());
    }
    user.setFirstName(postData.getFirstName());
    user.setLastName(postData.getLastName());
    user.setEmail(postData.getEmail());
    Map<String, List<String>> attributes = new HashMap<>();
    attributes.put("origin", Collections.singletonList("OPENCELL-API"));
    if (ParamBean.isMultitenancyEnabled() && !StringUtils.isBlank(provider)) {
        attributes.put("provider", Collections.singletonList(provider));
    }
    user.setAttributes(attributes);
    // Get realm
    RealmResource realmResource = keycloak.realm(keycloakAdminClientConfig.getRealm());
    UsersResource usersResource = realmResource.users();
    // check if realm role exists
    // find realm roles and assign to the newly create user
    List<RoleRepresentation> externalRolesRepresentation = new ArrayList<>();
    if (postData.getExternalRoles() != null && !postData.getExternalRoles().isEmpty()) {
        RolesResource rolesResource = realmResource.roles();
        for (RoleDto externalRole : postData.getExternalRoles()) {
            try {
                RoleRepresentation tempRole = rolesResource.get(externalRole.getName()).toRepresentation();
                externalRolesRepresentation.add(tempRole);
            } catch (NotFoundException e) {
                throw new EntityDoesNotExistsException(RoleRepresentation.class, externalRole.getName());
            }
        }
    }
    // Create user (requires manage-users role)
    Response response = usersResource.create(user);
    if (response.getStatus() != Status.CREATED.getStatusCode()) {
        log.error("Keycloak user creation with http status.code={} and reason={}", response.getStatus(), response.getStatusInfo().getReasonPhrase());
        if (response.getStatus() == HttpStatus.SC_CONFLICT) {
            throw new BusinessException("Username or email already exists.");
        } else {
            throw new BusinessException("Unable to create user with httpStatusCode=" + response.getStatus());
        }
    }
    String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
    log.debug("User created with userId: {}", userId);
    usersResource.get(userId).roles().realmLevel().add(externalRolesRepresentation);
    ClientRepresentation meveoWebClient = // 
    realmResource.clients().findByClientId(keycloakAdminClientConfig.getClientId()).get(0);
    // Get client level role (requires view-clients role)
    RoleRepresentation apiRole = // 
    realmResource.clients().get(meveoWebClient.getId()).roles().get(KeycloakConstants.ROLE_API_ACCESS).toRepresentation();
    RoleRepresentation guiRole = // 
    realmResource.clients().get(meveoWebClient.getId()).roles().get(KeycloakConstants.ROLE_GUI_ACCESS).toRepresentation();
    RoleRepresentation adminRole = // 
    realmResource.clients().get(meveoWebClient.getId()).roles().get(KeycloakConstants.ROLE_ADMINISTRATEUR).toRepresentation();
    RoleRepresentation userManagementRole = // 
    realmResource.clients().get(meveoWebClient.getId()).roles().get(KeycloakConstants.ROLE_USER_MANAGEMENT).toRepresentation();
    // Assign client level role to user
    // 
    usersResource.get(userId).roles().clientLevel(meveoWebClient.getId()).add(Arrays.asList(apiRole, guiRole, adminRole, userManagementRole));
    // Define password credential
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setTemporary(false);
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(postData.getPassword());
    // Set password credential
    usersResource.get(userId).resetPassword(credential);
    return userId;
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RoleDto(org.meveo.api.dto.RoleDto) KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) HashMap(java.util.HashMap) RealmResource(org.keycloak.admin.client.resource.RealmResource) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Response(javax.ws.rs.core.Response) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) BusinessException(org.meveo.admin.exception.BusinessException) EntityDoesNotExistsException(org.meveo.api.exception.EntityDoesNotExistsException) UsersResource(org.keycloak.admin.client.resource.UsersResource) ArrayList(java.util.ArrayList) List(java.util.List) Keycloak(org.keycloak.admin.client.Keycloak) RolesResource(org.keycloak.admin.client.resource.RolesResource) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 100 with BusinessException

use of org.meveo.admin.exception.BusinessException in project meveo by meveo-org.

the class KeycloakAdminClientService method addToCompositeCrossClient.

/**
 * Add a role from target client to a composite role of an default client.
 * Both roles should already exists.
 *
 * @param clientTarget Id of the client holding the composite role
 * @param roleCompositeSource composite role of the default client=
 * @param roleTargetToAdd role of the target client to add
 * @throws BusinessException if the source composite role does not exists in default client
 */
public void addToCompositeCrossClient(String clientTarget, String roleCompositeSource, String roleTargetToAdd) throws BusinessException {
    KeycloakAdminClientConfig keycloakAdminClientConfig = loadConfig();
    final KeycloakPrincipal<?> callerPrincipal = (KeycloakPrincipal<?>) ctx.getCallerPrincipal();
    final KeycloakSecurityContext keycloakSecurityContext = callerPrincipal.getKeycloakSecurityContext();
    Keycloak keycloak = getKeycloakClient(keycloakSecurityContext, keycloakAdminClientConfig);
    final String defaultSourceClient = keycloak.realm(keycloakAdminClientConfig.getRealm()).clients().findByClientId(keycloakAdminClientConfig.getClientId()).get(0).getId();
    final String targetClient = keycloak.realm(keycloakAdminClientConfig.getRealm()).clients().findByClientId(clientTarget).get(0).getId();
    final RoleRepresentation roleToAdd;
    try {
        roleToAdd = keycloak.realm(keycloakAdminClientConfig.getRealm()).clients().get(targetClient).roles().get(roleTargetToAdd).toRepresentation();
    } catch (NotFoundException e) {
        throw new BusinessException("Role " + roleTargetToAdd + " does not exists in client " + clientTarget);
    }
    ClientResource defaultClient = keycloak.realm(keycloakAdminClientConfig.getRealm()).clients().get(defaultSourceClient);
    RoleResource roleResource = defaultClient.roles().get(roleCompositeSource);
    try {
        roleResource.addComposites(Collections.singletonList(roleToAdd));
    } catch (NotFoundException e) {
        throw new BusinessException("Role " + roleCompositeSource + " does not exists in client " + keycloakAdminClientConfig.getClientId());
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) BusinessException(org.meveo.admin.exception.BusinessException) KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) RoleResource(org.keycloak.admin.client.resource.RoleResource) NotFoundException(javax.ws.rs.NotFoundException) ClientResource(org.keycloak.admin.client.resource.ClientResource) Keycloak(org.keycloak.admin.client.Keycloak) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Aggregations

BusinessException (org.meveo.admin.exception.BusinessException)229 IOException (java.io.IOException)97 File (java.io.File)59 HashMap (java.util.HashMap)50 EntityDoesNotExistsException (org.meveo.api.exception.EntityDoesNotExistsException)50 ArrayList (java.util.ArrayList)48 MeveoApiException (org.meveo.api.exception.MeveoApiException)39 ELException (org.meveo.elresolver.ELException)39 CustomFieldTemplate (org.meveo.model.crm.CustomFieldTemplate)38 CustomEntityTemplate (org.meveo.model.customEntities.CustomEntityTemplate)37 Map (java.util.Map)34 BundleKey (org.jboss.seam.international.status.builder.BundleKey)30 TransactionAttribute (javax.ejb.TransactionAttribute)28 CustomEntityInstance (org.meveo.model.customEntities.CustomEntityInstance)27 List (java.util.List)25 MeveoModule (org.meveo.model.module.MeveoModule)25 NoResultException (javax.persistence.NoResultException)24 HashSet (java.util.HashSet)22 Response (javax.ws.rs.core.Response)22 Collection (java.util.Collection)20