io.vlingo.symbio.Source Java Examples

The following examples show how to use io.vlingo.symbio.Source. 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: InMemoryJournal.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <S, ST> void appendWith(final String streamName, final int streamVersion, final Source<S> source, final Metadata metadata, final ST snapshot,
        final AppendResultInterest interest, final Object object) {
  final Entry<T> entry = entryAdapterProvider.asEntry(source, streamVersion, metadata);
  insert(streamName, streamVersion, entry);
  final RS raw;
  final Optional<ST> snapshotResult;
  if (snapshot != null) {
    raw = stateAdapterProvider.asRaw(streamName, snapshot, streamVersion);
    snapshots.put(streamName, raw);
    snapshotResult = Optional.of(snapshot);
  } else {
    raw = null;
    snapshotResult = Optional.empty();
  }

  dispatch(streamName, streamVersion, Collections.singletonList(entry), raw);
  interest.appendResultedIn(Success.of(Result.Success), streamName, streamVersion, source, snapshotResult, object);
}
 
Example #2
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 6 votes vote down vote up
private <STT> void applySource(final Source<STT> source) {
  Class<?> type = getClass();

  BiConsumer<Sourced<?>, Source<?>> consumer = null;

  while (type != Sourced.class) {
    final Map<Class<Source<?>>, BiConsumer<Sourced<?>, Source<?>>> sourcedTypeMap =
            registeredConsumers.get(type);

    if (sourcedTypeMap != null) {
      consumer = sourcedTypeMap.get(source.getClass());
      if (consumer != null) {
        consumer.accept(this, source);
        break;
      }
    }

    type = type.getSuperclass();
  }

  if (consumer == null) {
    throw new IllegalStateException("No such Sourced type.");
  }
}
 
Example #3
Source File: StatefulEntity.java    From vlingo-lattice with Mozilla Public License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
final public <ST,C> void writeResultedIn(final Outcome<StorageException, Result> outcome, final String id, final ST state, final int stateVersion, final List<Source<C>> sources, final Object supplier) {
  outcome
    .andThen(result -> {
      state((S) state);
      currentVersion = stateVersion;
      afterApply();
      completeUsing(supplier);
      disperseStowedMessages();
      return result;
    })
    .otherwise(cause -> {
      disperseStowedMessages();
      final String message = "State not applied for: " + getClass() + "(" + id + ") because: " + cause.result + " with: " + cause.getMessage();
      logger().error(message, cause);
      throw new IllegalStateException(message, cause);
    });
}
 
Example #4
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T extends StateObject, E> void persist(StateSources<T, E> stateSources, Metadata metadata, long updateId, PersistResultInterest interest, Object object) {
  try {
    final T stateObject = stateSources.stateObject();
    final List<Source<E>> sources = stateSources.sources();

    final State<?> raw = storeDelegate.persist(stateObject, updateId, metadata);

    final int entryVersion = (int) stateSources.stateObject().version();
    final List<BaseEntry<?>> entries = entryAdapterProvider.asEntries(sources, entryVersion, metadata);
    final Dispatchable<BaseEntry<?>, State<?>> dispatchable = buildDispatchable(raw, entries);

    this.storeDelegate.persistEntries(entries);
    this.storeDelegate.persistDispatchable(dispatchable);

    dispatch(dispatchable);
    interest.persistResultedIn(Success.of(Result.Success), stateObject, 1, 1, object);
  } catch (StorageException e){
    logger().error("Failed to persist all objects", e);
    interest.persistResultedIn(Failure.of(e), null, 0, 0, object);
  }
}
 
Example #5
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Register the means to apply {@code sourceType} instances for state transition
 * of {@code sourcedType} by means of a given {@code consumer}.
 * @param sourcedType the concrete {@code Class<SOURCED>} type to which sourceType instances are applied
 * @param sourceType the concrete {@code Class<SOURCE>} type to apply
 * @param consumer the {@code BiConsumer<SOURCED, SOURCE>} used to perform the application of sourceType
 * @param <SOURCED> the type {@code <? extends Sourced<?>>} of the sourced entity to apply to
 * @param <SOURCE> the type {@code <? extends Source<?>>} of the source to be applied
 */
@SuppressWarnings("unchecked")
public static <SOURCED extends Sourced<?>, SOURCE extends Source<?>> void registerConsumer(
        final Class<SOURCED> sourcedType,
        final Class<SOURCE> sourceType,
        final BiConsumer<SOURCED, SOURCE> consumer) {

  Map<Class<Source<?>>, BiConsumer<Sourced<?>, Source<?>>> sourcedTypeMap =
          registeredConsumers.get(sourcedType);

  if (sourcedTypeMap == null) {
    sourcedTypeMap = new ConcurrentHashMap<>();
    registeredConsumers.put((Class<Sourced<Source<?>>>) sourcedType, sourcedTypeMap);
  }

  sourcedTypeMap.put((Class<Source<?>>) sourceType, (BiConsumer<Sourced<?>, Source<?>>) consumer);
}
 
Example #6
Source File: InMemoryEventJournalActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testThatJournalReaderReadsThreeEvents() {
  interest.afterCompleting(1);
  dispatcher.afterCompleting(1);

  final List<Source<String>> three = Arrays.asList(new Test1Source(), new Test2Source(), new Test1Source());
  journal.appendAll("123", 1, three, interest, object);

  final AccessSafely accessResults = new TestResults().afterCompleting(1);
  journal.journalReader("test").andThenTo(reader -> reader.readNext(5)).andThenConsume(entries -> {
    accessResults.writeUsing("addAll", entries);
  });

  assertEquals(3, (int) accessResults.readFrom("size"));
  assertEquals("1", accessResults.readFrom("entryId", 0));
  assertEquals("2", accessResults.readFrom("entryId", 1));
  assertEquals("3", accessResults.readFrom("entryId", 2));
}
 
Example #7
Source File: ProjectionDispatcher.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new ProjectToDescription with {@code projectionType} for matches on types in {@code becauseOf}.
 * @param projectionType the Class of the projectionType that must be an Actor extender
 * @param constructionParameter the {@code Optional<Object>} to pass as the projectionType constructor parameter, or empty
 * @param becauseOf the {@code Class<? extends Source<?>>} causes/reasons that the projectionType handles
 * @return ProjectToDescription
 */
@SuppressWarnings("unchecked")
public static ProjectToDescription with(final Class<? extends Actor> projectionType, final Optional<Object> constructionParameter, final Class<? extends Source<?>>... becauseOf) {
  final String[] representations = new String[becauseOf.length];
  int index = 0;

  for (final Class<?> sourceType : becauseOf) {
    representations[index++] = sourceType.getName();
  }

  return new ProjectToDescription(projectionType, constructionParameter, representations);
}
 
Example #8
Source File: InMemoryEventJournalActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatJournalAppendsOneEvent() {
  dispatcher.afterCompleting(1);
  interest.afterCompleting(1);

  final Test1Source source = new Test1Source();
  final String streamName = "123";
  final int streamVersion = 1;
  journal.append(streamName, streamVersion, source, interest, object);

  assertEquals(1, interest.getReceivedAppendsSize());

  final List<JournalData<String, SnapshotState>> entries = interest.getEntries();
  final JournalData<String, SnapshotState> journalData = entries.get(0);
  assertNotNull(journalData);
  Assert.assertEquals(streamName, journalData.streamName);
  Assert.assertEquals(streamVersion, journalData.streamVersion);
  Assert.assertEquals(Result.Success, journalData.result);
  Assert.assertFalse(journalData.snapshot.isPresent());

  final List<Source<String>> sourceList = journalData.sources;
  Assert.assertEquals(1, sourceList.size());
  Assert.assertEquals(source, sourceList.get(0));

  assertEquals(1, dispatcher.dispatchedCount());
  final Dispatchable<Entry<?>, ?> dispatched = dispatcher.getDispatched().get(0);

  Assert.assertNotNull(dispatched.createdOn());
  Assert.assertFalse(dispatched.state().isPresent());
  Assert.assertNotNull(dispatched.id());
  final Collection<Entry<?>> dispatchedEntries = dispatched.entries();
  Assert.assertEquals(1, dispatchedEntries.size());
}
 
Example #9
Source File: MockAppendResultInterest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <S, ST> void appendAllResultedIn(Outcome<StorageException, Result> outcome, String streamName,
        int streamVersion, List<Source<S>> sources, Metadata metadata, Optional<ST> snapshot, Object object) {
  outcome.andThen(result -> {
    access.writeUsing("appendResultedIn",
            new JournalData<>(streamName, streamVersion, null, result, sources, snapshot));
    return result;
  }).otherwise(cause -> {
    access.writeUsing("appendResultedIn",
            new JournalData<>(streamName, streamVersion, cause, null, sources, snapshot));
    return cause.result;
  });
}
 
Example #10
Source File: UserEntity.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected <C> Tuple3<User.UserState,List<Source<C>>,String> whenNewState() {
  if (state.isIdentifiedOnly()) {
    return null;
  }
  return Tuple3.from(state, Collections.emptyList(), "User:new");
}
 
Example #11
Source File: InMemoryJournal.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <S, ST> void appendAll(final String streamName, final int fromStreamVersion, final List<Source<S>> sources, final Metadata metadata,
        final AppendResultInterest interest, final Object object) {
  final List<Entry<T>> entries = entryAdapterProvider.asEntries(sources, fromStreamVersion, metadata);
  insert(streamName, fromStreamVersion, entries);

  dispatch(streamName, fromStreamVersion, entries, null);
  interest.appendAllResultedIn(Success.of(Result.Success), streamName, fromStreamVersion, sources, Optional.empty(), object);
}
 
Example #12
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Received prior to the evaluation of each {@code apply()} and by
 * default adds all applied {@code Source<T>} {@code sources} to the
 * {@code TestContext reference}, if currently testing. The concrete
 * extender may override to implement different or additional behavior.
 * @param sources the {@code List<Source<T>>} ready to be applied
 */
protected void beforeApply(final List<Source<T>> sources) {
  // override to be informed prior to apply evaluation
  if (testContext != null) {
    final List<Source<T>> all = testContext.referenceValue();
    all.addAll(sources);
    testContext.referenceValueTo(all);
  }
}
 
Example #13
Source File: MockAppendResultInterest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <S, ST> void appendAllResultedIn(Outcome<StorageException, Result> outcome, String streamName,
        int streamVersion, List<Source<S>> sources, Optional<ST> snapshot, Object object) {
  outcome.andThen(result -> {
    access.writeUsing("appendResultedIn",
            new JournalData<>(streamName, streamVersion, null, result, sources, snapshot));
    return result;
  }).otherwise(cause -> {
    access.writeUsing("appendResultedIn",
            new JournalData<>(streamName, streamVersion, cause, null, sources, snapshot));
    return cause.result;
  });
}
 
Example #14
Source File: ProcessMessage.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code List<Source<ProcessMessage>>} that wraps each of the elements of {@code sources}.
 * @param sources the {@code List<Source<C>>} elements each to be wrapped with a ProcessMessage
 * @param <C> the type of Source
 * @return {@code List<Source<ProcessMessage>>}
 */
public static <C> List<Source<ProcessMessage>> wrap(final List<Source<C>> sources) {
  final boolean reuse = (!sources.isEmpty() && sources.get(0).getClass() == ProcessMessage.class);

  final List<Source<ProcessMessage>> messages = new ArrayList<>(sources.size());
  for (final Source<?> source : sources) {
    if (reuse) {
      messages.add((ProcessMessage) source);
    } else {
      final ProcessMessage message = new ProcessMessage(source);
      messages.add(message);
    }
  }
  return messages;
}
 
Example #15
Source File: ObjectProcess.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @see io.vlingo.lattice.model.object.ObjectEntity#afterApply()
 */
@Override
protected void afterApply() {
  for (final Source<?> source : applied) {
    info.exchange.send(source);
  }
  applied.clear();
}
 
Example #16
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * FOR INTERNAL USE ONLY.
 */
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public final <STT, ST> void appendAllResultedIn(final Outcome<StorageException, Result> outcome, final String streamName,
        final int streamVersion,final List<Source<STT>> sources, final Metadata metadata,
        final Optional<ST> snapshot, final Object supplier) {
  //TODO handle metadata
  outcome
    .andThen(result -> {
      restoreSnapshot(snapshot, currentVersion);
      for (final Source<STT> source : sources) {
        applyResultVersioned(source);
      }
      afterApply();
      completeUsing(supplier);
      disperseStowedMessages();
      return result;
    })
    .otherwise(cause -> {
      final Applicable<?> applicable = new Applicable(null, sources, metadata, (CompletionSupplier<?>) supplier);
      final String message = "Source (count " + sources.size() + ") not appended for: " + type() + "(" + this.streamName + ") because: " + cause.result + " with: " + cause.getMessage();
      final ApplyFailedException exception = new ApplyFailedException(applicable, message, cause);
      final Optional<ApplyFailedException> maybeException = afterApplyFailed(exception);
      disperseStowedMessages();
      if (maybeException.isPresent()) {
        logger().error(message, maybeException.get());
        throw maybeException.get();
      }
      logger().error(message, exception);
      return cause.result;
    });
}
 
Example #17
Source File: MockStateStoreResultInterest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
public StoreData(final int resultedIn, final Result objectResult, final Object state, final List<Source<C>> sources, final Metadata metadata, final Exception errorCauses) {
  this.resultedIn = resultedIn;
  this.result = objectResult;
  this.state = state;
  this.sources = sources;
  this.metadata = metadata;
  this.errorCauses = errorCauses;
}
 
Example #18
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * FOR INTERNAL USE ONLY.
 */
@Override
public final <S, ST> void appendResultedIn(
        final Outcome<StorageException, io.vlingo.symbio.store.Result> outcome, final String streamName, final int streamVersion,
        final Source<S> source, final Optional<ST> snapshot, final Object supplier) {
    this.appendResultedIn(outcome, streamName, streamVersion, source, Metadata.nullMetadata(), snapshot, supplier);
}
 
Example #19
Source File: StateStore__Proxy.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <S,C> void write(java.lang.String arg0, S arg1, int arg2, final List<Source<C>> arg3, io.vlingo.symbio.Metadata arg4, io.vlingo.symbio.store.state.StateStore.WriteResultInterest arg5, java.lang.Object arg6) {
  if (!actor.isStopped()) {
    final SerializableConsumer<StateStore> consumer = (actor) -> actor.write(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
    if (mailbox.isPreallocated()) { mailbox.send(actor, StateStore.class, consumer, null, writeRepresentation1); }
    else { mailbox.send(new LocalMessage<StateStore>(actor, StateStore.class, consumer, writeRepresentation1)); }
  } else {
    actor.deadLetters().failedDelivery(new DeadLetter(actor, writeRepresentation1));
  }
}
 
Example #20
Source File: ProcessMessageTextAdapter.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public ProcessMessage fromEntry(final TextEntry entry) {
  try {
    final SerializableProcessMessage serializedMessage = JsonSerialization.deserialized(entry.entryData(), SerializableProcessMessage.class);
    final Class<?> sourceType = Class.forName(serializedMessage.type);
    final Source<?> source = (Source<?>) JsonSerialization.deserialized(serializedMessage.source, sourceType);
  return new ProcessMessage(source);
  } catch (Exception e) {
    throw new IllegalArgumentException("ProcessMessageTextAdapter failed because: " + e.getMessage(), e);
  }
}
 
Example #21
Source File: InMemoryStateStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
private <C> List<Entry<?>> appendEntries(final List<Source<C>> sources, final int stateVersion, final Metadata metadata) {
  final List<Entry<?>> adapted = entryAdapterProvider.asEntries(sources, stateVersion, metadata);
  for (final Entry<?> each : adapted) {
    ((BaseEntry<?>) each).__internal__setId(String.valueOf(entries.size()));
    entries.add(each);
  }
  return adapted;
}
 
Example #22
Source File: StatefulProcess.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @see io.vlingo.lattice.model.object.ObjectEntity#afterApply()
 */
@Override
protected void afterApply() {
  for (final Source<?> source : applied) {
    info.exchange.send(source);
  }
  applied.clear();
}
 
Example #23
Source File: JournalProjectionDispatcherTest.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <S, ST> void appendResultedIn(Outcome<StorageException, Result> outcome, String streamName,
        int streamVersion, Source<S> source, Metadata metadata, Optional<ST> snapshot, Object object) {
  logger().debug("APPENDED");
  ((AccessHolder) object).accessJournal.writeUsing(AccessJournal, 1);
}
 
Example #24
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * FOR INTERNAL USE ONLY.
 */
@Override
public final <S, ST> void appendAllResultedIn(final Outcome<StorageException, io.vlingo.symbio.store.Result> outcome, final String streamName,
        final int streamVersion, final List<Source<S>> sources, final Optional<ST> snapshot, final Object supplier) {
  this.appendAllResultedIn(outcome, streamName, streamVersion, sources, Metadata.nullMetadata(), snapshot, supplier);
}
 
Example #25
Source File: InMemoryJournalActor.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <S,ST> void appendAllWith(final String streamName, final int fromStreamVersion, final List<Source<S>> sources, final ST snapshot, final AppendResultInterest interest, final Object object) {
  journal.appendAllWith(streamName, fromStreamVersion, sources, snapshot, interest, object);
}
 
Example #26
Source File: StatefulProcess.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @see io.vlingo.lattice.model.process.Process#processAll(java.util.List, java.util.function.Supplier)
 */
@Override
public <C,R> Completes<R> processAll(final List<Source<C>> sources, final Supplier<R> andThen) {
  applied.addAll(sources);
  return apply(chronicle().state, ProcessMessage.wrap(sources), andThen);
}
 
Example #27
Source File: ProcessMessage.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Construct my default state with a {@code source} and a type version of 1.
 * @param source the {@code Source<?>} to set as my source
 */
public ProcessMessage(final Source<?> source) {
  super();

  this.source = source;
}
 
Example #28
Source File: MockCounterAppendResultInterest.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <S,ST> void appendAllResultedIn(Outcome<StorageException, Result> outcome, String streamName, int streamVersion,
        List<Source<S>> sources, Optional<ST> snapshot, Object object) {
  
}
 
Example #29
Source File: StateSources.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
public List<Source<E>> sources() {
  return Collections.unmodifiableList(sources);
}
 
Example #30
Source File: MockCounterAppendResultInterest.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <S,ST> void appendResultedIn(Outcome<StorageException, Result> outcome, String streamName, int streamVersion,
        Source<S> source, Optional<ST> snapshot, Object object) {
  
}