public HandlingEvent createHandlingEvent( Date completionTime, TrackingId trackingId, CarrierMovementId carrierMovementId, UnLocode unlocode, HandlingEvent.Type type) throws UnknownTrackingIdException, UnknownCarrierMovementIdException, UnknownLocationException { Cargo cargo = validateCargoExists(trackingId); CarrierMovement carrierMovement = findCarrierMovement(carrierMovementId); Location location = findLocation(unlocode); Date registrationTime = new Date(); // Create entity UnitOfWork uow = uowf.currentUnitOfWork(); EntityBuilder<HandlingEvent> builder = uow.newEntityBuilder(HandlingEvent.class); HandlingEventState state = builder.instanceFor(HandlingEventState.class); state.cargo().set(cargo); // TODO: remove next line when query + association is implemented state.cargoTrackingId().set(trackingId.idString()); state.carrierMovement().set(carrierMovement); state.location().set(location); state.registrationTime().set(registrationTime); state.completionTime().set(completionTime); state.eventType().set(type); return builder.newInstance(); }
@Test public void whenTraceOnMixinImplExpectTwoEntryInEntityStore() throws Exception { SomeService sc = moduleInstance.serviceFinder().<SomeService>findService(SomeService.class).get(); assertEquals(123, sc.doSomethingImportant()); assertEquals(789, sc.doSomethingModeratelyImportant()); UnitOfWork uow = unitOfWorkFactory.newUnitOfWork(); try { QueryBuilder<TraceRecord> builder = queryBuilderFactory.newQueryBuilder(TraceRecord.class); Query<TraceRecord> query = builder.newQuery(uow); // IS sorting needed?? TraceRecord template = templateFor(TraceRecord.class); query.orderBy(orderBy(template.methodName())); Iterator<TraceRecord> result = query.iterator(); assertTrue(result.hasNext()); TraceRecord rec1 = result.next(); assertEquals("doSomethingImportant", rec1.methodName().get()); assertTrue(result.hasNext()); TraceRecord rec2 = result.next(); assertEquals("doSomethingModeratelyImportant", rec2.methodName().get()); assertFalse(result.hasNext()); uow.complete(); } catch (Exception e) { uow.discard(); throw e; } catch (Error e) { uow.discard(); throw e; } }
@Override public void tearDown() throws Exception { if (module.isUnitOfWorkActive()) { UnitOfWork uow = module.currentUnitOfWork(); uow.discard(); } super.tearDown(); }
@Override public void passivate() throws Exception { UnitOfWork uow = uowf.newUnitOfWork(); try { RootEntity root = rootEntity(); LOGGER.info("Existing RootEntity: " + root.identity().get()); } catch (NoSuchEntityException ex) { LOGGER.info("No RootEntity"); } uow.complete(); }
@Test public void payAllBills() throws Exception { UnitOfWork uow = module.newUnitOfWork(newUsecase("Pay all bills from checking to creditors")); try { BalanceData source = uow.get(BalanceData.class, CHECKING_ACCOUNT_ID); PayBillsContext2 context = module.newObject(PayBillsContext2.class); context.bind(source).payBills(); } finally { uow.discard(); } }
public Subject authenticate(Object credentials) { UnitOfWork unitOfWork = module .unitOfWorkFactory() .newUnitOfWork(UsecaseBuilder.newUsecase("Authenticate JMX user")); Subject subject = null; try { if (!(credentials instanceof String[])) { // Special case for null so we get a more informative message if (credentials == null) { throw new SecurityException("Credentials required"); } throw new SecurityException("Credentials should be String[]"); } final String[] aCredentials = (String[]) credentials; if (aCredentials.length != 2) { throw new SecurityException("Credentials should have 2 elements"); } String username = aCredentials[0]; String password = aCredentials[1]; Authentication user = unitOfWork.get(Authentication.class, username); if (!user.login(password)) { throw new SecurityException("User/password combination not valid."); } if (((UserAuthentication.Data) user).isAdministrator()) { subject = new Subject( true, Collections.singleton(new JMXPrincipal(username)), Collections.EMPTY_SET, Collections.EMPTY_SET); } else { throw new SecurityException("Invalid credentials"); } unitOfWork.complete(); } catch (Throwable e) { unitOfWork.discard(); throw new SecurityException(e); } return subject; }
@Override public Iterable<TimelineRecord> getNextRecords(int maxResults) { SortedSet<TimelineRecord> result = new TreeSet<>(); UnitOfWork uow = module.currentUnitOfWork(); String schedulesName = SchedulerMixin.getSchedulesIdentity(scheduler); Schedules schedules = uow.get(Schedules.class, schedulesName); for (Schedule schedule : schedules.schedules()) { Timeline timeline = (Timeline) schedule; Iterable<TimelineRecord> lastRecords = timeline.getNextRecords(maxResults); Iterables.addAll(result, lastRecords); } return Iterables.limit(maxResults, result); }
@Test public void givenEntityWithImmutableAssociationWhenBuildingThenNoException() throws Exception { UnitOfWork unitOfWork = unitOfWorkFactory.newUnitOfWork(); try { PersonEntity father = unitOfWork.newEntity(PersonEntity.class); EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity instance = builder.instance(); instance.father().set(father); PersonEntity child = builder.newInstance(); } finally { unitOfWork.discard(); } }
@Override public void activate() throws Exception { UnitOfWork uow = uowf.newUnitOfWork(); try { RootEntity root = rootEntity(); LOGGER.info("Will use RootEntity: " + root.identity().get()); } catch (NoSuchEntityException ex) { EntityBuilder<RootEntity> builder = uow.newEntityBuilder(RootEntity.class, RootEntity.IDENTITY); RootEntity root = builder.newInstance(); LOGGER.info("Created new RootEntity: " + root.identity().get()); } uow.complete(); }
@Override public Iterable<TimelineRecord> getRecords(DateTime from, DateTime to) { SortedSet<TimelineRecord> result = new TreeSet<>(); UnitOfWork uow = module.currentUnitOfWork(); String schedulesName = SchedulerMixin.getSchedulesIdentity(scheduler); Schedules schedules = uow.get(Schedules.class, schedulesName); for (Schedule schedule : schedules.schedules()) { Timeline timeline = (Timeline) schedule; Iterable<TimelineRecord> lastRecords = timeline.getRecords(from, to); Iterables.addAll(result, lastRecords); } return result; }
@Test public void testOperators() throws UnitOfWorkCompletionException, ActivationException, AssemblyException { SingletonAssembler assembler = new SingletonAssembler() { @Override public void assemble(ModuleAssembly module) throws AssemblyException { new EntityTestAssembler().assemble(module); module.entities(TestEntity.class); module.values(TestValue.class); module.forMixin(TestEntity.class).declareDefaults().foo().set("Bar"); module.forMixin(TestValue.class).declareDefaults().bar().set("Xyz"); } }; UnitOfWork uow = assembler.module().newUnitOfWork(); try { EntityBuilder<TestEntity> entityBuilder = uow.newEntityBuilder(TestEntity.class, "123"); entityBuilder.instance().value().set(assembler.module().newValue(TestValue.class)); TestEntity testEntity = entityBuilder.newInstance(); uow.complete(); uow = assembler.module().newUnitOfWork(); Iterable<TestEntity> entities = Iterables.iterable(testEntity = uow.get(testEntity)); QueryBuilder<TestEntity> builder = assembler.module().newQueryBuilder(TestEntity.class); { Specification<Composite> where = QueryExpressions.eq(QueryExpressions.templateFor(TestEntity.class).foo(), "Bar"); Assert.assertTrue(where.satisfiedBy(testEntity)); System.out.println(where); } { Specification<Composite> where = QueryExpressions.eq( QueryExpressions.templateFor(TestEntity.class).value().get().bar(), "Xyz"); Assert.assertTrue(where.satisfiedBy(testEntity)); System.out.println(where); Assert.assertTrue(builder.where(where).newQuery(entities).find().equals(testEntity)); } } finally { uow.discard(); } }
@SuppressWarnings("unchecked") private <V> V initializeConfigurationInstance( ServiceComposite serviceComposite, UnitOfWork uow, ServiceDescriptor serviceModel, String identity) throws InstantiationException { Module module = api.moduleOf(serviceComposite); Usecase usecase = UsecaseBuilder.newUsecase("Configuration:" + me.identity().get()); UnitOfWork buildUow = module.newUnitOfWork(usecase); EntityBuilder<V> configBuilder = buildUow.newEntityBuilder(serviceModel.<V>configurationType(), identity); // Check for defaults String s = identity + ".properties"; Class<?> type = first(api.serviceDescriptorFor(serviceComposite).types()); // Load defaults from classpath root if available if (type.getResource(s) == null && type.getResource("/" + s) != null) { s = "/" + s; } InputStream asStream = type.getResourceAsStream(s); if (asStream != null) { try { PropertyMapper.map(asStream, (Composite) configBuilder.instance()); } catch (IOException e1) { InstantiationException exception = new InstantiationException("Could not read underlying Properties file."); exception.initCause(e1); throw exception; } } try { configBuilder.newInstance(); buildUow.complete(); // Try again return (V) findConfigurationInstanceFor(serviceComposite, uow); } catch (Exception e1) { InstantiationException ex = new InstantiationException( "Could not instantiate configuration, and no Properties file was found (" + s + ")"); ex.initCause(e1); throw ex; } }
@Test public void planActivitiesTest() throws Exception { UnitOfWork uow = assembler.unitOfWorkFactory().newUnitOfWork(UsecaseBuilder.newUsecase("Test")); try { ProjectData project = uow.get(ProjectData.class, PROJECT); new FrontloadContext(project).frontloadNetworkFrom(1); // try 2 uow.complete(); } catch (Exception e) { uow.discard(); throw e; } }
@SuppressWarnings("unchecked") public <V> V findConfigurationInstanceFor(ServiceComposite serviceComposite, UnitOfWork uow) throws InstantiationException { ServiceDescriptor serviceModel = api.serviceDescriptorFor(serviceComposite); String identity = serviceComposite.identity().get(); V configuration; try { configuration = uow.get(serviceModel.<V>configurationType(), identity); uow.pause(); } catch (NoSuchEntityException | EntityTypeNotFoundException e) { return (V) initializeConfigurationInstance(serviceComposite, uow, serviceModel, identity); } return configuration; }
public Cargo create(String originUnLocode, String destinationUnLocode, Date arrivalDeadline) { TrackingId trackingId = cargoRepository.nextTrackingId(); Location origin = locationRepository.findLocationByUnLocode(originUnLocode); Location destination = locationRepository.findLocationByUnLocode(destinationUnLocode); RouteSpecification routeSpecification = routeSpecificationFactory.create(origin, destination, arrivalDeadline); UnitOfWork uow = uowf.currentUnitOfWork(); EntityBuilder<Cargo> builder = uow.newEntityBuilder(Cargo.class, trackingId.id().get()); Cargo.State instanceState = builder.instanceFor(Cargo.State.class); instanceState.routeSpecification().set(routeSpecification); instanceState.origin().set(origin); Cargo cargo = builder.newInstance(); logger.info("Booked new cargo with tracking id " + cargo.trackingId().id().get()); return cargo; }
@Test public void testIllustrationFactory() throws UnitOfWorkCompletionException { UnitOfWork uow = unitOfWorkFactory.newUnitOfWork(); IllustrationFactory illuFactory = (IllustrationFactory) serviceLocator.findService(IllustrationFactory.class).get(); IllustrationEntity illu = (IllustrationEntity) illuFactory.create("Tagada Tsoin tsoin"); System.out.println(illu.identity().get()); System.out.println(illu.name().get()); System.out.println(illu.creationDate().get()); uow.complete(); }
@Test public void givenEntityWithImmutableManyAssociationWhenBuildingThenNoException() throws Exception { UnitOfWork unitOfWork = unitOfWorkFactory.newUnitOfWork(); try { EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity person1 = builder.instance(); person1 = builder.newInstance(); builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity person2 = builder.instance(); person2.colleagues().add(0, person1); person2 = builder.newInstance(); } finally { unitOfWork.discard(); } }
@Override public synchronized void refresh() { if (configuration != null) { configuration = null; uow.discard(); uow = null; } }
@Test public void whenTraceOnMixinTypeMethodExpectOneEntryInEntityStore() throws Exception { SomeService sc = moduleInstance.serviceFinder().<SomeService>findService(SomeService.class).get(); assertEquals(123, sc.doSomethingImportant()); assertEquals(456, sc.doSomethingLessImportant()); UnitOfWork uow = unitOfWorkFactory.newUnitOfWork(); QueryBuilder<TraceRecord> builder = queryBuilderFactory.newQueryBuilder(TraceRecord.class); Query<TraceRecord> query = builder.newQuery(uow); // IS sorting needed?? // TraceRecord template = templateFor( TraceRecord.class ); // query.orderBy( orderBy( template.methodName() ) ); Iterator<TraceRecord> result = query.iterator(); assertTrue(result.hasNext()); TraceRecord rec1 = result.next(); assertEquals("doSomethingImportant", rec1.methodName().get()); assertFalse(result.hasNext()); uow.complete(); }
@After public void printResult() throws Exception { UnitOfWork uow = assembler.unitOfWorkFactory().newUnitOfWork(newUsecase("Print Gantt chart")); try { List<ActivityData> activities = uow.get(ProjectData.class, PROJECT).allActivities(); StringBuilder sb = new StringBuilder(); sb.append("\n\n### Gantt chart showing planned activities:\n"); Collections.sort( activities, new Comparator<ActivityData>() { public int compare(ActivityData a1, ActivityData a2) { if (a1.earlyStart().get().equals(a2.earlyStart().get())) return getEntityReference(a1) .identity() .compareTo(getEntityReference(a2).identity()); else return a1.earlyStart().get() - a2.earlyStart().get(); } }); for (ActivityData activity : activities) { String id = EntityReference.getEntityReference(activity).identity(); Integer start = activity.earlyStart().get(); Integer duration = activity.duration().get(); for (int i = 1; i < start; i++) { sb.append(" "); } sb.append(id); for (int i = 0; i < duration - 1; i++) { sb.append(" ="); } sb.append("\n"); } sb.append("1 2 3 4 5 6 7 8 9"); System.out.println(sb.toString()); } finally { uow.discard(); } System.out.println("----------------------------------------------------------"); }
@Test(expected = IllegalStateException.class) public void givenEntityWithImmutableAssociationWhenChangingValueThenThrowException() throws Exception { UnitOfWork unitOfWork = unitOfWorkFactory.newUnitOfWork(); try { EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity father = builder.instance(); father = builder.newInstance(); builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity child = builder.instance(); child = builder.newInstance(); child.father().set(father); unitOfWork.complete(); } catch (Exception e) { unitOfWork.discard(); throw e; } }
@Test public void whenTraceOnConcernExpectOneEntryInEntityStore() throws Exception { // It is not possible to put Annotation on Concern Methods, so it should only record one. SomeService sc = moduleInstance.serviceFinder().<SomeService>findService(SomeService.class).get(); assertEquals(123, sc.doSomethingImportant()); assertEquals(753, sc.doSomethingInsanelyImportant()); UnitOfWork uow = unitOfWorkFactory.newUnitOfWork(); QueryBuilder<TraceRecord> builder = queryBuilderFactory.newQueryBuilder(TraceRecord.class); Query<TraceRecord> query = builder.newQuery(uow); // IS sorting needed?? // TraceRecord template = templateFor( TraceRecord.class ); // query.orderBy( orderBy( template.methodName() ) ); Iterator<TraceRecord> result = query.iterator(); assertTrue(result.hasNext()); TraceRecord rec1 = result.next(); assertEquals("doSomethingImportant", rec1.methodName().get()); assertFalse(result.hasNext()); uow.complete(); }
@Test(expected = IllegalStateException.class) public void givenEntityWithImmutableManyAssociationWhenChangingValueThenThrowException() throws Exception { UnitOfWork unitOfWork = unitOfWorkFactory.newUnitOfWork(); try { EntityBuilder<PersonEntity> builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity person1 = builder.instance(); person1 = builder.newInstance(); builder = unitOfWork.newEntityBuilder(PersonEntity.class); PersonEntity person2 = builder.instance(); person2 = builder.newInstance(); person1.colleagues().add(0, person2); unitOfWork.complete(); } catch (Exception e) { unitOfWork.discard(); throw e; } }
public Voyage build() { final ValueBuilder<Schedule> builder = factory.newValueBuilder(Schedule.class); builder.prototype().carrierMovements().set(carrierMovements); final Schedule schedule = builder.newInstance(); final EntityBuilder<Voyage> entityBuilder = uow.newEntityBuilder(Voyage.class, createVoyageIdentity(voyageNumberString)); Voyage voyage = entityBuilder.instance(); VoyageNumber voyageNumber = createVoyageNumber(voyageNumberString); voyage.voyageNumber().set(voyageNumber); voyage.schedule().set(schedule); return entityBuilder.newInstance(); }
private static void buildDemoNetwork(SingletonAssembler assembler) throws Exception { UnitOfWork uow = assembler.unitOfWorkFactory().newUnitOfWork(newUsecase("Build demo network of activities")); try { // try different combinations here... ActivityEntity a = uow.newEntity(ActivityEntity.class, "A"); ActivityEntity b = uow.newEntity(ActivityEntity.class, "B"); ActivityEntity c = uow.newEntity(ActivityEntity.class, "C"); ActivityEntity d = uow.newEntity(ActivityEntity.class, "D"); a.duration().set(2); b.duration().set(7); c.duration().set(3); d.duration().set(2); a.succeededBy(c, d); // Try different variations: b.succeededBy(d); // "Original" // b.succeededBy( c ); // Variation // c.succeededBy( a ); // "C" already planned // d.succeededBy( a ); // Cyclic dependency ProjectData project = uow.newEntity(ProjectData.class, PROJECT); // project.addActivities( a, b, c, d ); project.addActivities(d, c, b, a); // More interesting execution flow // Save uow.complete(); } catch (Exception e) { uow.discard(); throw e; } }
// WARN Watch this code, see if we can do better, maybe leverage @UnitOfWorkRetry @Override public void run() { System.out.println("Running Schedule"); Usecase usecase = UsecaseBuilder.newUsecase("ScheduleRunner"); UnitOfWork uow = module.newUnitOfWork(usecase); try { Schedule schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity); Task task = schedule.task().get(); schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity); try { schedule.taskStarting(); task.run(); schedule.taskCompletedSuccessfully(); } catch (RuntimeException ex) { schedule.taskCompletedWithException(ex); } schedulerMixin.dispatchForExecution(schedule); uow.complete(); } catch (UnitOfWorkCompletionException ex) { } finally { // What should we do if we can't manage the Running flag?? if (uow.isOpen()) { uow.discard(); } } }
@Override public void save() { if (uow != null) { try { uow.complete(); uow = null; } catch (UnitOfWorkCompletionException e) { // Should be impossible e.printStackTrace(); } configuration = null; // Force refresh } }
@Test(expected = IllegalArgumentException.class) public void transferTwiceOfMoneyFromSavingsToChecking() throws Exception { UnitOfWork uow = module.newUnitOfWork(UsecaseBuilder.newUsecase("Transfer from savings to checking")); try { // Select source and destination BalanceData source = uow.get(BalanceData.class, SAVINGS_ACCOUNT_ID); BalanceData destination = uow.get(BalanceData.class, CHECKING_ACCOUNT_ID); // Instantiate context and execute enactments with that context TransferMoneyContext2 context = module.newTransient(TransferMoneyContext2.class).bind(source, destination); // Query for double the balance final Integer amountToTransfer = context.availableFunds() * 2; // Transfer from savings to checking context.transfer(amountToTransfer); } finally { uow.discard(); } }
@Test public void createAndModifyEntity() throws Exception { UnitOfWork uow = this.module.newUnitOfWork(); TestEntity entity = uow.newEntity(TestEntity.class); uow.complete(); uow = this.module.newUnitOfWork(); entity = uow.get(entity); entity.testString().set("NewTestString"); uow.complete(); uow = this.module.newUnitOfWork(); entity = uow.get(entity); Assert.assertEquals( "New value did not store in indexing.", "NewTestString", entity.testString().get()); uow.discard(); }
public void activate() throws Exception { UnitOfWork unitOfWork = uowf.newUnitOfWork(); try { { ValueBuilder<TestValue> valueBuilder = vbf.newValueBuilder(TestValue.class); valueBuilder.prototype().longList().get().add(42L); valueBuilder.prototype().string().set("Foo bar value"); valueBuilder.prototype().map().set(new HashMap()); EntityBuilder<TestEntity> builder = unitOfWork.newEntityBuilder(TestEntity.class, "test1"); builder.instance().name().set("Foo bar"); builder.instance().age().set(42); builder.instance().value().set(valueBuilder.newInstance()); TestEntity testEntity = builder.newInstance(); EntityBuilder<TestEntity> builder2 = unitOfWork.newEntityBuilder(TestEntity.class, "test2"); builder2.instance().name().set("Xyzzy"); builder2.instance().age().set(12); builder2.instance().association().set(testEntity); builder2.instance().manyAssociation().add(0, testEntity); builder2.instance().manyAssociation().add(0, testEntity); EntityBuilder<TestRole> builder3 = unitOfWork.newEntityBuilder(TestRole.class); builder3.instance().name().set("A role"); TestRole testRole = builder3.newInstance(); builder2.newInstance(); } { EntityBuilder<TestEntity2> builder = unitOfWork.newEntityBuilder(TestEntity2.class, "test3"); builder.instance().name().set("Test3"); builder.newInstance(); } unitOfWork.complete(); } catch (Exception e) { unitOfWork.discard(); throw e; } }