io.vavr.collection.Vector Java Examples

The following examples show how to use io.vavr.collection.Vector. 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: AbstractStatefulPersistentActorSpec.java    From ts-reaktive with MIT License 6 votes vote down vote up
@Override
public CompletionStage<Results<MyEvent>> handle(MyState state, String cmd) {
    return CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }                    
        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 #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: S3Backup.java    From ts-reaktive with MIT License 6 votes vote down vote up
private Receive startBackup(long offset) {
    query
        .eventsByTag(tag, NoOffset.getInstance())
        // create backups of max [N] elements, or at least every [T] on activity
        // FIXME write a stage that, instead of buffering each chunk into memory, creates sub-streams instead.
        .groupedWithin(eventChunkSize, eventChunkDuration)
        .filter(list -> list.size() > 0)
        .mapAsync(4, list -> s3.store(tag, Vector.ofAll(list)).thenApply(done -> list.get(list.size() - 1).offset()))
        .runWith(Sink.actorRefWithAck(self(), "init", "ack", "done", Failure::new), materializer);
    
    return ReceiveBuilder.create()
        .matchEquals("init", msg -> sender().tell("ack", self()))
        .match(Long.class, l -> pipe(s3.saveOffset(l).thenApply(done -> "ack"), context().dispatcher()).to(sender()))
        .match(Failure.class, msg -> {
            log.error("Stream failed, rethrowing", msg.cause());
            throw new RuntimeException(msg.cause());
        })
        .matchEquals("done", msg -> { throw new IllegalStateException("eventsByTag completed, this should not happen. Killing actor, hoping for restart"); })
        .build();
}
 
Example #4
Source File: VectorTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void vectorplay(){
    Vector.of(1,2,3)
        .map(i->{
            System.out.println("a "+ i);
            return i;
        })
        .map(i->i+2)

        .map(i->{
            System.out.println("b " + i);
            return i;
        })
        .filter(i->i<4)
        .map(i->{
            System.out.println("c "+ i);
            return i;
        });

}
 
Example #5
Source File: TagWriteProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * @param name The qualified name of the tag to write, or none() to have the last item of [getters] deliver a {@link QName}.
 * @param getters Getter function for each sub-protocol to write (and additional first element delivering a QName, if name == none())
 * @param protocols Protocols to use to write each of the getter elements
 */
public TagWriteProtocol(Option<QName> name, Vector<? extends WriteProtocol<XMLEvent,?>> protocols, Vector<Function1<T, ?>> g) {
    if (name.isDefined() && (protocols.size() != g.size()) ||
        name.isEmpty() && (protocols.size() != g.size() - 1)) {
        throw new IllegalArgumentException ("Number of protocols and getters does not match");
    }
    this.name = name;
    this.getName = t -> name.getOrElse(() -> (QName) g.head().apply(t));
    
    Vector<Function1<T, ?>> getters = (name.isEmpty()) ? g.drop(1) : g;
    
    Tuple2<Vector<Tuple2<WriteProtocol<XMLEvent,?>, Function1<T, ?>>>, Vector<Tuple2<WriteProtocol<XMLEvent,?>, Function1<T, ?>>>> partition =
        ((Vector<WriteProtocol<XMLEvent,?>>)protocols).zip(getters)
        .partition(t -> Attribute.class.isAssignableFrom(t._1.getEventType()));
    
    this.attrProtocols = partition._1().map(t -> t._1());
    this.attrGetters = partition._1().map(t -> t._2());
    this.otherProtocols = partition._2().map(t -> t._1());
    this.otherGetters = partition._2().map(t -> t._2());
}
 
Example #6
Source File: AnyFieldProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
public static <T> WriteProtocol<JSONEvent, Tuple2<String,T>> write(WriteProtocol<JSONEvent, T> innerProtocol) {
    return new WriteProtocol<JSONEvent, Tuple2<String,T>>() {
        @Override
        public Class<? extends JSONEvent> getEventType() {
            return JSONEvent.class;
        }
        
        @Override
        public Writer<JSONEvent, Tuple2<String,T>> writer() {
            return innerProtocol.writer()
                .compose((Tuple2<String, T> t) -> t._2)
                .mapWithInput((t, events) -> Vector.<JSONEvent>of(new JSONEvent.FieldName(t._1)).appendAll(events));
        }
        
        @Override
        public String toString() {
            return "(any): " + innerProtocol;
        }
    };
}
 
Example #7
Source File: MaterializerWorkers.java    From ts-reaktive with MIT License 6 votes vote down vote up
/** Returns a new MaterializerWorkers where the single expected worker has progressed to the given timestamp */
public MaterializerWorkers applyEvent(long event) {
    if (workers.size() == 0) {
        return new MaterializerWorkers(Vector.of(Worker.newBuilder()
            .setId(toProtobuf(UUID.randomUUID()))
            .setTimestamp(event)
            .build()), rollback);
    } else if (workers.size() == 1) {
        return new MaterializerWorkers(Vector.of(workers.head().toBuilder()
            .setTimestamp(event)
            .build()), rollback);
    } else {
        throw new IllegalStateException("Encountered legacy Long event " + event
            + " AFTER having more than 1 worker: " + workers);
    }
}
 
Example #8
Source File: MaterializerWorkers.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Reimport all timestamps, by removing any gaps between workers, and changing the first worker
 * to re-start at zero.
 */
public MaterializerActorEvent reset() {
    Worker zero = Worker.newBuilder()
        .setId(toProtobuf(UUID.randomUUID()))
        .setTimestamp(0L)
        .build();

    if (workers.size() <= 1) {
        return toEvent(Vector.of(zero));
    } else {
        return toEvent(workers.update(0, zero).sliding(2)
            .map(pair -> pair.apply(0).toBuilder()
                .setEndTimestamp(pair.apply(1).getTimestamp())
                .build())
            .toVector()
            .append(workers.last())
        );
    }
}
 
Example #9
Source File: MaterializerActor.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Materialize the given envelopes in parallel, as far as their entityIds allow it.
 */
private CompletionStage<Done> materialize(int workerIndex, java.util.List<E> envelopes) {
    long start = System.nanoTime();
    return CompletableFutures.sequence(
        Vector.ofAll(envelopes)
        .groupBy(this::getConcurrencyKey)
        .values()
        .map(es -> persistSequential(workerIndex, es))
        .map(c -> c.toCompletableFuture())
    ).thenApply(seqOfDone -> {
        long dur = (System.nanoTime() - start) / 1000;
        log.debug("Worker {} materialized {} events in {}ms", workerIndex, envelopes.size(),
            dur / 1000.0);
        if (envelopes.size() > 0) {
            metrics.getMaterializationDuration(workerIndex)
                .record((long) (dur / 1000.0 / envelopes.size()));
        }
        return Done.getInstance();
    });
}
 
Example #10
Source File: Writer.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a Writer that calls the given function for apply(), and nothing for reset().
 */
public static <E,T> Writer<E,T> of (Function<T,Seq<E>> f) {
    return new Writer<E, T>() {
        @Override
        public Seq<E> apply(T value) {
            return f.apply(value);
        }

        @Override
        public Seq<E> reset() {
            return Vector.empty();
        }
    };
}
 
Example #11
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 #12
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenVector_whenQueried_thenCorrect() {
    Vector<Integer> intVector = Vector.range(1, 5);
    Vector<Integer> newVector = intVector.replace(2, 6);

    assertEquals(4, intVector.size());
    assertEquals(4, newVector.size());

    assertEquals(2, intVector.get(1).intValue());
    assertEquals(6, newVector.get(1).intValue());
}
 
Example #13
Source File: DataColumnCollection.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
private Try<DataTable> checkColumnsAndBuild(String changeType, Supplier<Try<Vector<IDataColumn>>> columns) {
    // Calculate the new column collection then try and build a DataTable from it.
    Try<DataTable> result = columns.get()
            .flatMap(cols -> DataTable.build(this.table.name(), cols));

    return result.isSuccess()
            ? result
            : error("Error " + changeType + " column at specified index.", result.getCause());
}
 
Example #14
Source File: ExtFieldsPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testVector() throws Exception {
    Vector<A> src = Vector.of(new B("a", "b"));
    String json = MAPPER.writeValueAsString(new VectorPojo().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[{\"ExtFieldsPojoTest$B\":{\"a\":\"a\",\"b\":\"b\"}}]}");
    VectorPojo pojo = MAPPER.readValue(json, VectorPojo.class);
    Vector<A> restored = pojo.getValue();
    Assertions.assertTrue(restored.get(0) instanceof B);
    Assertions.assertEquals(restored.get(0).a, "a");
    Assertions.assertEquals(((B) restored.get(0)).b, "b");
}
 
Example #15
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 #16
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testVectorOfTuple() throws Exception {
    String src00 = "A";
    String src01 = "B";
    Tuple2<String, String> src0 = Tuple.of(src00, src01);
    Vector<Tuple2<String, String>> src = Vector.of(src0);
    String json = MAPPER.writeValueAsString(new VectorOfTuple().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[[\"A\",\"B\"]]}");
    VectorOfTuple restored = MAPPER.readValue(json, VectorOfTuple.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #17
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testVectorOfString() throws Exception {
    String src0 = "A";
    String src1 = "B";
    String src2 = "C";
    Vector<String> src = Vector.of(src0, src1, src2);
    String json = MAPPER.writeValueAsString(new VectorOfString().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[\"A\",\"B\",\"C\"]}");
    VectorOfString restored = MAPPER.readValue(json, VectorOfString.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #18
Source File: MaterializerWorkers.java    From ts-reaktive with MIT License 5 votes vote down vote up
/** Returns a new MaterializerWorkers with at least one worker in it */
public MaterializerWorkers initialize() {
    if (isEmpty()) {
        return new MaterializerWorkers(Vector.of(Worker.newBuilder()
            .setId(toProtobuf(UUID.randomUUID()))
            .setTimestamp(0L)
            .build()), rollback);
    } else {
        // already initialized;
        return this;
    }
}
 
Example #19
Source File: IterableProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
public static <E,T, I extends Iterable<T>> IterableWriteProtocol<E,I> write(WriteProtocol<E,T> inner) {
    return new IterableWriteProtocol<>(new WriteProtocol<E,I>() {
        @Override
        public Writer<E,I> writer() {
            return Writer.of(iterable -> {
                Vector<T> items = Vector.ofAll(iterable);
                if (items.isEmpty()) {
                    return Vector.empty();
                } else {
                    Writer<E,T> parentWriter = inner.writer();
                    return items.map(parentWriter::applyAndReset)
                        .flatMap(Function.identity());
                }
            });
        }
        
        @Override
        public Class<? extends E> getEventType() {
            return inner.getEventType();
        }
        
        @Override
        public String toString() {
            return "*(" + inner + ")";
        }
    });
}
 
Example #20
Source File: CsvProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a read-only protocol for a CSV format consisting of several nested protocols (probably created
 * using {@link #column(String)} ), invoking the [produce] function on reading.
 */
public static <T,F1,F2> ReadProtocol<CsvEvent, T> csv(
    ReadProtocol<CsvEvent,F1> p1,
    ReadProtocol<CsvEvent,F2> p2,
    Function2<F1,F2,T> produce) {
    return multi(Vector.of(p1, p2), args -> produce.apply((F1) args.get(0), (F2) args.get(1)));
}
 
Example #21
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 #22
Source File: CsvProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a read/write protocol for a CSV format consisting of several nested protocols (probably created
 * using {@link #column(String)} ), invoking the [produce] function on reading, and using the
 * specified getters for writing.
 */
public static <T,F1,F2,F3> Protocol<CsvEvent, T> csv(
    Protocol<CsvEvent,F1> p1, Protocol<CsvEvent,F2> p2, Protocol<CsvEvent,F3> p3,
    Function3<F1,F2,F3,T> produce,
    Function1<T,F1> g1, Function1<T,F2> g2, Function1<T,F3> g3) {
    return multi(Vector.of(p1, p2, p3), args -> produce.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2)), Vector.of(g1, g2, g3));
}
 
Example #23
Source File: CsvProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a read-only protocol for a CSV format consisting of several nested protocols (probably created
 * using {@link #column(String)} ), invoking the [produce] function on reading.
 */
public static <T,F1,F2,F3> ReadProtocol<CsvEvent, T> csv(
    ReadProtocol<CsvEvent,F1> p1,
    ReadProtocol<CsvEvent,F2> p2,
    ReadProtocol<CsvEvent,F3> p3,
    Function3<F1,F2,F3,T> produce) {
    return multi(Vector.of(p1, p2, p3), args -> produce.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2)));
}
 
Example #24
Source File: CsvProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a read/write protocol for a CSV format consisting of several nested protocols (probably created
 * using {@link #column(String)} ), using the
 * specified getters for writing.
 */
public static <T,F1,F2,F3> WriteProtocol<CsvEvent, T> csv(
    Function1<T,F1> g1, Protocol<CsvEvent,F1> p1,
    Function1<T,F2> g2, Protocol<CsvEvent,F2> p2,
    Function1<T,F3> g3, Protocol<CsvEvent,F3> p3) {
    return multi(Vector.of(p1, p2, p3), Vector.of(g1, g2, g3));
}
 
Example #25
Source File: PolymorphicPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testVector() throws Exception {
    Vector<I> src = Vector.of(new A(), new B());
    String json = MAPPER.writeValueAsString(new VectorPojo().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[{\"type\":\"a\"},{\"type\":\"b\"}]}");
    VectorPojo pojo = MAPPER.readValue(json, VectorPojo.class);
    Vector<I> restored = pojo.getValue();
    Assertions.assertTrue(restored.get(0) instanceof A);
    Assertions.assertTrue(restored.get(1) instanceof B);
}
 
Example #26
Source File: JSONProtocol.java    From ts-reaktive with MIT License 5 votes vote down vote up
public static <T> ReadProtocol<JSONEvent, Vector<T>> optionalVectorField(String name, ReadProtocol<JSONEvent,T> inner) {
    return option(
        field(name,
            array(
                vector(inner)
            )
        )
    ).map(o -> o.getOrElse(Vector.empty()));
}
 
Example #27
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testVectorOfString() throws Exception {
    String src0 = "A";
    String src1 = "B";
    String src2 = "C";
    Vector<String> src = Vector.of(src0, src1, src2);
    String json = MAPPER.writeValueAsString(new ParameterizedVectorPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":[\"A\",\"B\",\"C\"]}");
    ParameterizedVectorPojo<java.lang.String> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedVectorPojo<java.lang.String>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #28
Source File: VisibilityCassandraSession.java    From ts-reaktive with MIT License 5 votes vote down vote up
private static Vector<String> initialStatements(Config config) {
    String replStrategy = CassandraPluginConfig.getReplicationStrategy(
        config.getString("replication-strategy"),
        config.getInt("replication-factor"),
        asScalaBufferConverter(config.getStringList("data-center-replication-factors")).asScala());
    String keyspace = config.getString("keyspace");

    return Vector.of(
        "CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH REPLICATION = { 'class' : " + replStrategy + " } ",
        "CREATE TABLE IF NOT EXISTS " + keyspace + ".meta (datacenter text, tag text, lastEventOffset bigint, PRIMARY KEY(datacenter, tag))",
        "CREATE TABLE IF NOT EXISTS " + keyspace + ".visibility (persistenceid text PRIMARY KEY, master boolean, datacenters set<text>)"
    );
}
 
Example #29
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 #30
Source File: XMLProtocol.java    From ts-reaktive with MIT License 4 votes vote down vote up
/**
 * Reads and writes a tag and one child element (tag or attribute) using [p1], using [f] to create the result on reading, getting values using [g1] for writing.
 */
public static <F1,T> TagProtocol<T> tag(QName qname, Protocol<XMLEvent,F1> p1, Function1<F1,T> f, Function1<T,F1> g1) {
    return new TagProtocol<>(Option.of(qname), Vector.of(p1), args -> f.apply((F1) args.get(0)), Vector.of(g1));
}