@Override protected Object process(HttpServletRequest req, WxSession session) throws Exception { int first; int limit; Date start; Date end; first = req.getParameter("first") == null ? 0 : Integer.parseInt(req.getParameter("first")); limit = req.getParameter("limit") == null ? 20 : Integer.parseInt(req.getParameter("limit")); start = req.getParameter("start") == null ? getToday() : dateFormat.parse(req.getParameter("start")); end = req.getParameter("end") == null ? getToday() : dateFormat.parse(req.getParameter("end")); end = DateUtils.addDays(end, 1); try (Session s = SQLCore.sf.openSession()) { AuditReader reader = TableTicket.getAuditReader(s); return reader.createQuery() .forRevisionsOfEntity(Ticket.class, false, true) .addOrder(AuditEntity.revisionNumber().desc()) .add(AuditEntity.revisionProperty("timestamp").between(start.getTime(), end.getTime())) .setFirstResult(first) .setMaxResults(limit) .getResultList(); } }
public List<Revision> getRevisions(String id, Params params) { AuditReader reader = getAuditReader(); List<Number> revisionNumbers = reader.getRevisions(type, id); Map<Number, Revision> revisionMap = reader.findRevisions(Revision.class, asSet(revisionNumbers)); Collection<Revision> revisions = revisionMap.values(); Comparator<Revision> timestampComparator = Comparator.comparingLong(Revision::getTimestamp); Comparator<Revision> authorComparator = Comparator.comparing(Revision::getAuthor); Comparator<Revision> comparator; if (AUTHOR.equals(params.getSort())) { comparator = authorComparator; } else { comparator = timestampComparator; } if (params.getOrder() == Order.DESC) { comparator = comparator.reversed(); } return Ordering.from(comparator) .sortedCopy(revisions); }
@Transactional(readOnly = true) public List<CustomerHistory> listCustomerRevisions(Long customerId) { // Create the Audit Reader. It uses the EntityManager, which will be opened when // starting the new Transation and closed when the Transaction finishes. AuditReader auditReader = AuditReaderFactory.get(entityManager); // Create the Query: AuditQuery auditQuery = auditReader.createQuery() .forRevisionsOfEntity(Customer.class, false, true) .add(AuditEntity.id().eq(customerId)); // We don't operate on the untyped Results, but cast them into a List of AuditQueryResult: return AuditQueryUtils.getAuditQueryResults(auditQuery, Customer.class).stream() // Turn into the CustomerHistory Domain Object: .map(x -> getCustomerHistory(x)) // And collect the Results: .collect(Collectors.toList()); }
@Test public void persist2() throws Exception { if (!JBOSS.equals(APPSERVER)) { return; } log.info("start persist2()"); AuditedTComplexEntity ce = createAuditedTComplexEntity(); applEman.persist(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); List<Archive> archList = ArchiveLoader.loadArchivesByPrimaryKeyId(AuditedTComplexEntity.class.getName(), String.valueOf(ce.getId())); Assert.assertEquals(0, archList.size()); AuditReader ar = AuditReaderFactory.get(applEman); AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true); List<AuditedTComplexEntity> resList = query.getResultList(); Assert.assertEquals(0, resList.size()); }
@Test public void delete1() throws Exception { if (!JBOSS.equals(APPSERVER)) { return; } log.info("start delete1()"); AuditedTComplexEntity ce = createAuditedTComplexEntity(); applEman.persist(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); applEman.remove(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); AuditReader ar = AuditReaderFactory.get(applEman); AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true); List<AuditedTComplexEntity> resList = query.getResultList(); Assert.assertEquals(1, resList.size()); AuditedTComplexEntity ce2 = resList.get(0); log.debug(ce2); Assert.assertEquals(2, ce2.getEagerList().size()); }
@Test public void update1() throws Exception { if (!JBOSS.equals(APPSERVER)) { return; } log.info("start update1()"); AuditedTComplexEntity ce = createAuditedTComplexEntity(); applEman.persist(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); ce.setOwner("new owner"); ce = applEman.merge(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); AuditReader ar = AuditReaderFactory.get(applEman); AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true); List<AuditedTComplexEntity> resList = query.getResultList(); Assert.assertEquals(1, resList.size()); AuditedTComplexEntity ce2 = resList.get(0); Assert.assertEquals("new owner", ce2.getOwner()); }
/** * gets the entity at the specified revision * * @param id * the id of the entity to fetch * @param revisionNumber * the revision number * @return the entity or null if no entity can be found */ @Nullable @Override public JobNotification findRevision(int id, int revisionNumber) { JobNotification result = null; try { begin(); AuditReader reader = AuditReaderFactory.get(getEntityManager()); result = reader.find(JobNotification.class, id, revisionNumber); Hibernate.initialize(result.getLifecycleEvents()); result.getLifecycleEvents().contains(JobLifecycleEvent.QUEUE_ADD); commit(); } catch (NoResultException e) { LOG.warn("No result for revision " + revisionNumber + " with id of " + id); } finally { cleanup(); } return result; }
/** * * @param id * @return */ public int getHeadRevisionNumber(int id) { int result = 0; try { begin(); AuditReader reader = AuditReaderFactory.get(getEntityManager()); List<Number> revisions = reader.getRevisions(entityClass, id); if (!revisions.isEmpty()) { result = revisions.get(revisions.size() - 1).intValue(); } commit(); } catch (NoResultException e) { rollback(); LOG.warn("No result for revision with id of " + id); } finally { cleanup(); } return result; }
/** * gets the entity at the specified revision * * @param id * the id of the entity to fetch * @param revisionNumber * the revision number * @return the entity or null if no entity can be found */ @Nullable public T_ENTITY findRevision(int id, int revisionNumber) { T_ENTITY result = null; try { begin(); AuditReader reader = AuditReaderFactory.get(getEntityManager()); result = reader.find(entityClass, id, revisionNumber); commit(); } catch (NoResultException e) { rollback(); LOG.warn("No result for revision " + revisionNumber + " with id of " + id); } finally { cleanup(); } return result; }
public List<HistoryDto> findAllHistory(String username) { Patient patientA = patientRepository.findByUsername(username); Long patientId = patientA.getId(); EntityManager em = entityManagerFactory.createEntityManager(); AuditReader reader = AuditReaderFactory.get(em); List<Number> revisions = reader.getRevisions(Patient.class, patientId); List<HistoryDto> historyList = findHistoryDetails(revisions); List<HistoryDto> legalHistoryList = findLegalHistoryByPatient(patientId); historyList.addAll(legalHistoryList); Collections.sort(historyList); List<HistoryDto> historyListReverse = getReversed(historyList); em.close(); return historyListReverse; }
/** * @param clazz * @param lastId * @return */ @SuppressWarnings("unchecked") private <T extends Shareable> Bundle<T> getDelta(Class<T> clazz, String lastId) { AuditReader ar = AuditReaderFactory.get(getSession()); Number number = getLastId(clazz, lastId); List<Object[]> entities = ar.createQuery() .forRevisionsOfEntity(clazz, false, false) .add(AuditEntity.revisionNumber().gt(number)).getResultList(); Bundle<T> bundle = new Bundle<T>(lastId); for (Object[] o : entities) { if (o == null) { continue; } bundle.add((T) notNull(o[0]), notNull(getId(o[1]))); } return bundle; }
/** * @param clazz * @param reader * @param lastId * @return */ @SuppressWarnings("unchecked") private <T extends Shareable> boolean isUnknown(Class<T> clazz, String lastId) { if (Bundle.FIRST_CHANGE.equals(lastId)) { return false; } AuditReader reader = AuditReaderFactory.get(getSession()); List<T> entitiesAtRevision = reader.createQuery() .forRevisionsOfEntity(clazz, false, false) .add(AuditEntity.revisionNumber().eq(getLastId(clazz, lastId))) .getResultList(); return (entitiesAtRevision == null) || entitiesAtRevision.isEmpty(); }
@Nonnull private <T extends Shareable> Bundle<T> getAll(@Nonnull Class<T> clazz) { AuditReader reader = AuditReaderFactory.get(getSession()); Number prior = (Number) reader.createQuery() .forRevisionsOfEntity(clazz, false, true) .addProjection(AuditEntity.revisionNumber().max()) .getSingleResult(); String lastId; // previous revision, la actual no será persistida. if (prior == null) { lastId = Bundle.FIRST_CHANGE; } else { lastId = String.valueOf(prior); } return firstChangeProviderHandler.getAll(clazz, notNull(lastId)); }
@Override @SuppressWarnings("unchecked") public Revision<N, T> findLastChangeRevision(ID id) { Class<T> type = entityInformation.getJavaType(); AuditReader reader = AuditReaderFactory.get(entityManager); List<Number> revisions = reader.getRevisions(type, id); if (revisions.isEmpty()) { return null; } N latestRevision = (N) revisions.get(revisions.size() - 1); Class<?> revisionEntityClass = revisionEntityInformation.getRevisionEntityClass(); Object revisionEntity = reader.findRevision(revisionEntityClass, latestRevision); RevisionMetadata<N> metadata = (RevisionMetadata<N>) getRevisionMetadata(revisionEntity); return new Revision<N, T>(metadata, reader.find(type, id, latestRevision)); }
@Override @SuppressWarnings("unchecked") public Page<Revision<N, T>> findRevisions(ID id, Pageable pageable) { Class<T> type = entityInformation.getJavaType(); AuditReader reader = AuditReaderFactory.get(entityManager); List<Number> revisionNumbers = reader.getRevisions(type, id); if (pageable.getOffset() > revisionNumbers.size()) { return new PageImpl<Revision<N, T>>(Collections.<Revision<N, T>> emptyList(), pageable, 0); } int upperBound = pageable.getOffset() + pageable.getPageSize(); upperBound = upperBound > revisionNumbers.size() ? revisionNumbers.size() : upperBound; List<? extends Number> subList = revisionNumbers.subList(pageable.getOffset(), upperBound); Revisions<N, T> revisions = getEntitiesForRevisions((List<N>) subList, id, reader); return new PageImpl<Revision<N, T>>(revisions.getContent(), pageable, revisionNumbers.size()); }
@Override public List<DefiniteResult> getHistoryChanges(ProcessResult processResultImpl) { List<DefiniteResult> history = new ArrayList<>(); AuditReader auditReader = AuditReaderFactory.get(this.entityManager); Long id = processResultImpl.getId(); if (id == null) { return new ArrayList<>(); } List<Number> revisions = auditReader.getRevisions(processResultImpl.getClass(), id); DefiniteResult find = null; for (int i = 0; i < revisions.size(); i++) { Number revision = revisions.get(i); find = auditReader.find(DefiniteResultImpl.class, id, revision); history.add(find); } return history; }
/** * Builds the query to insert new {@link com.box.l10n.mojito.entity.TMTextUnitCurrentVariant}s * as they were at the rollback date. * * @param rollbackDateTime Date at which the {@link TMTextUnitCurrentVariant}s will be rollbacked to * @param tmId ID of the TM the {@link TMTextUnitCurrentVariant}s to be rolled back should belong to * @param extraParameters Extra parameters to filter what to rollback * @return The insert audit query */ protected AuditQuery buildInsertAuditQuery(DateTime rollbackDateTime, Long tmId, CurrentVariantRollbackParameters extraParameters) { logger.trace("Building the insert tmTextUnitCurrentVariants audit query"); AuditReader auditReader = AuditReaderFactory.get(entityManager); Number revNumberAtDate = auditReader.getRevisionNumberForDate(rollbackDateTime.toDate()); AuditQuery auditQuery = auditReader.createQuery() .forEntitiesAtRevision(TMTextUnitCurrentVariant.class, TMTextUnitCurrentVariant.class.getName(), revNumberAtDate, true) .add(AuditEntity.property("tm_id").eq(tmId)); List<Long> localeIdsToRollback = extraParameters.getLocaleIds(); if (localeIdsToRollback != null && !localeIdsToRollback.isEmpty()) { // Using "in" does not work with relatedId() nor property() so using loop instead for (Long localeIdToRollback : localeIdsToRollback) { auditQuery.add(AuditEntity.relatedId("locale").eq(localeIdToRollback)); } } List<Long> tmTextUnitIdsToRollback = extraParameters.getTmTextUnitIds(); if (tmTextUnitIdsToRollback != null && !tmTextUnitIdsToRollback.isEmpty()) { // Using "in" does not work with relatedId() nor property() so using loop instead for (Long tmTextUnitIdToRollback : tmTextUnitIdsToRollback) { auditQuery.add(AuditEntity.relatedId("tmTextUnit").eq(tmTextUnitIdToRollback)); } } return auditQuery; }
@Test public void persist1() throws Exception { if (!JBOSS.equals(APPSERVER)) { return; } log.info("start persist1()"); AuditedTComplexEntity ce = createAuditedTComplexEntity(); applEman.persist(ce); applEman.getTransaction().commit(); applEman.getTransaction().begin(); List<Archive> archList = ArchiveLoader.loadArchivesByPrimaryKeyId(AuditedTComplexEntity.class.getName(), String.valueOf(ce.getId())); Assert.assertEquals(1, archList.size()); Resource res0 = archList.get(0).getResource(); Assert.assertEquals(2, res0.getParameters().size()); ResourceParameter rp1 = res0.getParameters().iterator().next(); ResourceParameter rp2 = res0.getParameters().iterator().next(); Assert.assertTrue("compValue".equals(rp1.getName()) || "owner".equals(rp1.getName())); Assert.assertTrue("compValue".equals(rp2.getName()) || "owner".equals(rp2.getName())); AuditReader ar = AuditReaderFactory.get(applEman); AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true); List<AuditedTComplexEntity> resList = query.getResultList(); Assert.assertEquals(1, resList.size()); AuditedTComplexEntity ce2 = resList.get(0); Assert.assertEquals(2, ce2.getEagerList().size()); }
@SuppressWarnings("unchecked") public static List<Object[]> track(int tid) { try (Session s = SQLCore.sf.openSession()) { AuditReader reader = getAuditReader(s); return reader.createQuery() .forRevisionsOfEntity(Ticket.class, false, true) .addOrder(AuditEntity.revisionNumber().desc()) .add(AuditEntity.id().eq(tid)) .getResultList() ; } }
/** * {@inheritDoc} */ @Override public List<RevisionMetadata> getRevisionHistoryMetadata(Object id) { AuditReader auditReader = getAuditReader(); List<Number> revisionList = auditReader.getRevisions(getEntityClass(), id); List<RevisionMetadata> result = new ArrayList<RevisionMetadata>(); for (Number revision : revisionList) { Long revisionLong = Long.valueOf(revision.longValue()); result.add(new LazyRevisionMetadata(this.persistenceManager, revisionLong)); } return result; }
public List getProjectRevisions() { final Session s = openSession(); final AuditReader ar = AuditReaderFactory.get( s ); return ar.createQuery() .forRevisionsOfEntity(Project.class, false, true) .getResultList(); }
public List getProjectRevisions(String property) { final Session s = openSession(); final AuditReader ar = AuditReaderFactory.get( s ); return ar.createQuery() .forRevisionsOfEntity(Project.class, false, true) .add(AuditEntity.property(property).hasChanged()) .getResultList(); }
public List getRevisionProjects(int revisionNumber) { final Session s = openSession(); final AuditReader ar = AuditReaderFactory.get( s ); return ar.createQuery() .forEntitiesAtRevision(Project.class, revisionNumber) .getResultList(); }
@Override @SuppressWarnings("unchecked") public Revisions<N, T> findRevisions(ID id) { Class<T> type = entityInformation.getJavaType(); AuditReader reader = AuditReaderFactory.get(entityManager); List<? extends Number> revisionNumbers = reader.getRevisions(type, id); return revisionNumbers.isEmpty() ? new Revisions<N, T>(Collections.EMPTY_LIST) : getEntitiesForRevisions((List<N>) revisionNumbers, id, reader); }
@SuppressWarnings("unchecked") private Revisions<N, T> getEntitiesForRevisions(List<N> revisionNumbers, ID id, AuditReader reader) { Class<T> type = entityInformation.getJavaType(); Map<N, T> revisions = new HashMap<N, T>(revisionNumbers.size()); Class<?> revisionEntityClass = revisionEntityInformation.getRevisionEntityClass(); Map<Number, Object> revisionEntities = (Map<Number, Object>) reader.findRevisions(revisionEntityClass, new HashSet<Number>(revisionNumbers)); for (Number number : revisionNumbers) { revisions.put((N) number, reader.find(type, id, number)); } return new Revisions<N, T>(toRevisions(revisions, revisionEntities)); }
public List<RevisionInfo> findRevisions(String id) { List<RevisionInfo> list = new ArrayList<>(); AuditReader reader = AuditReaderFactory.get(getEntityManager()); List<Number> revisions = reader.getRevisions(getEntityClass(), id); for (Number n : revisions) { CustomRevisionEntity revEntity = reader.findRevision(CustomRevisionEntity.class, n); list.add(new RevisionInfo(n, revEntity)); } return list; }
public E findRevision(String id, Number revision) { AuditReader reader = AuditReaderFactory.get(getEntityManager()); List<Number> revisions = reader.getRevisions(getEntityClass(), id); if (!revisions.contains(revision)) { return null; } E entity = reader.find(getEntityClass(), id, revision); return entity; }
private AuditReader getAuditReader() { return AuditReaderFactory.get(entityManager); }
public static AuditReader getAuditReader(Session session) { return AuditReaderFactory.get(session); }
/** * @return the auditReader */ protected AuditReader getAuditReader() { return AuditReaderFactory.get(getEntityManager()); }
public List<HistoryDto> findLegalHistoryByPatient(long patientId) { EntityManager em2 = entityManagerFactory.createEntityManager(); AuditReader reader2 = AuditReaderFactory.get(em2); Set<Number> legalList = new HashSet<Number>(); List<ModifiedEntityTypeEntity> metes = modifiedEntityTypeEntityRepository .findAll(); for (ModifiedEntityTypeEntity m : metes) { String entityname = m.getEntityClassName() .substring(m.getEntityClassName().lastIndexOf('.') + 1) .trim(); if (entityname.equals("PatientLegalRepresentativeAssociation")) { long revisionId = m.getRevision().getId(); Byte bt = m.getRevisionType(); if (bt != 2) { AuditQuery query = reader2 .createQuery() .forEntitiesAtRevision( PatientLegalRepresentativeAssociation.class, revisionId); List<PatientLegalRepresentativeAssociation> psList = (List<PatientLegalRepresentativeAssociation>) query.getResultList(); for (PatientLegalRepresentativeAssociation ps : psList) { PatientLegalRepresentativeAssociationPk pks=ps.getPatientLegalRepresentativeAssociationPk(); Patient pl=pks.getPatient(); if(pl!=null) { if (patientId == pl.getId()) { Long LegalId = ps.getId(); List<Number> revisionListLegal = reader2 .getRevisions( PatientLegalRepresentativeAssociation.class, LegalId); legalList.addAll(revisionListLegal); Long LegalRepId = ps .getPatientLegalRepresentativeAssociationPk() .getLegalRepresentative().getId(); List<Number> revisionListLegal2 = reader2 .getRevisions(Patient.class, LegalRepId); legalList.addAll(revisionListLegal2); } } } } } } Set<Number> removeLegalList = new HashSet<Number>(); for (Number a : legalList) { RevisionInfoEntity patientRevisionEntity = patientRevisionEntityRepository .findOneById(a); List<ModifiedEntityTypeEntity> meteLegalLists = modifiedEntityTypeEntityRepository .findAllByRevision(patientRevisionEntity); for (ModifiedEntityTypeEntity meteLegal : meteLegalLists) { if (meteLegal.getRevisionType() == 0) { String en = new String(meteLegal.getEntityClassName()); if (en.substring(en.lastIndexOf('.') + 1).trim() .equals("Patient")) { removeLegalList.add(a); } } } } legalList.removeAll(removeLegalList); em2.close(); List<Number> legalList2 = new ArrayList<Number>(legalList); List<HistoryDto> historyLegals = (List<HistoryDto>) findLegalHistoryDetails(legalList2); return historyLegals; }
/** * Gets the configuration. * * @param clusterId * the cluster id * @return the configuration */ public List getConfiguration(Long clusterId) { try { AuditReader reader = AuditReaderFactory.get(HibernateUtils .getEntityManager()); AuditQuery query = reader.createQuery().forRevisionsOfEntity( Configuration.class, false, true); // filter results besed on cluster id. query.add(AuditEntity.property( com.impetus.ankush2.constant.Constant.Keys.CLUSTERID).eq( clusterId)); query.addOrder(AuditEntity.revisionProperty( com.impetus.ankush2.constant.Constant.Keys.TIMESTAMP) .desc()); // Getting Result list. List list = query.getResultList(); // Creating List Object. List result = new ArrayList(); for (Object object : list) { Object[] obj = (Object[]) object; Map map = new HashMap(); // Mapping Revision Entity. DefaultRevisionEntity ri = (DefaultRevisionEntity) obj[1]; map.putAll(JsonMapperUtil.mapFromObject(obj[0])); map.put(com.impetus.ankush2.constant.Constant.Keys.DATE, ri.getRevisionDate()); map.put(com.impetus.ankush2.constant.Constant.Keys.REVISIONID, ri.getId()); map.put(com.impetus.ankush2.constant.Constant.Keys.TYPE, obj[2]); result.add(map); } return result; } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; }
public Map<Number, DefaultRevisionEntity> getRevisions(long id) { Session s = hibernateUtil.getSession(); AuditReader reader = AuditReaderFactory.get(s); List<Number> revisionNums = reader.getRevisions( DataPoint.class, id ); return reader.findRevisions( DefaultRevisionEntity.class, new HashSet<Number>(revisionNums) ); }
public void testBasicUsage() { // create a couple of events EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist( new Event( "Our very first event!", new Date() ) ); entityManager.persist( new Event( "A follow up event", new Date() ) ); entityManager.getTransaction().commit(); entityManager.close(); // now lets pull events from the database and list them entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); List<Event> result = entityManager.createQuery( "from Event", Event.class ).getResultList(); for ( Event event : result ) { System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() ); } entityManager.getTransaction().commit(); entityManager.close(); // so far the code is the same as we have seen in previous tutorials. Now lets leverage Envers... // first lets create some revisions entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); Event myEvent = entityManager.find( Event.class, 2L ); // we are using the increment generator, so we know 2 is a valid id myEvent.setDate( new Date() ); myEvent.setTitle( myEvent.getTitle() + " (rescheduled)" ); entityManager.getTransaction().commit(); entityManager.close(); // and then use an AuditReader to look back through history entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); myEvent = entityManager.find( Event.class, 2L ); assertEquals( "A follow up event (rescheduled)", myEvent.getTitle() ); AuditReader reader = AuditReaderFactory.get( entityManager ); Event firstRevision = reader.find( Event.class, 2L, 1 ); assertFalse( firstRevision.getTitle().equals( myEvent.getTitle() ) ); assertFalse( firstRevision.getDate().equals( myEvent.getDate() ) ); Event secondRevision = reader.find( Event.class, 2L, 2 ); assertTrue( secondRevision.getTitle().equals( myEvent.getTitle() ) ); assertTrue( secondRevision.getDate().equals( myEvent.getDate() ) ); entityManager.getTransaction().commit(); entityManager.close(); }
@Test public void testRegion() { entityManager.getTransaction().begin(); RegionDao regionDao = injector.getInstance(RegionDao.class); Region germany = new Region(Region.GERMANY); String id1 = regionDao.save(germany); Assert.assertNotNull("ID expected", id1); List<Region> all = regionDao.findAll(); Assert.assertTrue("1 Region expected", all.size()==1); Region europe = new Region(Region.EUROPE); String id2 = regionDao.save(europe); all = regionDao.findAll(); Assert.assertTrue("2 Regions expected", all.size()==2); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); Region loadedGermany = regionDao.findByExactName(Region.GERMANY); Assert.assertNotNull(loadedGermany); Assert.assertEquals(loadedGermany.getId(), id1); Assert.assertEquals(loadedGermany, germany); Region loadedEurope = regionDao.findByExactName(Region.EUROPE); Assert.assertNotNull(loadedEurope); Assert.assertEquals(loadedEurope.getId(), id2); Assert.assertEquals(loadedEurope, europe); loadedEurope.setDescription("this is changed europe"); regionDao.save(loadedEurope); all = regionDao.findAll(); Assert.assertTrue("2 Regions expected", all.size()==2); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); Region loadedEurope2 = regionDao.findByExactName(Region.EUROPE); loadedEurope2.setDescription("this is twice changed europe"); regionDao.save(loadedEurope); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); AuditReader auditReader = AuditReaderFactory.get(entityManager); List<Number> revisionNumbers = auditReader.getRevisions(Region.class, loadedEurope.getId()); // System.out.println(revisionNumbers + " revisions found."); for (Number number : revisionNumbers) { // System.out.println("RevisionNumber: " + number); Region regionWithRevision = auditReader.find(Region.class, loadedEurope.getId(), number); // try { // System.out.println("Region with revision " + number + "\n" // + new ObjectMapper().writeValueAsString(regionWithRevision)); // } catch (JsonProcessingException e) { // Assert.fail(e.getMessage()); // } Assert.assertNotNull(regionWithRevision); } entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); regionDao.delete(loadedEurope); regionDao.delete(loadedGermany); List<Region> regionList = regionDao.findAll(); Assert.assertEquals(0, regionList.size()); entityManager.getTransaction().commit(); }
/** * looking for initial revision of entity(for first database insert). * * @param auditReader * envers reader implementation * @param persistentClass * something that extends {@link AbstractPersistentEntity} * @param uniqueIdentifier * primary key of entity * @return revision number */ public static Number initialRevision(AuditReader auditReader, Class<? extends IBO> persistentClass, long uniqueIdentifier) { return (Number) auditReader.createQuery() .forRevisionsOfEntity(persistentClass, true, true) .add(AuditEntity.id().eq(uniqueIdentifier)) .add(AuditEntity.revisionType().eq(RevisionType.ADD)) .addProjection(AuditEntity.revisionNumber().min()) .getSingleResult(); }
/** * looking for latest modify revision of entity(for latest database * update/delete). * * @param auditReader * envers reader implementation * @param persistentClass * something that extends {@link AbstractPersistentEntity} * @param uniqueIdentifier * primary key of entity * @return revision number */ public static Number latestModifyRevision(AuditReader auditReader, Class<? extends IBO> persistentClass, long uniqueIdentifier) { return (Number) auditReader .createQuery() .forRevisionsOfEntity(persistentClass, true, true) .add(AuditEntity.id().eq(uniqueIdentifier)) .add(AuditEntity.revisionType() .in(new RevisionType[] { RevisionType.MOD, RevisionType.DEL })) .addProjection(AuditEntity.revisionNumber().max()) .getSingleResult(); }