Search in sources :

Example 81 with Entity

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);
}
Also used : Entity(io.jmix.core.Entity) MetaClass(io.jmix.core.metamodel.model.MetaClass) MetaProperty(io.jmix.core.metamodel.model.MetaProperty) Nullable(javax.annotation.Nullable)

Example 82 with Entity

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;
}
Also used : Entity(io.jmix.core.Entity) Query(com.haulmont.cuba.core.Query) ArrayList(java.util.ArrayList) View(com.haulmont.cuba.core.global.View) EntityManager(com.haulmont.cuba.core.EntityManager) MetaClass(io.jmix.core.metamodel.model.MetaClass) Transaction(com.haulmont.cuba.core.Transaction) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) MetaProperty(io.jmix.core.metamodel.model.MetaProperty)

Example 83 with Entity

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);
        }
    }
}
Also used : Categorized(io.jmix.dynattr.model.Categorized) Entity(io.jmix.core.Entity) MetadataTools(io.jmix.core.MetadataTools) UserSessionSource(com.haulmont.cuba.core.global.UserSessionSource) LockService(com.haulmont.cuba.core.app.LockService) LockNotSupported(io.jmix.core.pessimisticlocking.LockNotSupported) EntityStates(io.jmix.core.EntityStates) DatasourceImplementation(com.haulmont.cuba.gui.data.impl.DatasourceImplementation) Security(com.haulmont.cuba.core.global.Security) DynamicAttributesGuiTools(com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools) EntityAccessException(io.jmix.core.EntityAccessException) LockInfo(io.jmix.core.pessimisticlocking.LockInfo) CollectionPropertyDatasourceImpl(com.haulmont.cuba.gui.data.impl.CollectionPropertyDatasourceImpl)

Example 84 with Entity

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());
            }
        }
    }
}
Also used : Entity(io.jmix.core.Entity) ConstraintViolation(javax.validation.ConstraintViolation) Validator(javax.validation.Validator)

Example 85 with Entity

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());
        }
    }
}
Also used : Entity(io.jmix.core.Entity) LockService(com.haulmont.cuba.core.app.LockService)

Aggregations

Entity (io.jmix.core.Entity)94 MetaClass (io.jmix.core.metamodel.model.MetaClass)20 MetaProperty (io.jmix.core.metamodel.model.MetaProperty)18 CommitContext (com.haulmont.cuba.core.global.CommitContext)10 CoreTest (com.haulmont.cuba.core.testsupport.CoreTest)10 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)10 Test (org.junit.jupiter.api.Test)10 Server (com.haulmont.cuba.core.model.common.Server)8 Datasource (com.haulmont.cuba.gui.data.Datasource)8 Collectors (java.util.stream.Collectors)8 Autowired (org.springframework.beans.factory.annotation.Autowired)8 FetchPlan (io.jmix.core.FetchPlan)7 Logger (org.slf4j.Logger)7 Metadata (io.jmix.core.Metadata)6 MetadataTools (io.jmix.core.MetadataTools)6 EntityValues (io.jmix.core.entity.EntityValues)6 java.util (java.util)6 ArrayList (java.util.ArrayList)6 Nullable (javax.annotation.Nullable)6 LoggerFactory (org.slf4j.LoggerFactory)6