Search in sources :

Example 21 with CollectionDatasource

use of com.haulmont.cuba.gui.data.CollectionDatasource in project cuba by cuba-platform.

the class ConstraintEditor method testConstraint.

public void testConstraint() {
    Constraint constraint = getItem();
    String entityName = constraint.getEntityName();
    if (validateAll()) {
        if (!Strings.isNullOrEmpty(constraint.getWhereClause())) {
            String baseQueryString = "select e from " + entityName + " e";
            try {
                QueryTransformer transformer = QueryTransformerFactory.createTransformer(baseQueryString);
                if (StringUtils.isNotBlank(constraint.getJoinClause())) {
                    transformer.addJoinAndWhere(constraint.getJoinClause(), constraint.getWhereClause());
                } else {
                    transformer.addWhere(constraint.getWhereClause());
                }
                CollectionDatasource datasource = DsBuilder.create().setMetaClass(metadata.getSession().getClassNN(entityName)).setMaxResults(0).buildCollectionDatasource();
                datasource.setQuery(transformer.getResult());
                datasource.refresh();
            } catch (JpqlSyntaxException e) {
                StringBuilder stringBuilder = new StringBuilder();
                for (ErrorRec rec : e.getErrorRecs()) {
                    stringBuilder.append(rec.toString()).append("<br>");
                }
                showMessageDialog(getMessage("notification.error"), formatMessage("notification.syntaxErrors", stringBuilder), MessageType.WARNING_HTML);
                return;
            } catch (Exception e) {
                String msg;
                Throwable rootCause = ExceptionUtils.getRootCause(e);
                if (rootCause == null)
                    rootCause = e;
                if (rootCause instanceof RemoteException) {
                    List<RemoteException.Cause> causes = ((RemoteException) rootCause).getCauses();
                    RemoteException.Cause cause = causes.get(causes.size() - 1);
                    msg = cause.getThrowable() != null ? cause.getThrowable().toString() : cause.getClassName() + ": " + cause.getMessage();
                } else {
                    msg = rootCause.toString();
                }
                showMessageDialog(getMessage("notification.error"), formatMessage("notification.runtimeError", msg), MessageType.WARNING_HTML);
                return;
            }
        }
        if (!Strings.isNullOrEmpty(constraint.getGroovyScript())) {
            try {
                security.evaluateConstraintScript(metadata.create(entityName), constraint.getGroovyScript());
            } catch (CompilationFailedException e) {
                showMessageDialog(getMessage("notification.error"), formatMessage("notification.scriptCompilationError", e.toString()), MessageType.WARNING_HTML);
                return;
            } catch (Exception e) {
            // ignore
            }
        }
        showNotification(getMessage("notification.success"), NotificationType.HUMANIZED);
    }
}
Also used : Constraint(com.haulmont.cuba.security.entity.Constraint) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) JpqlSyntaxException(com.haulmont.cuba.core.sys.jpql.JpqlSyntaxException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) ErrorRec(com.haulmont.cuba.core.sys.jpql.ErrorRec) JpqlSyntaxException(com.haulmont.cuba.core.sys.jpql.JpqlSyntaxException) Arrays.asList(java.util.Arrays.asList)

Example 22 with CollectionDatasource

use of com.haulmont.cuba.gui.data.CollectionDatasource in project cuba by cuba-platform.

the class GroupBrowser method init.

@Override
public void init(final Map<String, Object> params) {
    CreateAction createAction = new CreateAction(groupsTree);
    createAction.setAfterCommitHandler(entity -> {
        groupsTree.expandTree();
    });
    groupsTree.addAction(createAction);
    createAction.setCaption(getMessage("action.create"));
    createAction.setOpenType(OpenType.DIALOG);
    EditAction groupEditAction = new EditAction(groupsTree);
    groupEditAction.setAfterCommitHandler(entity -> {
        groupsTree.expandTree();
    });
    groupEditAction.setOpenType(OpenType.DIALOG);
    groupsTree.addAction(groupEditAction);
    groupCreateButton.addAction(createAction);
    groupCreateButton.addAction(groupCopyAction);
    userCreateAction = new GroupPropertyCreateAction(usersTable);
    userCreateAction.setAfterCommitHandler(entity -> {
        usersTable.getDatasource().refresh();
    });
    groupsTree.addAction(new RemoveAction(groupsTree) {

        @Override
        protected boolean isApplicable() {
            if (target != null && target.getDatasource() != null && target.getSingleSelected() != null) {
                @SuppressWarnings("unchecked") HierarchicalDatasource<Group, UUID> ds = (HierarchicalDatasource<Group, UUID>) target.getDatasource();
                UUID selectedItemId = (UUID) target.getSingleSelected().getId();
                return ds.getChildren(selectedItemId).isEmpty();
            }
            return false;
        }
    });
    usersTable.addAction(userCreateAction);
    RemoveAction removeAction = new UserRemoveAction(usersTable, userManagementService);
    usersTable.addAction(removeAction);
    Action moveToGroupAction = new ItemTrackingAction("moveToGroup").withIcon("icons/move.png").withCaption(getMessage("moveToGroup")).withHandler(event -> {
        Set<User> selected = usersTable.getSelected();
        if (!selected.isEmpty()) {
            Map<String, Object> lookupParams = ParamsMap.of("exclude", groupsTree.getSelected().iterator().next(), "excludeChildren", false);
            Lookup lookupWindow = openLookup(Group.class, items -> {
                if (items.size() == 1) {
                    Group group = (Group) items.iterator().next();
                    List<UUID> usersForModify = new ArrayList<>();
                    for (User user : selected) {
                        usersForModify.add(user.getId());
                    }
                    userManagementService.moveUsersToGroup(usersForModify, group.getId());
                    if (selected.size() == 1) {
                        User user = selected.iterator().next();
                        showNotification(formatMessage("userMovedToGroup", user.getLogin(), group.getName()));
                    } else {
                        showNotification(formatMessage("usersMovedToGroup", group.getName()));
                    }
                    usersTable.getDatasource().refresh();
                }
            }, OpenType.DIALOG, lookupParams);
            lookupWindow.addCloseListener(actionId -> {
                usersTable.requestFocus();
            });
        }
    });
    MetaClass userMetaClass = metadata.getSession().getClass(User.class);
    moveToGroupAction.setEnabled(security.isEntityOpPermitted(userMetaClass, EntityOp.UPDATE));
    usersTable.addAction(moveToGroupAction);
    tabsheet.addListener(newTab -> {
        if ("constraintsTab".equals(newTab.getName())) {
            initConstraintsTab();
        } else if ("attributesTab".equals(newTab.getName())) {
            initAttributesTab();
        }
    });
    final boolean hasPermissionsToCreateGroup = security.isEntityOpPermitted(metadata.getSession().getClass(Group.class), EntityOp.CREATE);
    // enable actions if group is selected
    groupsDs.addItemChangeListener(e -> {
        if (userCreateAction != null) {
            userCreateAction.setEnabled(e.getItem() != null);
        }
        if (attributeCreateAction != null) {
            attributeCreateAction.setEnabled(e.getItem() != null);
        }
        if (constraintCreateAction != null) {
            constraintCreateAction.setEnabled(e.getItem() != null);
        }
        groupCopyAction.setEnabled(hasPermissionsToCreateGroup && e.getItem() != null);
        CollectionDatasource ds = usersTable.getDatasource();
        if (ds instanceof CollectionDatasource.SupportsPaging) {
            ((CollectionDatasource.SupportsPaging) ds).setFirstResult(0);
        }
    });
    groupsDs.refresh();
    groupsTree.expandTree();
    final Collection<UUID> itemIds = groupsDs.getRootItemIds();
    if (!itemIds.isEmpty()) {
        groupsTree.setSelected(groupsDs.getItem(itemIds.iterator().next()));
    }
    groupCreateButton.setEnabled(hasPermissionsToCreateGroup);
    groupCopyAction.setEnabled(hasPermissionsToCreateGroup);
    importUpload.addFileUploadSucceedListener(event -> {
        File file = fileUploadingAPI.getFile(importUpload.getFileId());
        if (file == null) {
            String errorMsg = String.format("Entities import upload error. File with id %s not found", importUpload.getFileId());
            throw new RuntimeException(errorMsg);
        }
        byte[] fileBytes;
        try (InputStream is = new FileInputStream(file)) {
            fileBytes = IOUtils.toByteArray(is);
        } catch (IOException e) {
            throw new RuntimeException("Unable to import file", e);
        }
        try {
            fileUploadingAPI.deleteFile(importUpload.getFileId());
        } catch (FileStorageException e) {
            log.error("Unable to delete temp file", e);
        }
        try {
            Collection<Entity> importedEntities;
            if ("json".equals(Files.getFileExtension(importUpload.getFileName()))) {
                importedEntities = entityImportExportService.importEntitiesFromJSON(new String(fileBytes), createGroupsImportView());
            } else {
                importedEntities = entityImportExportService.importEntitiesFromZIP(fileBytes, createGroupsImportView());
            }
            long importedGroupsCount = importedEntities.stream().filter(entity -> entity instanceof Group).count();
            showNotification(importedGroupsCount + " groups imported", NotificationType.HUMANIZED);
            groupsDs.refresh();
        } catch (Exception e) {
            showNotification(formatMessage("importError", e.getMessage()), NotificationType.ERROR);
        }
    });
    Companion companion = getCompanion();
    if (companion != null) {
        companion.initDragAndDrop(usersTable, groupsTree, (event) -> {
            if (event.getUsers().size() == 1) {
                if (moveSelectedUsersToGroup(event)) {
                    showNotification(formatMessage("userMovedToGroup", event.getUsers().get(0).getLogin(), event.getGroup().getName()));
                }
            } else {
                showOptionDialog(messages.getMainMessage("dialogs.Confirmation"), formatMessage("dialogs.moveToGroup.message", event.getGroup().getName(), event.getUsers().size()), MessageType.CONFIRMATION, new Action[] { new DialogAction(Type.OK).withHandler(dialogEvent -> {
                    if (moveSelectedUsersToGroup(event)) {
                        showNotification(formatMessage("usersMovedToGroup", event.getGroup().getName()));
                    }
                }), new DialogAction(Type.CANCEL, Action.Status.PRIMARY) });
            }
        });
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) ReferenceImportBehaviour(com.haulmont.cuba.core.app.importexport.ReferenceImportBehaviour) LoggerFactory(org.slf4j.LoggerFactory) ParamsMap(com.haulmont.bali.util.ParamsMap) MetaClass(com.haulmont.chile.core.model.MetaClass) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) CreateAction(com.haulmont.cuba.gui.components.actions.CreateAction) Inject(javax.inject.Inject) ComponentsFactory(com.haulmont.cuba.gui.xml.layout.ComponentsFactory) Files(com.google.common.io.Files) CollectionImportPolicy(com.haulmont.cuba.core.app.importexport.CollectionImportPolicy) UserRemoveAction(com.haulmont.cuba.gui.app.security.user.browse.UserRemoveAction) ExportFormat(com.haulmont.cuba.gui.export.ExportFormat) Named(javax.inject.Named) com.haulmont.cuba.gui.components(com.haulmont.cuba.gui.components) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) OpenType(com.haulmont.cuba.gui.WindowManager.OpenType) Logger(org.slf4j.Logger) EntityImportExportService(com.haulmont.cuba.core.app.importexport.EntityImportExportService) ExportDisplay(com.haulmont.cuba.gui.export.ExportDisplay) com.haulmont.cuba.security.entity(com.haulmont.cuba.security.entity) Type(com.haulmont.cuba.gui.components.DialogAction.Type) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) EditAction(com.haulmont.cuba.gui.components.actions.EditAction) UserManagementService(com.haulmont.cuba.security.app.UserManagementService) Collectors(java.util.stream.Collectors) RemoveAction(com.haulmont.cuba.gui.components.actions.RemoveAction) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) EntityImportView(com.haulmont.cuba.core.app.importexport.EntityImportView) Consumer(java.util.function.Consumer) IOUtils(org.apache.commons.io.IOUtils) ByteArrayDataProvider(com.haulmont.cuba.gui.export.ByteArrayDataProvider) HierarchicalDatasource(com.haulmont.cuba.gui.data.HierarchicalDatasource) FileUploadingAPI(com.haulmont.cuba.gui.upload.FileUploadingAPI) ConstraintLocalizationService(com.haulmont.cuba.core.app.ConstraintLocalizationService) BaseUuidEntity(com.haulmont.cuba.core.entity.BaseUuidEntity) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Entity(com.haulmont.cuba.core.entity.Entity) InputStream(java.io.InputStream) BaseUuidEntity(com.haulmont.cuba.core.entity.BaseUuidEntity) Entity(com.haulmont.cuba.core.entity.Entity) CreateAction(com.haulmont.cuba.gui.components.actions.CreateAction) UserRemoveAction(com.haulmont.cuba.gui.app.security.user.browse.UserRemoveAction) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) EditAction(com.haulmont.cuba.gui.components.actions.EditAction) RemoveAction(com.haulmont.cuba.gui.components.actions.RemoveAction) UserRemoveAction(com.haulmont.cuba.gui.app.security.user.browse.UserRemoveAction) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) EditAction(com.haulmont.cuba.gui.components.actions.EditAction) CreateAction(com.haulmont.cuba.gui.components.actions.CreateAction) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) HierarchicalDatasource(com.haulmont.cuba.gui.data.HierarchicalDatasource) MetaClass(com.haulmont.chile.core.model.MetaClass) UserRemoveAction(com.haulmont.cuba.gui.app.security.user.browse.UserRemoveAction) RemoveAction(com.haulmont.cuba.gui.components.actions.RemoveAction) File(java.io.File)

Example 23 with CollectionDatasource

use of com.haulmont.cuba.gui.data.CollectionDatasource in project cuba by cuba-platform.

the class DataGridEditorComponentGenerationStrategy method createEntityField.

@Override
protected Field createEntityField(ComponentGenerationContext context, MetaPropertyPath mpp) {
    CollectionDatasource optionsDatasource = null;
    if (DynamicAttributesUtils.isDynamicAttribute(mpp.getMetaProperty())) {
        DynamicAttributesMetaProperty metaProperty = (DynamicAttributesMetaProperty) mpp.getMetaProperty();
        CategoryAttribute attribute = metaProperty.getAttribute();
        if (Boolean.TRUE.equals(attribute.getLookup())) {
            DynamicAttributesGuiTools dynamicAttributesGuiTools = AppBeans.get(DynamicAttributesGuiTools.class);
            optionsDatasource = dynamicAttributesGuiTools.createOptionsDatasourceForLookup(metaProperty.getRange().asClass(), attribute.getJoinClause(), attribute.getWhereClause());
        }
    }
    PickerField pickerField;
    if (optionsDatasource == null) {
        pickerField = componentsFactory.createComponent(PickerField.class);
        setDatasource(pickerField, context);
        pickerField.addLookupAction();
        if (DynamicAttributesUtils.isDynamicAttribute(mpp.getMetaProperty())) {
            DynamicAttributesGuiTools dynamicAttributesGuiTools = AppBeans.get(DynamicAttributesGuiTools.class);
            DynamicAttributesMetaProperty dynamicAttributesMetaProperty = (DynamicAttributesMetaProperty) mpp.getMetaProperty();
            dynamicAttributesGuiTools.initEntityPickerField(pickerField, dynamicAttributesMetaProperty.getAttribute());
        }
        PickerField.LookupAction lookupAction = (PickerField.LookupAction) pickerField.getActionNN(PickerField.LookupAction.NAME);
        // Opening lookup screen in another mode will close editor
        lookupAction.setLookupScreenOpenType(WindowManager.OpenType.DIALOG);
        // In case of adding special logic for lookup screen opened from DataGrid editor
        lookupAction.setLookupScreenParams(ParamsMap.of("dataGridEditor", true));
        boolean actionsByMetaAnnotations = ComponentsHelper.createActionsByMetaAnnotations(pickerField);
        if (!actionsByMetaAnnotations) {
            pickerField.addClearAction();
        }
    } else {
        LookupPickerField lookupPickerField = componentsFactory.createComponent(LookupPickerField.class);
        setDatasource(lookupPickerField, context);
        lookupPickerField.setOptionsDatasource(optionsDatasource);
        pickerField = lookupPickerField;
        ComponentsHelper.createActionsByMetaAnnotations(pickerField);
    }
    return pickerField;
}
Also used : CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) DynamicAttributesMetaProperty(com.haulmont.cuba.core.app.dynamicattributes.DynamicAttributesMetaProperty) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) DynamicAttributesGuiTools(com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools)

Example 24 with CollectionDatasource

use of com.haulmont.cuba.gui.data.CollectionDatasource in project cuba by cuba-platform.

the class EntityCombinedScreen method initBrowseEditAction.

/**
 * Adds an EditAction that enables controls for editing.
 */
protected void initBrowseEditAction() {
    ListComponent table = getTable();
    table.addAction(new EditAction(table) {

        @Override
        public void actionPerform(Component component) {
            if (table.getSelected().size() == 1) {
                if (lockIfNeeded((Entity) table.getSelected().iterator().next())) {
                    super.actionPerform(component);
                }
            }
        }

        @Override
        protected void internalOpenEditor(CollectionDatasource datasource, Entity existingItem, Datasource parentDs, Map<String, Object> params) {
            refreshOptionsForLookupFields();
            enableEditControls(false);
        }

        @Override
        public void refreshState() {
            if (target != null) {
                CollectionDatasource ds = target.getDatasource();
                if (ds != null && !captionInitialized) {
                    setCaption(messages.getMainMessage("actions.Edit"));
                }
            }
            super.refreshState();
        }

        @Override
        protected boolean isPermitted() {
            CollectionDatasource ownerDatasource = target.getDatasource();
            boolean entityOpPermitted = security.isEntityOpPermitted(ownerDatasource.getMetaClass(), EntityOp.UPDATE);
            if (!entityOpPermitted) {
                return false;
            }
            return super.isPermitted();
        }
    });
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Entity(com.haulmont.cuba.core.entity.Entity) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) EditAction(com.haulmont.cuba.gui.components.actions.EditAction)

Example 25 with CollectionDatasource

use of com.haulmont.cuba.gui.data.CollectionDatasource in project cuba by cuba-platform.

the class EntityCombinedScreen method cancel.

/**
 * Method that is invoked by clicking Cancel button, discards changes and disables controls for editing.
 */
@SuppressWarnings("unchecked")
public void cancel() {
    CollectionDatasource browseDs = getTable().getDatasource();
    Datasource editDs = getFieldGroup().getDatasource();
    Entity selectedItem = browseDs.getItem();
    if (selectedItem != null) {
        Entity reloadedItem = getDsContext().getDataSupplier().reload(selectedItem, editDs.getView());
        browseDs.setItem(reloadedItem);
    } else {
        editDs.setItem(null);
    }
    releaseLock();
    disableEditControls();
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Entity(com.haulmont.cuba.core.entity.Entity) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource)

Aggregations

CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)67 Datasource (com.haulmont.cuba.gui.data.Datasource)39 UUID (java.util.UUID)24 Group (com.haulmont.cuba.security.entity.Group)23 User (com.haulmont.cuba.security.entity.User)23 ArrayList (java.util.ArrayList)23 Ignore (org.junit.Ignore)23 Test (org.junit.Test)23 Component (com.haulmont.cuba.gui.components.Component)20 List (java.util.List)19 Assert.assertEquals (org.junit.Assert.assertEquals)19 Assert.assertTrue (org.junit.Assert.assertTrue)19 Entity (com.haulmont.cuba.core.entity.Entity)15 MetaClass (com.haulmont.chile.core.model.MetaClass)10 MetaProperty (com.haulmont.chile.core.model.MetaProperty)10 LookupField (com.haulmont.cuba.gui.components.LookupField)8 GuiDevelopmentException (com.haulmont.cuba.gui.GuiDevelopmentException)7 LookupPickerField (com.haulmont.cuba.gui.components.LookupPickerField)7 Element (org.dom4j.Element)7 Assert.assertNotNull (org.junit.Assert.assertNotNull)7