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);
}
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;
}
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;
}
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;
}
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());
}
}
Aggregations