Search in sources :

Example 46 with Entity

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

the class EntityRestore method showRestoreDialog.

protected void showRestoreDialog() {
    final Set<Entity> entityList = entitiesTable.getSelected();
    Entity entity = entitiesDs.getItem();
    if (entityList != null && entity != null && entityList.size() > 0) {
        if (entity instanceof SoftDelete) {
            showOptionDialog(getMessage("dialogs.Confirmation"), getMessage("dialogs.Message"), MessageType.CONFIRMATION, new Action[] { new DialogAction(Type.OK).withHandler(event -> {
                restoreService.restoreEntities(entityList);
                entitiesTable.refresh();
                entitiesTable.requestFocus();
            }), new DialogAction(Type.CANCEL, Status.PRIMARY).withHandler(event -> {
                entitiesTable.requestFocus();
            }) });
        }
    } else {
        showNotification(getMessage("entityRestore.restoreMsg"));
    }
}
Also used : SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) Dom4j(com.haulmont.bali.util.Dom4j) DsBuilder(com.haulmont.cuba.gui.data.DsBuilder) EntityRestoreService(com.haulmont.cuba.core.app.EntityRestoreService) SimpleDateFormat(java.text.SimpleDateFormat) EnableRestore(com.haulmont.cuba.core.entity.annotation.EnableRestore) MetaClass(com.haulmont.chile.core.model.MetaClass) Inject(javax.inject.Inject) MetadataTools(com.haulmont.cuba.core.global.MetadataTools) ComponentsFactory(com.haulmont.cuba.gui.xml.layout.ComponentsFactory) DsContextImplementation(com.haulmont.cuba.gui.data.impl.DsContextImplementation) GroupDatasource(com.haulmont.cuba.gui.data.GroupDatasource) ViewRepository(com.haulmont.cuba.core.global.ViewRepository) com.haulmont.cuba.gui.components(com.haulmont.cuba.gui.components) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) DsContext(com.haulmont.cuba.gui.data.DsContext) Range(com.haulmont.chile.core.model.Range) Formatter(com.haulmont.cuba.gui.components.Formatter) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Status(com.haulmont.cuba.gui.components.Action.Status) Type(com.haulmont.cuba.gui.components.DialogAction.Type) View(com.haulmont.cuba.core.global.View) AppConfig(com.haulmont.cuba.gui.AppConfig) Element(org.dom4j.Element) Entity(com.haulmont.cuba.core.entity.Entity) MessageTools(com.haulmont.cuba.core.global.MessageTools) AnnotatedElement(java.lang.reflect.AnnotatedElement) Entity(com.haulmont.cuba.core.entity.Entity) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete)

Example 47 with Entity

use of com.haulmont.cuba.core.entity.Entity 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 48 with Entity

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

the class RoleBrowser method importRoles.

protected void importRoles() {
    File file = fileUploadingAPI.getFile(importRolesUpload.getFileId());
    if (file == null) {
        String errorMsg = String.format("Entities import upload error. File with id %s not found", importRolesUpload.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 {
        Collection<Entity> importedEntities;
        if ("json".equals(Files.getFileExtension(importRolesUpload.getFileName()))) {
            String jsonContent = new String(fileBytes, StandardCharsets.UTF_8);
            importedEntities = entityImportExportService.importEntitiesFromJSON(jsonContent, createRolesImportView());
        } else {
            importedEntities = entityImportExportService.importEntitiesFromZIP(fileBytes, createRolesImportView());
        }
        long importedRolesCount = importedEntities.stream().filter(entity -> entity instanceof Role).count();
        showNotification(importedRolesCount + " roles imported", NotificationType.HUMANIZED);
        rolesDs.refresh();
    } catch (Exception e) {
        showNotification(formatMessage("importError", e.getMessage()), NotificationType.ERROR);
    }
    try {
        fileUploadingAPI.deleteFile(importRolesUpload.getFileId());
    } catch (FileStorageException e) {
        log.error("Unable to delete temp file", e);
    }
}
Also used : java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) Files(com.google.common.io.Files) CollectionImportPolicy(com.haulmont.cuba.core.app.importexport.CollectionImportPolicy) ExportFormat(com.haulmont.cuba.gui.export.ExportFormat) 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) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) UserManagementService(com.haulmont.cuba.security.app.UserManagementService) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) EntityImportView(com.haulmont.cuba.core.app.importexport.EntityImportView) WindowParams(com.haulmont.cuba.gui.WindowParams) IOUtils(org.apache.commons.io.IOUtils) ByteArrayDataProvider(com.haulmont.cuba.gui.export.ByteArrayDataProvider) FileUploadingAPI(com.haulmont.cuba.gui.upload.FileUploadingAPI) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Entity(com.haulmont.cuba.core.entity.Entity) InputStream(java.io.InputStream) Entity(com.haulmont.cuba.core.entity.Entity) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) File(java.io.File)

Example 49 with Entity

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

the class ScreenHistorySupport method saveScreenHistory.

public void saveScreenHistory(Window window, WindowManager.OpenMode openMode) {
    Security security = AppBeans.get(Security.NAME);
    if (security.isEntityOpPermitted(ScreenHistoryEntity.class, EntityOp.CREATE) && window.getFrame() != null && (window.getFrame() instanceof Window.Editor) && openMode != WindowManager.OpenMode.DIALOG && (screenIds == null || screenIds.contains(window.getId()))) {
        String caption = window.getCaption();
        UUID entityId = null;
        Frame frame = window.getFrame();
        Entity entity = null;
        if (frame instanceof Window.Editor) {
            entity = ((Window.Editor) frame).getItem();
            if (entity != null) {
                if (PersistenceHelper.isNew(entity)) {
                    return;
                }
                if (StringUtils.isBlank(caption))
                    caption = messages.getTools().getEntityCaption(entity.getMetaClass()) + " " + entity.getInstanceName();
                entityId = (UUID) entity.getId();
            }
        }
        ScreenHistoryEntity screenHistoryEntity = metadata.create(ScreenHistoryEntity.class);
        screenHistoryEntity.setCaption(StringUtils.abbreviate(caption, 255));
        screenHistoryEntity.setUrl(makeLink(window));
        screenHistoryEntity.setEntityId(entityId);
        addAdditionalFields(screenHistoryEntity, entity);
        CommitContext cc = new CommitContext(Collections.singleton(screenHistoryEntity));
        DataService dataService = AppBeans.get(DataService.NAME);
        dataService.commit(cc);
    }
}
Also used : Window(com.haulmont.cuba.gui.components.Window) ScreenHistoryEntity(com.haulmont.cuba.security.entity.ScreenHistoryEntity) Entity(com.haulmont.cuba.core.entity.Entity) Frame(com.haulmont.cuba.gui.components.Frame) ScreenHistoryEntity(com.haulmont.cuba.security.entity.ScreenHistoryEntity) DataService(com.haulmont.cuba.core.app.DataService)

Example 50 with Entity

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

the class LinkColumnHelper method initColumn.

public static void initColumn(Table table, final String propertyName, final Handler handler) {
    final ComponentsFactory componentsFactory = AppBeans.get(ComponentsFactory.NAME);
    table.addGeneratedColumn(propertyName, new Table.ColumnGenerator() {

        @Override
        public Component generateCell(final Entity entity) {
            // //process properties like building.house.room
            String[] props = propertyName.split("\\.");
            Instance nestedEntity = entity;
            for (int i = 0; i < props.length - 1; i++) {
                nestedEntity = nestedEntity.getValue(props[i]);
                if (nestedEntity == null) {
                    break;
                }
            }
            final Object value = (nestedEntity == null) ? null : nestedEntity.getValue(props[props.length - 1]);
            if (value != null) {
                Button button = componentsFactory.createComponent(Button.class);
                button.setStyleName("link");
                button.setAction(new AbstractAction("open") {

                    @Override
                    public void actionPerform(Component component) {
                        handler.onClick(entity);
                    }

                    @Override
                    public String getCaption() {
                        String str;
                        Datatype datatype = Datatypes.get(value.getClass());
                        if (datatype != null) {
                            UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
                            str = datatype.format(value, sessionSource.getLocale());
                        } else {
                            str = value.toString();
                        }
                        return str;
                    }
                });
                button.setStyleName("link");
                return button;
            }
            return null;
        }
    });
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) UserSessionSource(com.haulmont.cuba.core.global.UserSessionSource) Table(com.haulmont.cuba.gui.components.Table) Instance(com.haulmont.chile.core.model.Instance) Datatype(com.haulmont.chile.core.datatypes.Datatype) ComponentsFactory(com.haulmont.cuba.gui.xml.layout.ComponentsFactory) Button(com.haulmont.cuba.gui.components.Button) Component(com.haulmont.cuba.gui.components.Component) AbstractAction(com.haulmont.cuba.gui.components.AbstractAction)

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