io.vavr.collection.Seq Java Examples

The following examples show how to use io.vavr.collection.Seq. 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: AriEventProcessingTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void verifyTheRequiredMetricsAreGatheredForStasisEnd() {
	final Seq<MetricsGatherer> metricsGatherers = AriEventProcessing
			.determineMetricsGatherer(AriMessageType.STASIS_END);

	final Seq<Object> metricsRequests = metricsGatherers
			.map(metricsGatherer -> metricsGatherer.withCallContextSupplier(() -> "CALL_CONTEXT"));

	assertThat(len(metricsGatherers), is(2));

	final IncreaseCounter eventTypeCounter = (IncreaseCounter) metricsRequests.get(0);
	final IncreaseCounter callsEndedCounter = (IncreaseCounter) metricsRequests.get(1);

	assertThat(eventTypeCounter.getName(), is(AriMessageType.STASIS_END.name()));
	assertThat(callsEndedCounter.getName(), is("CallsEnded"));
}
 
Example #2
Source File: ValueProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
@Override
public Writer<CsvEvent, String> writer() {
    return new Writer<CsvEvent, String>() {
        @Override
        public Seq<CsvEvent> apply(String value) {
            if (value.isEmpty()) {
                return Vector.empty();
            } else {
                return Vector.of(CsvEvent.text(value));
            }
        }

        @Override
        public Seq<CsvEvent> reset() {
            return Vector.empty();
        }
    };
}
 
Example #3
Source File: AnyOfProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Returns a Protocol that uses an AlternativesProtocol for reading, and always picks the first alternative when writing.
 */
public static <E,T> Protocol<E,T> readWrite(Seq<Protocol<E,T>> alternatives) {
    Protocol<E,T> write = alternatives.head();
    AnyOfProtocol<E,T> read = new AnyOfProtocol<>(Seq.narrow(alternatives));
    return new Protocol<E,T>() {
        @Override
        public Writer<E,T> writer() {
            return write.writer();
        }

        @Override
        public Class<? extends E> getEventType() {
            return write.getEventType();
        }

        @Override
        public Reader<E,T> reader() {
            return read.reader();
        }
    };
}
 
Example #4
Source File: AbstractStatefulPersistentActorSpec.java    From ts-reaktive with MIT License 5 votes vote down vote up
@Override
public Results<MyEvent> handleSynchronously(MyState state, String cmd) {
    return new Results<MyEvent>() {
        @Override
        public Seq<MyEvent> getEventsToEmit() {
            return Vector.of(new MyEvent(cmd));
        }

        @Override
        public Object getReply(Seq<MyEvent> emittedEvents, long lastSequenceNr) {
            return Done.getInstance();
        }                    
    };
}
 
Example #5
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void testJaxbXmlSerialization() throws IOException {
    ObjectMapper mapper = xmlMapperJaxb();
    String javaUtilValue = mapper.writeValueAsString(new JaxbXmlSerializeVavr().init((Seq<Integer>) of(1, 2, 3)));
    Assertions.assertEquals(mapper.writeValueAsString(new JaxbXmlSerializeJavaUtil().init(Arrays.asList(1, 2, 3))), javaUtilValue);
    JaxbXmlSerializeVavr restored = mapper.readValue(javaUtilValue, JaxbXmlSerializeVavr.class);
    Assertions.assertEquals(restored.transitTypes.size(), 3);
}
 
Example #6
Source File: BaseTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
private void appendObj(StringBuilder sb, Object o) {
    if (o instanceof java.lang.String) {
        sb.append("\"").append(o).append("\"");
    } else if (o instanceof io.vavr.collection.Seq) {
        sb.append(genJsonList(((Seq) o).toJavaList().toArray()));
    } else {
        sb.append(o);
    }
}
 
Example #7
Source File: DataSort.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
/**
 * Validates that all the columns being sorted are comparable.
 *
 * @param columns The columns to sort.
 * @return Returns the result as a Try : Success / Failure.
 */
private static Try<Void> validateColumnsAreComparable(Seq<IDataColumn> columns) {
    Option<IDataColumn> invalidCol = columns.find(col -> !col.IsComparable());

    return invalidCol.isEmpty()
            ? Try.success(null)
            : DataTableException.tryError("Column '" + invalidCol.get().name() + "' doesn't support comparable.");
}
 
Example #8
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    ObjectWriter writer = mapper().writer();
    Seq<?> src = of(1, null, 2.0, "s");
    String json = writer.writeValueAsString(src);
    Assertions.assertEquals(genJsonList(1, null, 2.0, "s"), json);
    Seq<?> dst = (Seq<?>) mapper().readValue(json, clz());
    Assertions.assertEquals(src, dst);
}
 
Example #9
Source File: Writer.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a writer that emits an event for every element, the event being the element itself.
 */
public static <E, T extends E> Writer<E,T> identity() {
    return new Writer<E,T>() {
        @Override
        public Seq<E> apply(T value) {
            return Vector.of(value);
        }
        
        @Override
        public Seq<E> reset() {
            return Vector.empty();
        }
    };
}
 
Example #10
Source File: CassandraSession.java    From ts-reaktive with MIT License 5 votes vote down vote up
public static CompletionStage<Done> executeInitStatements(Session session, Seq<String> statements) {
    if (statements.isEmpty()) {
        return CompletableFuture.completedFuture(Done.getInstance());
    }

    return toJava(session.executeAsync(statements.head())).thenCompose(rs -> executeInitStatements(session, statements.tail()));
}
 
Example #11
Source File: Writer.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Invokes the given function before calling this writer.
 */
public default <U> Writer<E,U> compose(Function1<U,T> f) {
    Writer<E,T> parent = this;
    return new Writer<E,U>() {
        @Override
        public Seq<E> apply(U value) {
            return parent.apply(f.apply(value));
        }
        
        @Override
        public Seq<E> reset() {
            return parent.reset();
        }
    };
}
 
Example #12
Source File: Writer.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Applies the given transformation to the returned events of {@link #apply} and {@link #reset}
 */
public default Writer<E,T> map(Function<Seq<E>, Seq<E>> f) {
    Writer<E,T> parent = this;
    return new Writer<E,T>() {
        @Override
        public Seq<E> apply(T value) {
            return f.apply(parent.apply(value));
        }

        @Override
        public Seq<E> reset() {
            return f.apply(parent.reset());
        }
    };
}
 
Example #13
Source File: Writer.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Applies the given transformation to the returned events of {@link #apply} (but not to {@link #reset}), also passing in the original input
 */
public default Writer<E,T> mapWithInput(BiFunction<T, Seq<E>, Seq<E>> f) {
    Writer<E,T> parent = this;
    return new Writer<E,T>() {
        @Override
        public Seq<E> apply(T value) {
            return f.apply(value, parent.apply(value));
        }

        @Override
        public Seq<E> reset() {
            return parent.reset();
        }
    };
}
 
Example #14
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test2() throws IOException {
    ObjectMapper mapper = mapper().addMixIn(clz(), WrapperObject.class);
    Seq<?> src = of(1);
    String plainJson = mapper().writeValueAsString(src);
    String wrappedJson = mapper.writeValueAsString(src);
    Assertions.assertEquals(wrappedJson, wrapToObject(implClzName(), plainJson));
    Seq<?> restored = (Seq<?>) mapper.readValue(wrappedJson, clz());
    Assertions.assertEquals(src, restored);
}
 
Example #15
Source File: TagWriteProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
@Override
 public String toString() {
     StringBuilder msg = new StringBuilder("<");
     msg.append(name.map(Object::toString).getOrElse("*"));
     msg.append(">");
     Seq<WriteProtocol<XMLEvent,?>> protocols = attrProtocols.appendAll(otherProtocols);
     if (!protocols.isEmpty()) {
         msg.append(" with ");
         msg.append(protocols.map(p -> p.toString()).mkString(", "));
     }
     return msg.toString();
}
 
Example #16
Source File: TagWriteProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
private TagWriteProtocol(Option<QName> name, Function<T, QName> getName, Seq<WriteProtocol<XMLEvent,?>> attrProtocols,
    Seq<WriteProtocol<XMLEvent,?>> otherProtocols, Seq<Function1<T, ?>> attrGetters, Seq<Function1<T, ?>> otherGetters) {
    this.name = name;
    this.getName = getName;
    this.attrProtocols = attrProtocols;
    this.otherProtocols = otherProtocols;
    this.attrGetters = attrGetters;
    this.otherGetters = otherGetters;
}
 
Example #17
Source File: BulkheadChain.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private ServerSentEvents serverSentEvents(Chain chain, Seq<Flux<BulkheadEvent>> eventStreams) {
    Function<BulkheadEvent, String> data = b -> Jackson.getObjectWriter(chain.getRegistry())
        .writeValueAsString(BulkheadEventDTOFactory.createBulkheadEventDTO(b));
    return ServerSentEvents.serverSentEvents(Flux.merge(eventStreams),
        e -> e.id(BulkheadEvent::getBulkheadName).event(c -> c.getEventType().name())
            .data(data));
}
 
Example #18
Source File: AbstractCommandResultsAssert.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Object actualToString() {
    if (actual.getValidationError(0).isDefined()) {
        return "Result(invalid, reply=" + actual.getValidationError(0) + ")";
    } else if (actual.isAlreadyApplied()) {
        return "Result(idempotent, reply=" + actual.getIdempotentReply(0) + ")";
    } else {
        Seq<E> events = actual.getEventsToEmit();
        return "Result(nonIdempotent, reply=" + actual.getReply(events, 0) + ", events=" + events + ")";
    }
}
 
Example #19
Source File: JSONProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
public static <T> Protocol<JSONEvent, Seq<T>> optionalVectorField(String name, Protocol<JSONEvent,T> inner) {
    return option(
        field(name,
            array(
                vector(inner)
            )
        )
    ).map(o -> o.getOrElse(Vector.empty()), (Seq<T> i) -> Option.when(!i.isEmpty(), i));
}
 
Example #20
Source File: CQLStoreManager.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void clearStorage() throws BackendException {
    if (this.storageConfig.get(DROP_ON_CLEAR)) {
        this.session.execute(dropKeyspace(this.keyspace).build());
    } else if (this.exists()) {
        Future<Seq<AsyncResultSet>> result = Future.sequence(
                Iterator.ofAll(this.session.getMetadata().getKeyspace(this.keyspace).get().getTables().values())
                        .map(table -> Future.fromJavaFuture(this.session.executeAsync(truncate(this.keyspace, table.getName().toString()).build())
                                .toCompletableFuture())));
        result.await();
    } else {
        LOGGER.info("Keyspace {} does not exist in the cluster", this.keyspace);
    }
}
 
Example #21
Source File: MaterializerActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
private void applyEvent(MaterializerActorEvent evt) {
    workers = workers.applyEvent(evt);
    Seq<UUID> ids = workers.getIds();
    workerEndTimestamps.forEach((id, endTimestamp) -> {
        if (ids.contains(id)) {
            endTimestamp.set(workers.getEndTimestamp(id).map(t -> t.toEpochMilli()).getOrElse(-1L));
        } else {
            // No longer in the list -> we should stop it right now.
            log.info("Worker {} being stopped by event.", id);
            endTimestamp.set(0L);
        }
    });
    recordOffsetMetric();
}
 
Example #22
Source File: MaterializerActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
private void recordOffsetMetric() {
    Seq<UUID> ids = workers.getIds();
    metrics.getWorkers().set(workers.getIds().size());
    for (int i = 0; i < ids.size(); i++) {
        Instant offset = workers.getTimestamp(ids.apply(i));
        metrics.getOffset(i).set(offset.toEpochMilli());
        metrics.getDelay(i).set(Duration.between(offset, Instant.now()).toMillis());
        for (Instant end: workers.getEndTimestamp(workers.getIds().apply(i))) {
            metrics.getRemaining(i).set(Duration.between(offset, end).toMillis());
        }
    }
}
 
Example #23
Source File: MaterializerActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
private CompletionStage<Done> persistSequential(int workerIndex, Seq<E> seq) {
    if (seq.isEmpty()) {
        return done;
    } else {
        return materialize(seq.head())
            .thenCompose(done -> {
                metrics.getEvents(workerIndex).increment();
                return persistSequential(workerIndex, seq.tail());
            });
    }
}
 
Example #24
Source File: TestEventClassifier.java    From ts-reaktive with MIT License 5 votes vote down vote up
@Override
public Seq<String> getDataCenterNames(TestEvent e) {
    if (e.getMsg().startsWith("dc:")) {
        return Vector.of(e.getMsg().substring(3));
    } else {
        return Vector.empty();
    }
}
 
Example #25
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializable() throws IOException {
    ObjectMapper mapper = mapper();
    Seq<?> src = of(1);
    Seq<?> restored = (Seq<?>) mapper.readValue(mapper.writeValueAsString(src), clz());
    checkSerialization(restored);
}
 
Example #26
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void testXmlSerialization() throws IOException {
    ObjectMapper mapper = xmlMapper();
    String javaUtilValue = mapper.writeValueAsString(new XmlSerializeVavr().init((Seq<Integer>) of(1, 2, 3)));
    Assertions.assertEquals(mapper.writeValueAsString(new XmlSerializeJavaUtil().init(Arrays.asList(1, 2, 3))), javaUtilValue);
    XmlSerializeVavr restored = mapper.readValue(javaUtilValue, XmlSerializeVavr.class);
    Assertions.assertEquals(restored.transitTypes.size(), 3);
}
 
Example #27
Source File: AbstractStatefulPersistentActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Applies the results that came in from a handler, emitting any events, and responding to sender().
 */
protected void handleResults(CommandHandler.Results<E> results) {
    Option<Object> error = results.getValidationError(lastSequenceNr());
    if (error.isDefined()) {
        log.debug("  invalid: {}", error.get());
        sender().tell(error.get(), self());
    } else if (results.isAlreadyApplied()) {
        log.debug("  was already applied.");
        sender().tell(results.getIdempotentReply(lastSequenceNr()), self());
    } else {
        Seq<E> events = results.getEventsToEmit();
        log.debug("  emitting {}", events);
        if (events.isEmpty()) {
            sender().tell(results.getReply(events, lastSequenceNr()), self());
        } else {
            if (lastSequenceNr() == 0) {
                validateFirstEvent(events.head());
            }
            AtomicInteger need = new AtomicInteger(events.size());
            persistAllEvents(events, evt -> {
                if (need.decrementAndGet() == 0) {
                    sender().tell(results.getReply(events, lastSequenceNr()), self());
                }
            });
        }
    }
}
 
Example #28
Source File: GroupWhileSpec.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Seq<Seq<Integer>> run(Source<Integer,?> source) {
    try {
        List<Seq<Integer>> result = source.runWith(sink, materializer).toCompletableFuture().get(10, TimeUnit.SECONDS);
        return Vector.ofAll(result);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: TagWriteProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
@Override
public Writer<XMLEvent,T> writer() {
    return new Writer<XMLEvent, T>() {
        boolean started = false;
        private EndElement endElement;
        
        @Override
        public Seq<XMLEvent> apply(T value) {
            log.debug("{}: Writing {}", TagWriteProtocol.this, value);
            Seq<XMLEvent> prefix = (started) ? Vector.empty() : Vector.of(startElement(value));
            started = true;
            endElement = factory.createEndElement(getName.apply(value), null);
            
            return prefix.appendAll(
                Vector.range(0, otherProtocols.size()).map(i -> {
                    Writer<XMLEvent,Object> w = (Writer<XMLEvent,Object>) otherProtocols.get(i).writer();
                    return w.applyAndReset(otherGetters.get(i).apply(value));
                }).flatMap(Function.identity())
            );
        }

        @Override
        public Seq<XMLEvent> reset() {
            log.debug("{}: Resetting", TagWriteProtocol.this);
            if (started) {
                started = false;
                return Vector.of(endElement);
            } else {
                return Vector.empty();
            }
        }
    };
}
 
Example #30
Source File: DTO1.java    From ts-reaktive with MIT License 4 votes vote down vote up
public DTO1(long l, Option<Integer> i, Seq<String> s) {
    this.l = l;
    this.i = i;
    this.s = s;
}