Example usage for org.hibernate.envers RevisionType DEL

List of usage examples for org.hibernate.envers RevisionType DEL

Introduction

In this page you can find the example usage for org.hibernate.envers RevisionType DEL.

Prototype

RevisionType DEL

To view the source code for org.hibernate.envers RevisionType DEL.

Click Source Link

Document

Indicates that the entity was deleted (removed) at that revision.

Usage

From source file:ch.puzzle.itc.mobiliar.business.auditview.control.AuditServiceTest.java

License:Open Source License

@Test
public void shouldReturnTrueIfRevisionTypeIsDel() {
    // given/*from   w w w  . ja va  2s .co  m*/
    String value = EMPTY;
    MyRevisionEntity revisionEntity = new MyRevisionEntity();
    AuditViewEntry entryInList = AuditViewEntry.builder(revisionEntity, RevisionType.DEL).oldValue(value)
            .value(value).build();
    Map<Integer, AuditViewEntry> allAuditViewEntries = new HashMap<>(1);
    allAuditViewEntries.put(entryInList.hashCode(), entryInList);

    // when
    boolean relevant = auditService.isAuditViewEntryRelevant(entryInList, allAuditViewEntries);

    // then
    assertThat(relevant, is(true));
}

From source file:com.actelion.research.spiritcore.services.dao.DAORevision.java

License:Open Source License

/**
 * Group the modified entities per revisionId/type
 * @param objects/*from   www. ja v  a2s. com*/
 * @return
 */
private static List<Revision> getRevisions(Set<Class<?>> entityClasses, List<Object[]> objects) {
    Map<Integer, Revision> map = new HashMap<>();
    for (Object[] a : objects) {

        Object entity = a[0];
        if (entityClasses == null && !(entity instanceof IAuditable))
            continue;
        else if (entityClasses != null && !entityClasses.contains(entity.getClass()))
            continue;

        SpiritRevisionEntity rev = (SpiritRevisionEntity) a[1];
        RevisionType type = (RevisionType) a[2];

        Revision r = map.get(rev.getId());
        if (r == null) {
            int sid = rev.getSid();
            Study study = DAOStudy.getStudy(sid);
            r = new Revision(rev.getId(), type, study, rev.getReason(), rev.getDifferenceList(),
                    rev.getUserId(), rev.getRevisionDate());
            map.put(rev.getId(), r);
        } else {
            if (type == RevisionType.DEL)
                r.setType(RevisionType.DEL);
            else if (type == RevisionType.ADD && r.getType() != RevisionType.DEL)
                r.setType(RevisionType.ADD);
        }
        r.getAuditables().add((IAuditable) entity);
    }

    List<Revision> res = new ArrayList<>(map.values());
    Collections.sort(res);
    return res;
}

From source file:com.actelion.research.spiritcore.services.dao.DAORevision.java

License:Open Source License

/**
 * Gets the last version and the change for the given entity, in the given context.
 * This method should return the last change, even if the changes of the given entity have not been committed.
 *
 * This method should be used exclusively from the SpritRevisionEntityListener to record the differences between the object to be saved and the last revision.
 * (when the record to be saved in already in the audit table)
 *
 * @param entityClass/*  w w w. j  a  va 2 s.  co  m*/
 * @param entityId
 * @return
 */
@SuppressWarnings("unchecked")
public static <T extends IAuditable> Pair<IAuditable, DifferenceList> getLastChange(RevisionType revisionType,
        Class<T> entityClass, Serializable entityId) {
    //Query the 2 last revisions of entityClass:entityId
    EntityManager session = JPAUtil.getManager();
    AuditReader reader = AuditReaderFactory.get(session);
    AuditQuery query = reader.createQuery().forRevisionsOfEntity(entityClass, false, true)
            .add(AuditEntity.id().eq(entityId)).addOrder(AuditEntity.revisionNumber().desc()).setMaxResults(2)
            .setCacheable(false).setLockMode(LockMode.NONE);
    List<Object[]> histories = query.getResultList();

    //Compute the difference between those 2 last versions
    assert histories.size() > 0;

    DifferenceList diff = null;
    if (revisionType == RevisionType.DEL) {
        diff = ((T) histories.get(0)[0]).getDifferenceList(null);
        diff.add("", ChangeType.DEL);
        assert diff.size() == 1;
    } else if (revisionType == RevisionType.ADD) {
        diff = ((T) histories.get(0)[0]).getDifferenceList(null);
        diff.add("", ChangeType.ADD);
        assert diff.size() == 1;
    } else if (histories.size() >= 2) {
        diff = ((T) histories.get(0)[0]).getDifferenceList((T) histories.get(1)[0]);
    } else {
        return null;
    }
    return new Pair<IAuditable, DifferenceList>((T) histories.get(0)[0], diff);
}

From source file:fr.mcc.ginco.audit.tracking.GincoRevListener.java

License:CeCILL license

@Override
public void entityChanged(Class entityClass, String entityName, Serializable entityId,
        RevisionType revisionType, Object revisionEntity) {
    GincoRevModifiedEntityType revEntity = new GincoRevModifiedEntityType();
    revEntity.setEntityClassName(entityClass.getName());
    revEntity.setRevision(((GincoRevEntity) revisionEntity).getId());
    ((GincoRevEntity) revisionEntity).addModifiedEntityType(revEntity);
    if (ArrayUtils.contains(entityClass.getGenericInterfaces(), IAuditableBean.class)) {
        if (!revisionType.equals(RevisionType.DEL)) {
            GenericHibernateDAO objectDAO = new GenericHibernateDAO(entityClass);
            objectDAO.setSessionFactory((SessionFactory) applicationContext.getBean("gincoSessionFactory"));
            String thesaurusId = ((IAuditableBean) objectDAO.getById(entityId)).getThesaurusId();
            ((GincoRevEntity) revisionEntity).setThesaurusId(thesaurusId);
        } else {//from ww w  .  j  av  a  2s .c o  m
            SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("gincoSessionFactory");
            AuditReader reader = AuditReaderFactory.get(sessionFactory.getCurrentSession());

            AuditQueryBuilder queryBuilder = new AuditQueryBuilder();
            AuditQuery query;
            try {
                query = queryBuilder.getEntityAddedQuery(reader, Class.forName(entityName), entityId);
                try {
                    List<Object[]> createdEvent = (List<Object[]>) query.getResultList();
                    if (createdEvent != null && createdEvent.size() > 0) {
                        ((GincoRevEntity) revisionEntity)
                                .setThesaurusId(((GincoRevEntity) createdEvent.get(0)[1]).getThesaurusId());
                    }
                } catch (AuditException ae) {
                    logger.warn("Unable to get the creation revision of the destroyed object", ae);
                }
            } catch (ClassNotFoundException e) {
                logger.error("Error storing audit data", e);
            }
        }
    } else {
        logger.warn("Trying to audit a bean not implementing IAuditableBean interface");
    }

}

From source file:org.azafiu.hibernatetest.datainteractor.ProductDAO.java

License:Apache License

/**
 * Get all products that need to be shown to the checker for approval.
 * /*from  w  w  w . j  a va  2 s .c o  m*/
 * @return a list of Object[]. Each element will be an Object[3] array with
 *         the following items: Object[0] - the {@link ProductEntity} at a
 *         revision ( greater or equal than the one given as parameter)
 *         Object[1] a {@link DefaultRevisionEntity} Object[2] a
 *         {@link RevisionType} object containing information about the
 *         revision
 */
@Transactional
public List<Object[]> getAllProductsWaitingForApproval() {
    /**
     * Get all distinct {@link ProductEntity} objects where the wasChecked
     * property is false order by modified descending
     */
    final AuditQuery query = this.getAuditReader().createQuery()
            .forRevisionsOfEntity(ProductEntity.class, false, true)
            .addOrder(AuditEntity.property("modified").desc())
            .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext())
            .add(AuditEntity.property("wasChecked").eq(Boolean.FALSE))
            .add(AuditEntity.revisionType().ne(RevisionType.DEL));

    final List<Object[]> resultList = query.getResultList();

    final List<Object[]> result = new ArrayList<>();

    /**
     * for each "changed" object found in the db we need to check if there
     * is a newer revision of it in which the {@link ProductEntity} was
     * approved (wasChecked = true) because we do not need to retrieve
     * already checked objects to the checker.
     */
    for (final Object[] change : resultList) {
        final ProductEntity pe = (ProductEntity) change[0];
        final AuditQuery queryForWasCheckedTrue = this.getAuditReader().createQuery()
                .forRevisionsOfEntity(ProductEntity.class, false, true)
                .addOrder(AuditEntity.property("modified").desc()).add(AuditEntity.id().eq(pe.getId()))
                .add(AuditEntity.property("wasChecked").eq(Boolean.TRUE));

        if (pe.getModified() != null) {
            queryForWasCheckedTrue.add(AuditEntity.property("modified").gt(pe.getModified()));
        }

        try {
            final Object[] trueWasChecked = (Object[]) queryForWasCheckedTrue.getSingleResult();
        } catch (final NoResultException ex) {
            // there is no newer revision where the current product has
            // wasChecked property == true
            result.add(change);
        }

    }

    return result;
}

From source file:org.cast.cwm.admin.UserContentLogPage.java

License:Open Source License

protected List<IDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>> makeColumns() {
    List<IDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>> columns = new ArrayList<IDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>>(
            10);/*from  ww w .j a  va  2  s  . co  m*/
    columns.add(new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Rev ID", "info.id"));
    columns.add(new AbstractDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Rev Date") {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<AuditTriple<UserContent, DefaultRevisionEntity>>> cellItem,
                String componentId, IModel<AuditTriple<UserContent, DefaultRevisionEntity>> rowModel) {
            cellItem.add(DateLabel.forDatePattern(componentId,
                    new PropertyModel<Date>(rowModel, "info.revisionDate"), eventDateFormat));
        }

        @Override
        public String getItemString(IModel<AuditTriple<UserContent, DefaultRevisionEntity>> rowModel) {
            AuditTriple<UserContent, DefaultRevisionEntity> triple = rowModel.getObject();
            DefaultRevisionEntity info = triple.getInfo();
            Date revisionDate = info.getRevisionDate();
            return new SimpleDateFormat(eventDateFormat).format(revisionDate);
        }
    });
    columns.add(new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Rev Type", "type"));
    columns.add(new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("UC ID", "entity.id"));
    columns.add(new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("User",
            "entity.user.subjectId"));
    columns.add(
            new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Type", "entity.dataType"));
    columns.add(
            new PropertyDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Title", "entity.title"));

    // What to do with the content column depends on the data type.
    columns.add(new AbstractDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>("Content") {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<AuditTriple<UserContent, DefaultRevisionEntity>>> item,
                String componentId, IModel<AuditTriple<UserContent, DefaultRevisionEntity>> rowModel) {
            UserContent uc = rowModel.getObject().getEntity();
            if (!rowModel.getObject().getType().equals(RevisionType.DEL)) {
                if (uc.getDataType().getName().equals("TEXT"))
                    item.add(new Label(componentId, new PropertyModel<String>(rowModel, "entity.text")));
                else
                    item.add(new ContentLinkPanel(componentId, rowModel.getObject().getEntity().getId(),
                            rowModel.getObject().getInfo().getId()));
            } else {
                item.add(new EmptyPanel(componentId));
            }
        }

        @Override
        public String getItemString(IModel<AuditTriple<UserContent, DefaultRevisionEntity>> rowModel) {
            UserContent uc = rowModel.getObject().getEntity();
            if (uc.getDataType().getName().equals("TEXT")) {
                return rowModel.getObject().getEntity().getText();
            } else {
                // output a text link for the spreadsheet
                Url path = Url.parse(urlFor(UserContentViewPage.class, getPageParameters(
                        rowModel.getObject().getEntity().getId(), rowModel.getObject().getInfo().getId()))
                                .toString());
                return getRequestCycle().getUrlRenderer().renderFullUrl(path);
                // TODO, if we have a urlPrefix, replace Tomcat's idea of the URL with the given prefix.
            }
        }

    });

    return columns;

}