Search in sources :

Example 51 with Entity

use of com.haulmont.cuba.core.entity.Entity in project cuba by cuba-platform.

the class BulkEditorWindow method init.

@Override
public void init(Map<String, Object> params) {
    super.init(params);
    String width = themeConstants.get("cuba.gui.BulkEditorWindow.width");
    String height = themeConstants.get("cuba.gui.BulkEditorWindow.height");
    getDialogOptions().setWidth(width).setHeight(height);
    checkNotNullArgument(metaClass);
    checkNotNullArgument(selected);
    if (StringUtils.isNotBlank(exclude)) {
        excludeRegex = Pattern.compile(exclude);
    }
    for (ManagedField managedField : getManagedFields(metaClass)) {
        managedFields.put(managedField.getFqn(), managedField);
    }
    View view = createView(metaClass);
    items = loadItems(view);
    dsContext = new DsContextImpl(dataSupplier);
    dsContext.setFrameContext(getDsContext().getFrameContext());
    setDsContext(dsContext);
    datasource = new DatasourceImpl<>();
    datasource.setup(dsContext, dataSupplier, metaClass.getName() + "Ds", metaClass, view);
    ((DatasourceImpl) datasource).valid();
    dsContext.register(datasource);
    createNestedEmbeddedDatasources(datasource, metaClass, "");
    Entity instance = metadata.create(metaClass);
    if (loadDynamicAttributes && (instance instanceof BaseGenericIdEntity)) {
        ((BaseGenericIdEntity) instance).setDynamicAttributes(new HashMap<>());
    }
    createEmbeddedFields(metaClass, instance, "");
    datasource.setItem(instance);
    datasource.setAllowCommit(false);
    createDataComponents();
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) DatasourceImpl(com.haulmont.cuba.gui.data.impl.DatasourceImpl) EmbeddedDatasourceImpl(com.haulmont.cuba.gui.data.impl.EmbeddedDatasourceImpl) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) DsContextImpl(com.haulmont.cuba.gui.data.impl.DsContextImpl)

Example 52 with Entity

use of com.haulmont.cuba.core.entity.Entity in project cuba by cuba-platform.

the class BulkEditorWindow method commitChanges.

protected void commitChanges() {
    List<String> fields = new ArrayList<>();
    for (Map.Entry<String, Field> fieldEntry : dataFields.entrySet()) {
        Field field = fieldEntry.getValue();
        if (isFieldChanged(field)) {
            fields.add(managedFields.get(fieldEntry.getKey()).getFqn());
        }
    }
    for (Map.Entry<String, Field> fieldEntry : dataFields.entrySet()) {
        Field field = fieldEntry.getValue();
        if (!field.isEnabled()) {
            for (Entity item : items) {
                ensureEmbeddedPropertyCreated(item, fieldEntry.getKey());
                item.setValueEx(fieldEntry.getKey(), null);
            }
        } else if (isFieldChanged(field)) {
            for (Entity item : items) {
                ensureEmbeddedPropertyCreated(item, fieldEntry.getKey());
                item.setValueEx(fieldEntry.getKey(), field.getValue());
            }
        }
    }
    Set<Entity> committed = dataSupplier.commit(new CommitContext(items));
    Logger logger = LoggerFactory.getLogger(BulkEditorWindow.class);
    logger.info("Applied bulk editing for {} entries of {}. Changed properties: {}", committed.size(), metaClass, StringUtils.join(fields, ", "));
    showNotification(formatMessage("bulk.successMessage", committed.size()), NotificationType.HUMANIZED);
    close(COMMIT_ACTION_ID);
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) Logger(org.slf4j.Logger)

Example 53 with Entity

use of com.haulmont.cuba.core.entity.Entity in project cuba by cuba-platform.

the class AttributeEditor method initFieldGroup.

protected void initFieldGroup() {
    attributeFieldGroup.addCustomField("defaultBoolean", new FieldGroup.CustomFieldGenerator() {

        @Override
        public Component generateField(Datasource datasource, String propertyId) {
            LookupField lookupField = factory.createComponent(LookupField.class);
            Map<String, Object> options = new TreeMap<>();
            options.put(datatypeFormatter.formatBoolean(true), true);
            options.put(datatypeFormatter.formatBoolean(false), false);
            lookupField.setOptionsMap(options);
            lookupField.setDatasource(attributeDs, "defaultBoolean");
            return lookupField;
        }
    });
    attributeFieldGroup.addCustomField("dataType", new FieldGroup.CustomFieldGenerator() {

        @Override
        public Component generateField(Datasource datasource, String propertyId) {
            dataTypeField = factory.createComponent(LookupField.class);
            Map<String, Object> options = new TreeMap<>();
            PropertyType[] types = PropertyType.values();
            for (PropertyType propertyType : types) {
                options.put(getMessage(propertyType.toString()), propertyType);
            }
            dataTypeField.setWidth(fieldWidth);
            dataTypeField.setNewOptionAllowed(false);
            dataTypeField.setRequired(true);
            dataTypeField.setRequiredMessage(getMessage("dataTypeRequired"));
            dataTypeField.setOptionsMap(options);
            dataTypeField.setCaption(getMessage("dataType"));
            dataTypeField.setFrame(frame);
            dataTypeField.setDatasource(datasource, propertyId);
            return dataTypeField;
        }
    });
    attributeFieldGroup.addCustomField("screen", new FieldGroup.CustomFieldGenerator() {

        @Override
        public Component generateField(Datasource datasource, String propertyId) {
            screenField = factory.createComponent(LookupField.class);
            screenField.setId("screenField");
            screenField.setCaption(getMessage("screen"));
            screenField.setWidth(fieldWidth);
            screenField.setRequired(true);
            screenField.setRequiredMessage(getMessage("entityScreenRequired"));
            screenField.setFrame(frame);
            screenField.setDatasource(datasource, propertyId);
            return screenField;
        }
    });
    attributeFieldGroup.addCustomField("entityClass", new FieldGroup.CustomFieldGenerator() {

        @Override
        public Component generateField(Datasource datasource, String propertyId) {
            entityTypeField = factory.createComponent(LookupField.class);
            entityTypeField.setId("entityClass");
            entityTypeField.setCaption(getMessage("entityType"));
            entityTypeField.setRequired(true);
            entityTypeField.setRequiredMessage(getMessage("entityTypeRequired"));
            entityTypeField.setWidth(fieldWidth);
            entityTypeField.setFrame(frame);
            Map<String, Object> options = new TreeMap<>();
            MetaClass entityType = null;
            for (MetaClass metaClass : metadataTools.getAllPersistentMetaClasses()) {
                if (!metadataTools.isSystemLevel(metaClass)) {
                    if (metadata.getTools().hasCompositePrimaryKey(metaClass) && !HasUuid.class.isAssignableFrom(metaClass.getJavaClass())) {
                        continue;
                    }
                    options.put(messageTools.getDetailedEntityCaption(metaClass), metaClass.getJavaClass().getName());
                    if (attribute != null && metaClass.getJavaClass().getName().equals(attribute.getEntityClass())) {
                        entityType = metaClass;
                    }
                }
            }
            entityTypeField.setOptionsMap(options);
            entityTypeField.setValue(entityType);
            entityTypeField.setDatasource(datasource, propertyId);
            return entityTypeField;
        }
    });
    attributeFieldGroup.addCustomField("defaultEntityId", (datasource, propertyId) -> {
        defaultEntityField = factory.createComponent(PickerField.class);
        defaultEntityField.setCaption(messages.getMessage(CategoryAttribute.class, "CategoryAttribute.defaultEntityId"));
        defaultEntityField.addValueChangeListener(e -> {
            Entity entity = (Entity) e.getValue();
            if (entity != null) {
                attribute.setObjectDefaultEntityId(referenceToEntitySupport.getReferenceId(entity));
            } else {
                attribute.setObjectDefaultEntityId(null);
            }
            ((AbstractDatasource) attributeDs).modified(attribute);
        });
        entityLookupAction = defaultEntityField.addLookupAction();
        defaultEntityField.addClearAction();
        return defaultEntityField;
    });
    attributeFieldGroup.addCustomField("enumeration", (datasource, propertyId) -> {
        enumerationListEditor = factory.createComponent(ListEditor.class);
        enumerationListEditor.setWidth("100%");
        enumerationListEditor.setItemType(ListEditor.ItemType.STRING);
        enumerationListEditor.setRequired(true);
        enumerationListEditor.setRequiredMessage(getMessage("enumRequired"));
        enumerationListEditor.addValueChangeListener(e -> {
            List<String> value = (List<String>) e.getValue();
            attribute.setEnumeration(Joiner.on(",").join(value));
        });
        if (localizedFrame != null) {
            enumerationListEditor.setEditorWindowId("localizedEnumerationWindow");
            enumerationListEditor.setEditorParamsSupplier(() -> ParamsMap.of("enumerationLocales", attribute.getEnumerationLocales()));
            enumerationListEditor.addEditorCloseListener(closeEvent -> {
                if (closeEvent.getActionId().equals(COMMIT_ACTION_ID)) {
                    LocalizedEnumerationWindow enumerationWindow = (LocalizedEnumerationWindow) closeEvent.getWindow();
                    attribute.setEnumerationLocales(enumerationWindow.getLocalizedValues());
                }
            });
        }
        return enumerationListEditor;
    });
    attributeFieldGroup.addCustomField("whereClause", (datasource, propertyId) -> {
        whereField = factory.createComponent(SourceCodeEditor.class);
        whereField.setDatasource(attributeDs, "whereClause");
        whereField.setWidth("100%");
        whereField.setHeight(themeConstants.get("cuba.gui.customConditionFrame.whereField.height"));
        whereField.setSuggester((source, text, cursorPosition) -> requestHint(whereField, text, cursorPosition));
        whereField.setHighlightActiveLine(false);
        whereField.setShowGutter(false);
        return whereField;
    });
    attributeFieldGroup.addCustomField("joinClause", (datasource, propertyId) -> {
        joinField = factory.createComponent(SourceCodeEditor.class);
        joinField.setDatasource(attributeDs, "joinClause");
        joinField.setWidth("100%");
        joinField.setHeight(themeConstants.get("cuba.gui.customConditionFrame.joinField.height"));
        joinField.setSuggester((source, text, cursorPosition) -> requestHint(joinField, text, cursorPosition));
        joinField.setHighlightActiveLine(false);
        joinField.setShowGutter(false);
        return joinField;
    });
    attributeFieldGroup.addCustomField("constraintWizard", (datasource, propertyId) -> {
        HBoxLayout hbox = factory.createComponent(HBoxLayout.class);
        hbox.setWidth("100%");
        LinkButton linkButton = factory.createComponent(LinkButton.class);
        linkButton.setAction(new BaseAction("constraintWizard").withHandler(event -> openConstraintWizard()));
        linkButton.setCaption(getMessage("constraintWizard"));
        linkButton.setAlignment(Alignment.MIDDLE_LEFT);
        hbox.add(linkButton);
        return hbox;
    });
    attributeDs.addItemPropertyChangeListener(e -> {
        String property = e.getProperty();
        CategoryAttribute attribute = getItem();
        if ("dataType".equalsIgnoreCase(property) || "lookup".equalsIgnoreCase(property) || "defaultDateIsCurrent".equalsIgnoreCase(property) || "entityClass".equalsIgnoreCase(property)) {
            setupVisibility();
        }
        if ("name".equalsIgnoreCase(property)) {
            fillAttributeCode();
        }
        if ("screen".equalsIgnoreCase(property) || "joinClause".equals(property) || "whereClause".equals(property)) {
            dynamicAttributesGuiTools.initEntityPickerField(defaultEntityField, attribute);
        }
    });
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) StrBuilder(org.apache.commons.lang.text.StrBuilder) StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) WindowManager(com.haulmont.cuba.gui.WindowManager) Datasource(com.haulmont.cuba.gui.data.Datasource) DynamicAttributesGuiTools(com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools) Dom4j(com.haulmont.bali.util.Dom4j) ParamsMap(com.haulmont.bali.util.ParamsMap) Multimap(com.google.common.collect.Multimap) MetaClass(com.haulmont.chile.core.model.MetaClass) FakeFilterSupport(com.haulmont.cuba.gui.components.filter.FakeFilterSupport) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) AbstractDatasource(com.haulmont.cuba.gui.data.impl.AbstractDatasource) DatasourceImplementation(com.haulmont.cuba.gui.data.impl.DatasourceImplementation) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) FilterEditor(com.haulmont.cuba.gui.components.filter.edit.FilterEditor) Lists(com.google.common.collect.Lists) FilterParser(com.haulmont.cuba.gui.components.filter.FilterParser) HasUuid(com.haulmont.cuba.core.entity.HasUuid) JpqlSuggestionFactory(com.haulmont.cuba.gui.components.autocomplete.JpqlSuggestionFactory) ComponentsFactory(com.haulmont.cuba.gui.xml.layout.ComponentsFactory) CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) BaseAction(com.haulmont.cuba.gui.components.actions.BaseAction) Splitter(com.google.common.base.Splitter) com.haulmont.cuba.gui.components(com.haulmont.cuba.gui.components) ScreensHelper(com.haulmont.cuba.gui.ScreensHelper) FilterEntity(com.haulmont.cuba.security.entity.FilterEntity) Sets(com.google.common.collect.Sets) RemoveAction(com.haulmont.cuba.gui.components.actions.RemoveAction) String.format(java.lang.String.format) ConditionsTree(com.haulmont.cuba.gui.components.filter.ConditionsTree) Suggestion(com.haulmont.cuba.gui.components.autocomplete.Suggestion) ThemeConstants(com.haulmont.cuba.gui.theme.ThemeConstants) Param(com.haulmont.cuba.gui.components.filter.Param) SecurityJpqlGenerator(com.haulmont.cuba.core.global.filter.SecurityJpqlGenerator) Element(org.dom4j.Element) PropertyType(com.haulmont.cuba.core.app.dynamicattributes.PropertyType) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Joiner(com.google.common.base.Joiner) Entity(com.haulmont.cuba.core.entity.Entity) FilterEntity(com.haulmont.cuba.security.entity.FilterEntity) Entity(com.haulmont.cuba.core.entity.Entity) PropertyType(com.haulmont.cuba.core.app.dynamicattributes.PropertyType) HasUuid(com.haulmont.cuba.core.entity.HasUuid) Datasource(com.haulmont.cuba.gui.data.Datasource) AbstractDatasource(com.haulmont.cuba.gui.data.impl.AbstractDatasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) AbstractDatasource(com.haulmont.cuba.gui.data.impl.AbstractDatasource) BaseAction(com.haulmont.cuba.gui.components.actions.BaseAction) CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) MetaClass(com.haulmont.chile.core.model.MetaClass) ParamsMap(com.haulmont.bali.util.ParamsMap)

Example 54 with Entity

use of com.haulmont.cuba.core.entity.Entity in project cuba by cuba-platform.

the class AttributeEditor method fillDefaultEntities.

@SuppressWarnings("unchecked")
protected void fillDefaultEntities(Class entityClass) {
    MetaClass metaClass = metadata.getClassNN(entityClass);
    if (attribute.getObjectDefaultEntityId() != null) {
        LoadContext<Entity> lc = new LoadContext<>(entityClass).setView(View.MINIMAL);
        String pkName = referenceToEntitySupport.getPrimaryKeyForLoadingEntity(metaClass);
        lc.setQueryString(format("select e from %s e where e.%s = :entityId", metaClass.getName(), pkName)).setParameter("entityId", attribute.getObjectDefaultEntityId());
        Entity entity = dataManager.load(lc);
        if (entity != null) {
            defaultEntityField.setValue(entity);
        } else {
            defaultEntityField.setValue(null);
        }
    }
}
Also used : FilterEntity(com.haulmont.cuba.security.entity.FilterEntity) Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass)

Example 55 with Entity

use of com.haulmont.cuba.core.entity.Entity in project cuba by cuba-platform.

the class AppPropertiesLocator method setDataType.

private void setDataType(Method method, AppPropertyEntity entity) {
    Class<?> returnType = method.getReturnType();
    if (returnType.isPrimitive()) {
        if (returnType == boolean.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Boolean.class));
        if (returnType == int.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Integer.class));
        if (returnType == long.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Long.class));
        if (returnType == double.class || returnType == float.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Double.class));
    } else if (returnType.isEnum()) {
        entity.setDataTypeName("enum");
        EnumStore enumStoreAnn = method.getAnnotation(EnumStore.class);
        if (enumStoreAnn != null && enumStoreAnn.value() == EnumStoreMode.ID) {
            // noinspection unchecked
            Class<EnumClass> enumeration = (Class<EnumClass>) returnType;
            entity.setEnumValues(Arrays.asList(enumeration.getEnumConstants()).stream().map(ec -> String.valueOf(ec.getId())).collect(Collectors.joining(",")));
        } else {
            entity.setEnumValues(Arrays.asList(returnType.getEnumConstants()).stream().map(Object::toString).collect(Collectors.joining(",")));
        }
    } else {
        Datatype<?> datatype = datatypes.get(returnType);
        if (datatype != null)
            entity.setDataTypeName(datatypes.getId(datatype));
        else
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
    }
    String dataTypeName = entity.getDataTypeName();
    if (!dataTypeName.equals("enum")) {
        Datatype datatype = Datatypes.get(dataTypeName);
        String v = null;
        try {
            v = entity.getDefaultValue();
            datatype.parse(v);
            v = entity.getCurrentValue();
            datatype.parse(v);
        } catch (ParseException e) {
            log.debug("Cannot parse '{}' with {} datatype, using StringDatatype for property {}", v, datatype, entity.getName());
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
        }
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) ReflectionHelper(com.haulmont.bali.util.ReflectionHelper) LoggerFactory(org.slf4j.LoggerFactory) ClassMetadata(org.springframework.core.type.ClassMetadata) DatatypeRegistry(com.haulmont.chile.core.datatypes.DatatypeRegistry) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) Inject(javax.inject.Inject) Datatype(com.haulmont.chile.core.datatypes.Datatype) MetadataReader(org.springframework.core.type.classreading.MetadataReader) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) ParseException(java.text.ParseException) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Resource(org.springframework.core.io.Resource) com.haulmont.cuba.core.config.type(com.haulmont.cuba.core.config.type) Logger(org.slf4j.Logger) Datatypes(com.haulmont.chile.core.datatypes.Datatypes) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Component(org.springframework.stereotype.Component) MetadataReaderFactory(org.springframework.core.type.classreading.MetadataReaderFactory) com.haulmont.cuba.core.config.defaults(com.haulmont.cuba.core.config.defaults) AppContext(com.haulmont.cuba.core.sys.AppContext) ResourcePatternResolver(org.springframework.core.io.support.ResourcePatternResolver) Entity(com.haulmont.cuba.core.entity.Entity) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) ParseException(java.text.ParseException) Datatype(com.haulmont.chile.core.datatypes.Datatype)

Aggregations

Entity (com.haulmont.cuba.core.entity.Entity)203 MetaClass (com.haulmont.chile.core.model.MetaClass)51 MetaProperty (com.haulmont.chile.core.model.MetaProperty)44 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)40 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)18 Test (org.junit.Test)15 Inject (javax.inject.Inject)14 java.util (java.util)12 EntityManager (com.haulmont.cuba.core.EntityManager)11 ParseException (java.text.ParseException)11 Element (org.dom4j.Element)11 Logger (org.slf4j.Logger)11 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)10 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)9 LoggerFactory (org.slf4j.LoggerFactory)9 Query (com.haulmont.cuba.core.Query)8 Server (com.haulmont.cuba.core.entity.Server)8 Transaction (com.haulmont.cuba.core.Transaction)7 Datasource (com.haulmont.cuba.gui.data.Datasource)7 Collectors (java.util.stream.Collectors)7