Search in sources :

Example 1 with SoftDelete

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

the class EntityInspectorBrowse method createButtonsPanel.

protected void createButtonsPanel(Table table) {
    ButtonsPanel buttonsPanel = uiComponents.create(ButtonsPanel.class);
    createButton = uiComponents.create(Button.class);
    createButton.setCaption(messages.getMessage(EntityInspectorBrowse.class, "create"));
    CreateAction createAction = new CreateAction();
    table.addAction(createAction);
    createButton.setAction(createAction);
    createButton.setIcon(icons.get(CubaIcon.CREATE_ACTION));
    createButton.setFrame(frame);
    editButton = uiComponents.create(Button.class);
    editButton.setCaption(messages.getMessage(EntityInspectorBrowse.class, "edit"));
    EditAction editAction = new EditAction();
    table.addAction(editAction);
    editButton.setAction(editAction);
    editButton.setIcon(icons.get(CubaIcon.EDIT_ACTION));
    editButton.setFrame(frame);
    removeButton = uiComponents.create(Button.class);
    removeButton.setCaption(messages.getMessage(EntityInspectorBrowse.class, "remove"));
    RemoveAction removeAction = new RemoveAction(entitiesTable) {

        @Override
        protected boolean isPermitted() {
            if (getTarget().getSingleSelected() instanceof SoftDelete) {
                for (Object e : getTarget().getSelected()) {
                    if (((SoftDelete) e).isDeleted())
                        return false;
                }
            }
            return super.isPermitted();
        }
    };
    removeAction.setAfterRemoveHandler(removedItems -> entitiesDs.refresh());
    table.addAction(removeAction);
    removeButton.setAction(removeAction);
    removeButton.setIcon(icons.get(CubaIcon.REMOVE_ACTION));
    removeButton.setFrame(frame);
    excelButton = uiComponents.create(Button.class);
    excelButton.setCaption(messages.getMessage(EntityInspectorBrowse.class, "excel"));
    excelButton.setAction(new ExcelAction(entitiesTable));
    excelButton.setIcon(icons.get(CubaIcon.EXCEL_ACTION));
    excelButton.setFrame(frame);
    refreshButton = uiComponents.create(Button.class);
    refreshButton.setCaption(messages.getMessage(EntityInspectorBrowse.class, "refresh"));
    refreshButton.setAction(new RefreshAction(entitiesTable));
    refreshButton.setIcon(icons.get(CubaIcon.REFRESH_ACTION));
    refreshButton.setFrame(frame);
    exportPopupButton = uiComponents.create(PopupButton.class);
    exportPopupButton.setIcon(icons.get(CubaIcon.DOWNLOAD));
    exportPopupButton.addAction(new ExportAction("exportJSON", JSON));
    exportPopupButton.addAction(new ExportAction("exportZIP", ZIP));
    importUpload = uiComponents.create(FileUploadField.class);
    importUpload.setFrame(frame);
    importUpload.setPermittedExtensions(Sets.newHashSet(".json", ".zip"));
    importUpload.setUploadButtonIcon(icons.get(CubaIcon.UPLOAD));
    importUpload.setUploadButtonCaption(getMessage("import"));
    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 upload file", e);
        }
        try {
            fileUploadingAPI.deleteFile(importUpload.getFileId());
        } catch (FileStorageException e) {
            log.error("Unable to delete temp file", e);
        }
        String fileName = importUpload.getFileName();
        try {
            Collection<Entity> importedEntities;
            if ("json".equals(Files.getFileExtension(fileName))) {
                String content = new String(fileBytes, StandardCharsets.UTF_8);
                importedEntities = entityImportExportService.importEntitiesFromJSON(content, createEntityImportView(content, selectedMeta));
            } else {
                importedEntities = entityImportExportService.importEntitiesFromZIP(fileBytes, createEntityImportView(selectedMeta));
            }
            // todo localize the message !
            showNotification(importedEntities.size() + " entities imported", NotificationType.HUMANIZED);
        } catch (Exception e) {
            showNotification(getMessage("importFailed"), formatMessage("importFailedMessage", fileName, nullToEmpty(e.getMessage())), NotificationType.ERROR);
            log.error("Entities import error", e);
        }
        entitiesDs.refresh();
    });
    buttonsPanel.add(createButton);
    buttonsPanel.add(editButton);
    buttonsPanel.add(removeButton);
    buttonsPanel.add(excelButton);
    buttonsPanel.add(refreshButton);
    buttonsPanel.add(exportPopupButton);
    buttonsPanel.add(importUpload);
    table.setButtonsPanel(buttonsPanel);
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) 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 2 with SoftDelete

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

the class StudioEclipseLinkSessionEventListener method preLogin.

@Override
public void preLogin(SessionEvent event) {
    Session session = event.getSession();
    Map<Class, ClassDescriptor> descriptorMap = session.getDescriptors();
    for (Map.Entry<Class, ClassDescriptor> entry : descriptorMap.entrySet()) {
        ClassDescriptor desc = entry.getValue();
        if (SoftDelete.class.isAssignableFrom(desc.getJavaClass())) {
            desc.getQueryManager().setAdditionalCriteria("this.deleteTs is null");
            desc.setDeletePredicate(entity -> entity instanceof SoftDelete && PersistenceHelper.isLoaded(entity, "deleteTs") && ((SoftDelete) entity).isDeleted());
        }
        List<DatabaseMapping> mappings = desc.getMappings();
        Class entityClass = entry.getKey();
        for (DatabaseMapping mapping : mappings) {
            if (UUID.class.equals(getFieldType(entityClass, mapping.getAttributeName()))) {
                ((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
                setDatabaseFieldParameters(session, mapping.getField());
            }
        }
    }
}
Also used : DirectToFieldMapping(org.eclipse.persistence.mappings.DirectToFieldMapping) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Map(java.util.Map) Session(org.eclipse.persistence.sessions.Session)

Example 3 with SoftDelete

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

the class EntityRestore method showRestoreDialog.

protected void showRestoreDialog() {
    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.focus();
            }), new DialogAction(Type.CANCEL, Status.PRIMARY).withHandler(event -> {
                entitiesTable.focus();
            }) });
        }
    } else {
        showNotification(getMessage("entityRestore.restoreMsg"));
    }
}
Also used : SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) java.util(java.util) Dom4jTools(com.haulmont.cuba.core.sys.xmlparsing.Dom4jTools) 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) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) MetaClass(com.haulmont.chile.core.model.MetaClass) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) DsContextImplementation(com.haulmont.cuba.gui.data.impl.DsContextImplementation) GroupDatasource(com.haulmont.cuba.gui.data.GroupDatasource) 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) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Status(com.haulmont.cuba.gui.components.Action.Status) Type(com.haulmont.cuba.gui.components.DialogAction.Type) Element(org.dom4j.Element) UiComponents(com.haulmont.cuba.gui.UiComponents) Entity(com.haulmont.cuba.core.entity.Entity) AnnotatedElement(java.lang.reflect.AnnotatedElement) Entity(com.haulmont.cuba.core.entity.Entity) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete)

Example 4 with SoftDelete

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

the class EntityRestoreServiceBean method restoreDetails.

protected void restoreDetails(Entity entity, Date deleteTs, String storeName) {
    EntityManager em = persistence.getEntityManager(storeName);
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    List<MetaProperty> properties = new ArrayList<>();
    fillProperties(metaClass, properties, OnDelete.class.getName());
    for (MetaProperty property : properties) {
        OnDelete annotation = property.getAnnotatedElement().getAnnotation(OnDelete.class);
        DeletePolicy deletePolicy = annotation.value();
        if (deletePolicy == DeletePolicy.CASCADE) {
            MetaClass detailMetaClass = property.getRange().asClass();
            if (!storeName.equals(metadata.getTools().getStoreName(detailMetaClass))) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is from different data store");
                continue;
            }
            if (!SoftDelete.class.isAssignableFrom(detailMetaClass.getJavaClass())) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is hard deleted");
                continue;
            }
            if (metadataTools.isOwningSide(property)) {
                Object value = entity.getValue(property.getName());
                if (value instanceof Entity) {
                    restoreEntity((Entity) value, storeName);
                } else if (value instanceof Collection) {
                    for (Object detailEntity : (Collection) value) {
                        restoreEntity((Entity) detailEntity, storeName);
                    }
                }
            } else {
                MetaProperty inverseProp = property.getInverse();
                if (inverseProp == null) {
                    log.debug("Cannot restore " + property.getRange().asClass() + " because it has no inverse property for " + metaClass);
                    continue;
                }
                String jpql = "select e from " + detailMetaClass + " e where e." + inverseProp.getName() + ".id = ?1 " + "and e.deleteTs >= ?2 and e.deleteTs <= ?3";
                Query query = em.createQuery(jpql);
                query.setParameter(1, entity.getId());
                query.setParameter(2, DateUtils.addMilliseconds(deleteTs, -100));
                query.setParameter(3, DateUtils.addMilliseconds(deleteTs, 1000));
                // noinspection unchecked
                List<Entity> list = query.getResultList();
                for (Entity detailEntity : list) {
                    if (entity instanceof SoftDelete) {
                        restoreEntity(detailEntity, storeName);
                    }
                }
            }
        }
    }
    properties = new ArrayList<>();
    fillProperties(metaClass, properties, OnDeleteInverse.class.getName());
    for (MetaProperty property : properties) {
        OnDeleteInverse annotation = property.getAnnotatedElement().getAnnotation(OnDeleteInverse.class);
        DeletePolicy deletePolicy = annotation.value();
        if (deletePolicy == DeletePolicy.CASCADE) {
            MetaClass detailMetaClass = property.getDomain();
            if (!storeName.equals(metadata.getTools().getStoreName(detailMetaClass))) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is from different data store");
                continue;
            }
            if (!SoftDelete.class.isAssignableFrom(detailMetaClass.getJavaClass())) {
                log.debug("Cannot restore " + property.getRange().asClass() + " because it is hard deleted");
                continue;
            }
            List<MetaClass> metClassesToRestore = new ArrayList<>();
            metClassesToRestore.add(detailMetaClass);
            metClassesToRestore.addAll(detailMetaClass.getDescendants());
            for (MetaClass metaClassToRestore : metClassesToRestore) {
                if (!metadata.getTools().isPersistent(metaClassToRestore))
                    continue;
                String jpql;
                if (property.getRange().getCardinality().isMany()) {
                    jpql = "select e from " + metaClassToRestore.getName() + " e join e." + property.getName() + " p" + " where p.id = ?1 and e.deleteTs >= ?2 and e.deleteTs <= ?3";
                } else {
                    jpql = "select e from " + metaClassToRestore.getName() + " e where e." + property.getName() + ".id = ?1 and e.deleteTs >= ?2 and e.deleteTs <= ?3";
                }
                Query query = em.createQuery(jpql);
                query.setParameter(1, entity.getId());
                query.setParameter(2, DateUtils.addMilliseconds(deleteTs, -100));
                query.setParameter(3, DateUtils.addMilliseconds(deleteTs, 1000));
                // noinspection unchecked
                List<Entity> list = query.getResultList();
                for (Entity detailEntity : list) {
                    if (entity instanceof SoftDelete) {
                        restoreEntity(detailEntity, storeName);
                    }
                }
            }
        }
    }
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) Query(com.haulmont.cuba.core.Query) DeletePolicy(com.haulmont.cuba.core.global.DeletePolicy) EntityManager(com.haulmont.cuba.core.EntityManager) MetaClass(com.haulmont.chile.core.model.MetaClass) OnDeleteInverse(com.haulmont.cuba.core.entity.annotation.OnDeleteInverse) MetaProperty(com.haulmont.chile.core.model.MetaProperty) OnDelete(com.haulmont.cuba.core.entity.annotation.OnDelete)

Example 5 with SoftDelete

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

the class EntityRestoreServiceBean method restoreEntity.

protected void restoreEntity(Entity entity, String storeName) {
    EntityManager em = persistence.getEntityManager(storeName);
    Entity reloadedEntity = em.find(entity.getClass(), entity.getId());
    if (reloadedEntity != null && ((SoftDelete) reloadedEntity).isDeleted()) {
        log.info("Restoring deleted entity " + entity);
        Date deleteTs = ((SoftDelete) reloadedEntity).getDeleteTs();
        ((SoftDelete) reloadedEntity).setDeleteTs(null);
        em.merge(reloadedEntity);
        restoreDetails(reloadedEntity, deleteTs, storeName);
    }
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) EntityManager(com.haulmont.cuba.core.EntityManager) SoftDelete(com.haulmont.cuba.core.entity.SoftDelete)

Aggregations

SoftDelete (com.haulmont.cuba.core.entity.SoftDelete)11 Entity (com.haulmont.cuba.core.entity.Entity)9 MetaClass (com.haulmont.chile.core.model.MetaClass)5 MetaProperty (com.haulmont.chile.core.model.MetaProperty)3 EntityManager (com.haulmont.cuba.core.EntityManager)3 Range (com.haulmont.chile.core.model.Range)2 Query (com.haulmont.cuba.core.Query)2 OnDelete (com.haulmont.cuba.core.entity.annotation.OnDelete)2 OnDeleteInverse (com.haulmont.cuba.core.entity.annotation.OnDeleteInverse)2 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)2 WindowConfig (com.haulmont.cuba.gui.config.WindowConfig)2 DataSupplier (com.haulmont.cuba.gui.data.DataSupplier)2 java.util (java.util)2 Map (java.util.Map)2 Inject (javax.inject.Inject)2 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)2 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)2 Session (org.eclipse.persistence.sessions.Session)2 Pair (com.haulmont.bali.datastruct.Pair)1 QueryRunner (com.haulmont.bali.db.QueryRunner)1