org.javers.core.Javers Java Examples

The following examples show how to use org.javers.core.Javers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicValueObjectDiffExample.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCompareTwoObjects() {

  //given
  Javers javers = JaversBuilder.javers().build();

  Address address1 = new Address("New York","5th Avenue");
  Address address2 = new Address("New York","6th Avenue");

  //when
  Diff diff = javers.compare(address1, address2);

  //then
  //there should be one change of type {@link ValueChange}
  ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

  assertThat(diff.getChanges()).hasSize(1);
  assertThat(change.getAffectedGlobalId().value())
            .isEqualTo("org.javers.core.examples.model.Address/");
  assertThat(change.getPropertyName()).isEqualTo("street");
  assertThat(change.getLeft()).isEqualTo("5th Avenue");
  assertThat(change.getRight()).isEqualTo("6th Avenue");

  System.out.println(diff);
}
 
Example #2
Source File: JaversUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() {
    // given
    Javers javers = JaversBuilder.javers().build();

    PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));

    PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList());

    // when
    Diff diff = javers.compare(person, personWithNewAddress);
    List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class);

    // then
    assertThat(objectsByChangeType).hasSize(1);
    assertThat(objectsByChangeType.get(0).equals(new Address("England")));
}
 
Example #3
Source File: JaversUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() {
    // given
    Javers javers = JaversBuilder.javers().build();

    PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));

    PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA")));

    // when
    Diff diff = javers.compare(person, personWithNewAddress);
    List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class);

    // then
    assertThat(objectsByChangeType).hasSize(1);
    assertThat(objectsByChangeType.get(0).equals(new Address("USA")));
}
 
Example #4
Source File: JaversUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() {
    // given
    Javers javers = JaversBuilder.javers().build();
    Person personThatWillBeRemoved = new Person(2, "Thomas Link");
    List<Person> oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved);
    List<Person> newList = Lists.asList(new Person(1, "Michael Not Program"));

    // when
    Diff diff = javers.compareCollections(oldList, newList, Person.class);

    // then
    assertThat(diff.getChanges()).hasSize(3);

    ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0);
    assertThat(valueChange.getPropertyName()).isEqualTo("name");
    assertThat(valueChange.getLeft()).isEqualTo("Michael Program");
    assertThat(valueChange.getRight()).isEqualTo("Michael Not Program");

    ObjectRemoved objectRemoved = diff.getChangesByType(ObjectRemoved.class).get(0);
    assertThat(objectRemoved.getAffectedObject().get().equals(personThatWillBeRemoved)).isTrue();

    ListChange listChange = diff.getChangesByType(ListChange.class).get(0);
    assertThat(listChange.getValueRemovedChanges().size()).isEqualTo(1);

}
 
Example #5
Source File: JaversUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() {
    // given
    Javers javers = JaversBuilder.javers().build();

    Person person = new Person(1, "Michael Program");
    Person personAfterModification = new Person(1, "Michael Java");

    // when
    Diff diff = javers.compare(person, personAfterModification);

    // then
    ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

    assertThat(diff.getChanges()).hasSize(1);
    assertThat(change.getPropertyName()).isEqualTo("name");
    assertThat(change.getLeft()).isEqualTo("Michael Program");
    assertThat(change.getRight()).isEqualTo("Michael Java");
}
 
Example #6
Source File: JaversSpringJpaApplicationConfig.java    From javers with Apache License 2.0 6 votes vote down vote up
/**
 * Creates JaVers instance with {@link JaversSqlRepository}
 */
@Bean
public Javers javers(PlatformTransactionManager txManager) {
    JaversSqlRepository sqlRepository = SqlRepositoryBuilder
            .sqlRepository()
            .withConnectionProvider(jpaConnectionProvider())
            .withDialect(DialectName.H2)
            .build();

    return TransactionalJaversBuilder
            .javers()
            .withTxManager(txManager)
            .withObjectAccessHook(new HibernateUnproxyObjectAccessHook())
            .registerJaversRepository(sqlRepository)
            .build();
}
 
Example #7
Source File: ChangedPropertyNamesForNullifiedValuesCase.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateChangedPropertyNamesForNullifiedValues() {
    //given
    Javers javers = JaversBuilder.javers().build();
    SimpleTypes obj = new SimpleTypes("1");
    javers.commit("anonymous", obj);

    //when
    obj.shortNumber = -1;
    javers.commit("anonymous", obj);
    CdoSnapshot s = javers.getLatestSnapshot("1", SimpleTypes.class).get();

    //then
    Assertions.assertThat(s.getChanged()).containsExactly("shortNumber");

    //when
    obj.nullify();
    javers.commit("anonymous", obj);
    s = javers.getLatestSnapshot("1", SimpleTypes.class).get();

    //then
    Assertions.assertThat(s.getChanged()).hasSize(11);
}
 
Example #8
Source File: Case250CharSequence.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCompareTwoObjectsWithCharSequencePropertiesOfString() {
    //given
    Javers javers = JaversBuilder.javers().build();

    AvroAddress oldVersion = new AvroAddress("New York", "First Avenue");
    AvroAddress currentVersion = new AvroAddress("New York", "Second Avenue");

    //when
    Diff diff = javers.compare(oldVersion, currentVersion);
    System.out.println(diff);

    //then
    ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

    assertThat(diff.getChanges()).hasSize(1);
    assertThat(change.getPropertyName()).isEqualTo("street");
    assertThat(change.getLeft()).isEqualTo(oldVersion.getStreet());
    assertThat(change.getRight()).isEqualTo(currentVersion.getStreet());
}
 
Example #9
Source File: NpeFromReflectionUtilCase.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSupportInterfaceProperty() {
    // given
    TestClassWithInterfaceProperty foo = new TestClassWithInterfaceProperty("1", new TestInterfaceImpl("Foo"));
    TestClassWithInterfaceProperty bar = new TestClassWithInterfaceProperty("1", new TestInterfaceImpl("Bar"));
    Javers javers = JaversBuilder.javers().build();

    // when
    Diff diff = javers.compare(foo, bar);

    System.out.println(diff);

    // then
    assertTrue(diff.getChanges().size() == 1);
    ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
    ValueObjectIdDTO voId = ValueObjectIdDTO.valueObjectId("1", TestClassWithInterfaceProperty.class, "interfaceProperty");

    Assertions.assertThat(change.getAffectedGlobalId().value()).isEqualTo(voId.value());
    Assertions.assertThat(change.getPropertyName()).isEqualTo("value");
    Assertions.assertThat(change.getLeft()).isEqualTo("Foo");
    Assertions.assertThat(change.getRight()).isEqualTo("Bar");
}
 
Example #10
Source File: JsonTypeAdapterExample.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeValueToJsonWithTypeAdapter() {
    //given
    Javers javers = JaversBuilder.javers()
            .registerValueTypeAdapter(new ObjectIdTypeAdapter())
            .build();

    //when
    ObjectId id = ObjectId.get();
    MongoStoredEntity entity1 = new MongoStoredEntity(id, "alg1", "1.0", "name");
    MongoStoredEntity entity2 = new MongoStoredEntity(id, "alg1", "1.0", "another");
    Diff diff = javers.compare(entity1, entity2);

    //then
    String json = javers.getJsonConverter().toJson(diff);
    Assertions.assertThat(json).contains(id.toString());

    System.out.println(json);
}
 
Example #11
Source File: AuditableAspectConfiguration.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the javers.
 *
 * @param txManager the tx manager
 * @return the javers
 */
@Bean
public Javers getJavers(final PlatformTransactionManager txManager) {
	final JaversSqlRepository sqlRepository = SqlRepositoryBuilder.sqlRepository()
			.withConnectionProvider(new ConnectionProvider() {

				@Override
				public Connection getConnection() {
					final SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);

					return session.connection();
				}
			}).withDialect(DialectName.POSTGRES).build();

	return TransactionalJaversBuilder.javers().withTxManager(txManager)
			.withObjectAccessHook(new HibernateUnproxyObjectAccessHook()).registerJaversRepository(sqlRepository)
			.withMappingStyle(MappingStyle.BEAN).build();
}
 
Example #12
Source File: ComparingTopLevelCollectionExample.java    From javers with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeeplyCompareTwoTopLevelCollections() {
  //given
  Javers javers = JaversBuilder.javers().build();

  List<Person> oldList = Lists.asList( new Person("tommy", "Tommy Smart") );
  List<Person> newList = Lists.asList( new Person("tommy", "Tommy C. Smart") );

  //when
  Diff diff = javers.compareCollections(oldList, newList, Person.class);

  //then
  //there should be one change of type {@link ValueChange}
  ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

  assertThat(diff.getChanges()).hasSize(1);
  assertThat(change.getPropertyName()).isEqualTo("name");
  assertThat(change.getLeft()).isEqualTo("Tommy Smart");
  assertThat(change.getRight()).isEqualTo("Tommy C. Smart");

  System.out.println(diff);
}
 
Example #13
Source File: JaversSqlAutoConfiguration.java    From javers with Apache License 2.0 5 votes vote down vote up
@Bean(name = "JaversFromStarter")
@ConditionalOnMissingBean
public Javers javers(JaversSqlRepository sqlRepository, PlatformTransactionManager transactionManager) {
    return TransactionalJaversBuilder
            .javers()
            .withTxManager(transactionManager)
            .registerJaversRepository(sqlRepository)
            .withObjectAccessHook(javersSqlProperties.createObjectAccessHookInstance())
            .withProperties(javersSqlProperties)
            .build();
}
 
Example #14
Source File: JaversMongoAutoConfiguration.java    From javers with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "javers.auditableAspectEnabled", havingValue = "true", matchIfMissing = true)
public JaversAuditableAspect javersAuditableAspect(
        Javers javers,
        AuthorProvider authorProvider,
        CommitPropertiesProvider commitPropertiesProvider) {
    return new JaversAuditableAspect(javers, authorProvider, commitPropertiesProvider);
}
 
Example #15
Source File: JaversSpringMongoApplicationConfig.java    From javers with Apache License 2.0 5 votes vote down vote up
/**
 * Creates JaVers instance backed by {@link MongoRepository}
 */
@Bean
public Javers javers() {
    MongoRepository javersMongoRepository =
            new MongoRepository(mongo().getDatabase(DATABASE_NAME));

    return JaversBuilder.javers()
            .registerJaversRepository(javersMongoRepository)
            .build();
}
 
Example #16
Source File: TransactionalJaversBuilder.java    From javers with Apache License 2.0 5 votes vote down vote up
@Override
public Javers build() {
    if (txManager == null) {
        throw new JaversException(JaversExceptionCode.TRANSACTION_MANAGER_NOT_SET);
    }

    Javers javersCore = super.assembleJaversInstance();

    Javers javersTransactional =
            new JaversTransactionalDecorator(javersCore, getContainerComponent(JaversSqlRepository.class), txManager);

    return javersTransactional;
}
 
Example #17
Source File: JaversMongoAutoConfiguration.java    From javers with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "javers.springDataAuditableRepositoryAspectEnabled", havingValue = "true", matchIfMissing = true)
public JaversSpringDataAuditableRepositoryAspect javersSpringDataAuditableAspect(
        Javers javers,
        AuthorProvider authorProvider,
        CommitPropertiesProvider commitPropertiesProvider) {
    return new JaversSpringDataAuditableRepositoryAspect(javers, authorProvider, commitPropertiesProvider);
}
 
Example #18
Source File: Case249GenericId.java    From javers with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCommitEntityWithSerializableId() {
    //given
    Javers javers = JaversBuilder.javers().
            registerJaversRepository(H2RepositoryFactory.create()).build();

    //when
    Account acc = new Account("1","2");
    javers.commit("author", acc);

    //then
    CdoSnapshot snapshot = javers.getLatestSnapshot("1", Account.class).get();
    Assertions.assertThat(snapshot.getPropertyValue("id")).isEqualTo("1");
    Assertions.assertThat(snapshot.getPropertyValue("value")).isEqualTo("2");
}
 
Example #19
Source File: JaversMongoAutoConfiguration.java    From javers with Apache License 2.0 5 votes vote down vote up
@Bean(name = "JaversFromStarter")
@ConditionalOnMissingBean
public Javers javers() {
    logger.info("Starting javers-spring-boot-starter-mongo ...");

    MongoDatabase mongoDatabase = initJaversMongoDatabase();

    MongoRepository javersRepository = createMongoRepository(mongoDatabase);

    return JaversBuilder.javers()
            .registerJaversRepository(javersRepository)
            .withProperties(javersMongoProperties)
            .withObjectAccessHook(javersMongoProperties.createObjectAccessHookInstance())
            .build();
}
 
Example #20
Source File: EmployeeHierarchiesDiffExample.java    From javers with Apache License 2.0 5 votes vote down vote up
/** {@link ReferenceChange} example */
@Test
public void shouldDetectBossChange() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss")
      .addSubordinates(
           new Employee("Manager One")
               .addSubordinate(new Employee("Great Developer")),
           new Employee("Manager Second"));

  Employee newBoss = new Employee("Big Boss")
      .addSubordinates(
           new Employee("Manager One"),
           new Employee("Manager Second")
               .addSubordinate(new Employee("Great Developer")));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  ReferenceChange change = diff.getChangesByType(ReferenceChange.class).get(0);

  assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
  assertThat(change.getLeft().value()).endsWith("Manager One");
  assertThat(change.getRight().value()).endsWith("Manager Second");

  System.out.println(diff);
}
 
Example #21
Source File: EmployeeHierarchiesDiffExample.java    From javers with Apache License 2.0 5 votes vote down vote up
/** {@link ValueChange} example */
@Test
public void shouldDetectSalaryChange(){
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss")
          .addSubordinates(
                  new Employee("Noisy Manager"),
                  new Employee("Great Developer", 10000));

  Employee newBoss = new Employee("Big Boss")
          .addSubordinates(
                  new Employee("Noisy Manager"),
                  new Employee("Great Developer", 20000));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  ValueChange change =  diff.getChangesByType(ValueChange.class).get(0);

  assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
  assertThat(change.getPropertyName()).isEqualTo("salary");
  assertThat(change.getLeft()).isEqualTo(10000);
  assertThat(change.getRight()).isEqualTo(20000);

  System.out.println(diff);
}
 
Example #22
Source File: EmployeeHierarchiesDiffExample.java    From javers with Apache License 2.0 5 votes vote down vote up
/** {@link ObjectRemoved} example */
@Test
public void shouldDetectFired() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss")
          .addSubordinates(
                  new Employee("Great Developer"),
                  new Employee("Team Lead").addSubordinates(
                          new Employee("Another Dev"),
                          new Employee("To Be Fired")
                  ));

  Employee newBoss = new Employee("Big Boss")
          .addSubordinates(
                  new Employee("Great Developer"),
                  new Employee("Team Lead").addSubordinates(
                          new Employee("Another Dev")
                  ));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  assertThat(diff.getChangesByType(ObjectRemoved.class)).hasSize(1);

  System.out.println(diff);
}
 
Example #23
Source File: EmployeeHierarchiesDiffExample.java    From javers with Apache License 2.0 5 votes vote down vote up
/** {@link NewObject} example */
@Test
public void shouldDetectHired() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss")
      .addSubordinates(
          new Employee("Great Developer"));

  Employee newBoss = new Employee("Big Boss")
      .addSubordinates(
          new Employee("Great Developer"),
          new Employee("Hired One"),
          new Employee("Hired Second"));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  assertThat(diff.getObjectsByChangeType(NewObject.class))
      .hasSize(2)
      .containsOnly(new Employee("Hired One"),
                    new Employee("Hired Second"));

  System.out.println(diff);
}
 
Example #24
Source File: Application.java    From javers with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.out.println(".. Starting javers-core runtime environment self test ...");

    System.out.println("java.runtime.name:          " + System.getProperty("java.runtime.name"));
    System.out.println("java.vendor:                " + System.getProperty("java.vendor"));
    System.out.println("java.runtime.version:       " + System.getProperty("java.runtime.version"));
    System.out.println("java.version:               " + System.getProperty("java.version"));
    System.out.println("java.home:                  " + System.getProperty("java.home"));
    System.out.println("os.name & ver:              " + System.getProperty("os.name")+" v."+System.getProperty("os.version"));

    System.out.println(".. building JaVers instance ...");

    try {
        Javers javers = JaversBuilder.javers().build();

        SampleValueObject left = new SampleValueObject("red");
        SampleValueObject right = new SampleValueObject("green");

        System.out.println(".. calculating diff for two simple ValueObjects...");
        Diff diff = javers.compare(left, right);

        conditionFulfilled(diff.getChanges().size() == 1, "assertion failed");
        conditionFulfilled(diff.getPropertyChanges("color").size() == 1, "assertion failed");

        System.out.println(".. self test PASSED ..");
    }catch(Throwable e) {
        System.out.println(e);
        e.printStackTrace();
        System.out.println(".. self test FAILED! ..");
    }
}
 
Example #25
Source File: ReflectionUtil.java    From javers with Apache License 2.0 5 votes vote down vote up
/**
 * throws RuntimeException if class is not found
 */
public static Class<?> classForName(String className) {
    try {
        return Class.forName(className, false, Javers.class.getClassLoader());
    }
    catch (ClassNotFoundException ex) {
        throw new JaversException(JaversExceptionCode.CLASS_NOT_FOUND, className);
    }
}
 
Example #26
Source File: ReflectionUtil.java    From javers with Apache License 2.0 5 votes vote down vote up
public static boolean isClassPresent(String className) {
    try {
        Class.forName(className, false, Javers.class.getClassLoader());
        return true;
    }
    catch (Throwable ex) {
        // Class or one of its dependencies is not present...
        return false;
    }
}
 
Example #27
Source File: HibernateConfig.java    From javers with Apache License 2.0 4 votes vote down vote up
@Bean
public JaversAuditableAspect javersAuditableAspect(Javers javers) {
    return new JaversAuditableAspect(javers, authorProvider(), commitPropertiesProvider());
}
 
Example #28
Source File: JaversTransactionalDecorator.java    From javers with Apache License 2.0 4 votes vote down vote up
JaversTransactionalDecorator(Javers delegate, JaversSqlRepository javersSqlRepository, PlatformTransactionManager txManager) {
    Validate.argumentsAreNotNull(delegate, javersSqlRepository, txManager);
    this.delegate = delegate;
    this.javersSqlRepository = javersSqlRepository;
    this.txManager = txManager;
}
 
Example #29
Source File: HibernateConfig.java    From javers with Apache License 2.0 4 votes vote down vote up
@Bean
public JaversSpringDataAuditableRepositoryAspect javersSpringDataAuditableAspect(Javers javers) {
    return new JaversSpringDataAuditableRepositoryAspect(javers, authorProvider(), commitPropertiesProvider());
}
 
Example #30
Source File: StoreController.java    From tutorials with MIT License 4 votes vote down vote up
public StoreController(StoreService customerService, Javers javers) {
    this.storeService = customerService;
    this.javers = javers;
}