use of io.jmix.core.Entity in project jmix by jmix-framework.
the class EntityLoadInfoBuilder method parse.
/**
* Parse an info from the string.
*
* @param str string representation of the info. See {@link EntityLoadInfo} for formats.
* @return info instance or null if the string can not be parsed. Any exception is silently swallowed.
*/
@Nullable
public EntityLoadInfo parse(String str) {
boolean isNew = false;
if (str.startsWith(EntityLoadInfo.NEW_PREFIX)) {
str = str.substring("NEW-".length());
isNew = true;
}
int idDashPos = str.indexOf('-');
if (idDashPos == -1) {
if (isNew) {
MetaClass metaClass = metadata.getSession().findClass(str);
if (metaClass == null) {
return null;
}
Entity entity = (Entity) metadata.create(metaClass);
MetaProperty primaryKeyProp = metadataTools.getPrimaryKeyProperty(metaClass);
boolean stringKey = primaryKeyProp != null && primaryKeyProp.getJavaType().equals(String.class);
return new EntityLoadInfo(EntityValues.getId(entity), metaClass, null, stringKey, true);
}
return null;
}
String entityName = str.substring(0, idDashPos);
MetaClass metaClass = metadata.getSession().findClass(entityName);
if (metaClass == null) {
return null;
}
Object id;
String viewName;
boolean stringKey = false;
MetaProperty primaryKeyProp = metadataTools.getPrimaryKeyProperty(metaClass);
if (primaryKeyProp == null)
return null;
if (primaryKeyProp.getJavaType().equals(UUID.class)) {
int viewDashPos = -1;
int dashCount = StringUtils.countMatches(str, "-");
if (dashCount < 5) {
return null;
}
if (dashCount >= 6) {
int i = 0;
while (i < 6) {
viewDashPos = str.indexOf('-', viewDashPos + 1);
i++;
}
viewName = str.substring(viewDashPos + 1);
} else {
viewDashPos = str.length();
viewName = null;
}
String entityIdStr = str.substring(idDashPos + 1, viewDashPos);
try {
id = UuidProvider.fromString(entityIdStr);
} catch (Exception e) {
return null;
}
} else {
String entityIdStr;
if (primaryKeyProp.getJavaType().equals(String.class)) {
stringKey = true;
int viewDashPos = str.indexOf("}-", idDashPos + 2);
if (viewDashPos > -1) {
viewName = str.substring(viewDashPos + 2);
} else {
viewDashPos = str.length() - 1;
viewName = null;
}
entityIdStr = str.substring(idDashPos + 2, viewDashPos);
} else {
int viewDashPos = str.indexOf('-', idDashPos + 1);
if (viewDashPos > -1) {
viewName = str.substring(viewDashPos + 1);
} else {
viewDashPos = str.length();
viewName = null;
}
entityIdStr = str.substring(idDashPos + 1, viewDashPos);
}
try {
if (primaryKeyProp.getJavaType().equals(Long.class)) {
id = Long.valueOf(entityIdStr);
} else if (primaryKeyProp.getJavaType().equals(Integer.class)) {
id = Integer.valueOf(entityIdStr);
} else {
id = entityIdStr;
}
} catch (Exception e) {
return null;
}
}
return new EntityLoadInfo(id, metaClass, viewName, stringKey, isNew);
}
use of io.jmix.core.Entity in project jmix by jmix-framework.
the class RelatedEntitiesServiceBean method getRelatedIds.
@Override
public List<Object> getRelatedIds(List<Object> parentIds, String parentMetaClass, String relationProperty) {
checkNotNullArgument(parentIds, "parents argument is null");
checkNotNullArgument(parentMetaClass, "parentMetaClass argument is null");
checkNotNullArgument(relationProperty, "relationProperty argument is null");
MetaClass metaClass = extendedEntities.getEffectiveMetaClass(metadata.getClassNN(parentMetaClass));
Class<? extends Entity> parentClass = metaClass.getJavaClass();
MetaProperty metaProperty = metaClass.getProperty(relationProperty);
// return empty list only after all argument checks
if (parentIds.isEmpty()) {
return Collections.emptyList();
}
MetaClass propertyMetaClass = extendedEntities.getEffectiveMetaClass(metaProperty.getRange().asClass());
Class<? extends Entity> propertyClass = propertyMetaClass.getJavaClass();
List<Object> relatedIds = new ArrayList<>();
Transaction tx = persistence.createTransaction();
try {
EntityManager em = persistence.getEntityManager();
String parentPrimaryKey = metadata.getTools().getPrimaryKeyName(metaClass);
String queryString = "select x from " + parentMetaClass + " x where x." + parentPrimaryKey + " in :ids";
Query query = em.createQuery(queryString);
String relatedPrimaryKey = metadata.getTools().getPrimaryKeyName(propertyMetaClass);
View view = new View(parentClass);
view.addProperty(relationProperty, new View(propertyClass).addProperty(relatedPrimaryKey));
query.setView(view);
query.setParameter("ids", parentIds);
List resultList = query.getResultList();
for (Object obj : resultList) {
Entity e = (Entity) obj;
Object value = EntityValues.getValue(e, relationProperty);
if (value instanceof Entity) {
relatedIds.add(EntityValues.getId(value));
} else if (value instanceof Collection) {
for (Object collectionItem : (Collection) value) {
relatedIds.add(EntityValues.getId(collectionItem));
}
}
}
tx.commit();
} finally {
tx.end();
}
return relatedIds;
}
use of io.jmix.core.Entity in project jmix by jmix-framework.
the class AbstractEditor method setItemInternal.
@SuppressWarnings("unchecked")
protected void setItemInternal(Entity item) {
Datasource ds = getDatasourceInternal();
DataSupplier dataservice = ds.getDataSupplier();
DatasourceImplementation parentDs = (DatasourceImplementation) ((DatasourceImplementation) ds).getParent();
DynamicAttributesGuiTools dynamicAttributesGuiTools = (DynamicAttributesGuiTools) getApplicationContext().getBean(DynamicAttributesGuiTools.NAME);
if (dynamicAttributesGuiTools.screenContainsDynamicAttributes(ds.getView(), getFrame().getId())) {
ds.setLoadDynamicAttributes(true);
}
Class<? extends Entity> entityClass = item.getClass();
Object entityId = EntityValues.getId(item);
EntityStates entityStates = getApplicationContext().getBean(EntityStates.class);
if (parentDs != null) {
if (!PersistenceHelper.isNew(item) && !parentDs.getItemsToCreate().contains(item) && !parentDs.getItemsToUpdate().contains(item) && parentDs instanceof CollectionDatasource && ((CollectionDatasource) parentDs).containsItem(EntityValues.getId(item)) && !entityStates.isLoadedWithFetchPlan(item, ds.getView())) {
item = dataservice.reload(item, ds.getView(), ds.getMetaClass(), ds.getLoadDynamicAttributes());
if (parentDs instanceof CollectionPropertyDatasourceImpl) {
((CollectionPropertyDatasourceImpl) parentDs).replaceItem(item);
} else {
((CollectionDatasource) parentDs).updateItem(item);
}
}
item = EntityCopyUtils.copyCompositions(item);
handlePreviouslyDeletedCompositionItems(item, parentDs);
} else if (!PersistenceHelper.isNew(item)) {
item = dataservice.reload(item, ds.getView(), ds.getMetaClass(), ds.getLoadDynamicAttributes());
}
if (item == null) {
throw new EntityAccessException(metadata.getClassNN(entityClass), entityId);
}
if (PersistenceHelper.isNew(item) && !ds.getMetaClass().equals(metadata.getClass(item))) {
Entity newItem = ds.getDataSupplier().newInstance(ds.getMetaClass());
MetadataTools metadataTools = (MetadataTools) getApplicationContext().getBean(MetadataTools.class);
metadataTools.copy(item, newItem);
item = newItem;
}
if (ds.getLoadDynamicAttributes()) {
if (PersistenceHelper.isNew(item)) {
dynamicAttributesGuiTools.initDefaultAttributeValues(item, metadata.getClass(item));
}
if (item instanceof Categorized) {
dynamicAttributesGuiTools.listenCategoryChanges(ds);
}
}
ds.setItem(item);
if (PersistenceHelper.isNew(item)) {
// make sure that they will be saved on commit.
for (Datasource datasource : ds.getDsContext().getAll()) {
if (datasource instanceof NestedDatasource && ((NestedDatasource) datasource).getMaster() == ds) {
if (datasource.getItem() != null && PersistenceHelper.isNew(datasource.getItem()))
((DatasourceImplementation) datasource).modified(datasource.getItem());
}
}
}
((DatasourceImplementation) ds).setModified(false);
Security security = (Security) getApplicationContext().getBean(Security.NAME);
if (!PersistenceHelper.isNew(item)) {
if (security.isEntityOpPermitted(ds.getMetaClass(), EntityOp.UPDATE)) {
readOnlyDueToLock = false;
LockService lockService = (LockService) getApplicationContext().getBean(LockService.NAME);
LockInfo lockInfo = lockService.lock(getMetaClassForLocking(ds).getName(), EntityValues.getId(item).toString());
if (lockInfo == null) {
justLocked = true;
addAfterDetachListener(afterCloseEvent -> {
releaseLock();
});
} else if (!(lockInfo instanceof LockNotSupported)) {
UserSessionSource userSessionSource = (UserSessionSource) getApplicationContext().getBean(UserSessionSource.NAME);
Frame frame = (Frame) getFrame();
frame.getWindowManager().showNotification(messages.getMainMessage("entityLocked.msg"), String.format(messages.getMainMessage("entityLocked.desc"), lockInfo.getUsername(), Datatypes.getNN(Date.class).format(lockInfo.getSince(), userSessionSource.getLocale())), Frame.NotificationType.HUMANIZED);
readOnlyDueToLock = true;
showEnableEditingBtn = false;
setReadOnly(true);
}
} else {
showEnableEditingBtn = false;
setReadOnly(true);
}
}
}
use of io.jmix.core.Entity in project jmix by jmix-framework.
the class AbstractEditor method validateAdditionalRules.
public void validateAdditionalRules(ValidationErrors errors) {
// all previous validations return no errors
if (crossFieldValidate && errors.isEmpty()) {
Validator validator = getApplicationContext().getBean(Validator.class);
Set<ConstraintViolation<Entity>> violations = validator.validate(getItem(), UiCrossFieldChecks.class);
for (ConstraintViolation<Entity> violation : violations) {
if (Iterables.getLast(violation.getPropertyPath()).getKind() == ElementKind.BEAN) {
errors.add(violation.getMessage());
}
}
}
}
use of io.jmix.core.Entity in project jmix by jmix-framework.
the class AbstractEditor method releaseLock.
public void releaseLock() {
if (justLocked) {
Datasource ds = getDatasourceInternal();
Entity entity = ds.getItem();
if (entity != null) {
getApplicationContext().getBean(LockService.class).unlock(getMetaClassForLocking(ds).getName(), EntityValues.getId(entity).toString());
}
}
}
Aggregations