io.vavr.collection.Map Java Examples

The following examples show how to use io.vavr.collection.Map. 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: MaterializerActor.java    From ts-reaktive with MIT License 7 votes vote down vote up
/**
 * @param additionalMetricTags the custom tags which will be attached to materializer metrics reported by Kamon.
 *                             By default, only the class name is attached as a tag in Kamon metrics and there are
 *                             no custom tags.
 */
protected MaterializerActor(Map<String, String> additionalMetricTags) {
    this.materializer = SharedActorMaterializer.get(context().system());
    Config config = context().system().settings().config().getConfig(configPath);
    rollback = FiniteDuration.create(config.getDuration("rollback", SECONDS), SECONDS);
    updateAccuracy = FiniteDuration.create(config.getDuration("update-accuracy", SECONDS), SECONDS);
    restartDelay = FiniteDuration.create(config.getDuration("restart-delay", SECONDS), SECONDS);
    batchSize = config.getInt("batch-size");
    updateSize = config.getInt("update-size");
    maxEventsPerTimestamp = config.getInt("max-events-per-timestamp");
    maxWorkerCount = config.getInt("max-worker-count");
    updateOffsetInterval = config.getDuration("update-offset-interval");
    deleteMessagesAfter = config.getInt("delete-messages-after");
    this.workers = MaterializerWorkers.empty(Duration.ofMillis(rollback.toMillis()));
    metrics = new MaterializerMetrics(getClass().getSimpleName().replaceAll("([a-z])([A-Z]+)", "$1-$2").toLowerCase(),
        additionalMetricTags);
    log.info("{} has started.", self().path());

    getContext().setReceiveTimeout(updateOffsetInterval);
}
 
Example #2
Source File: ParameterizedPojo.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
static void generate(java.util.Map<String, Object> cases) throws IOException {

        TypeSpec.Builder pojoTest = TypeSpec.classBuilder("ParameterizedPojoTest")
                .addJavadoc("generated\n")
                .addModifiers(Modifier.PUBLIC);
        initMapper(pojoTest, "MAPPER");

        cases.forEach((k, v) -> addCase(pojoTest, k, v));

        JavaFile javaFile = JavaFile.builder("io.vavr.jackson.generated", pojoTest.build())
                .indent("    ")
                .skipJavaLangImports(true)
                .build();

        javaFile.writeTo(new File("src/test/java"));
    }
 
Example #3
Source File: FixedThreadPoolBulkhead.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a bulkhead using a configuration supplied
 *
 * @param name           the name of this bulkhead
 * @param bulkheadConfig custom bulkhead configuration
 * @param tags           tags to add to the Bulkhead
 */
public FixedThreadPoolBulkhead(String name, @Nullable ThreadPoolBulkheadConfig bulkheadConfig,
    Map<String, String> tags) {
    this.name = name;
    this.config = requireNonNull(bulkheadConfig, CONFIG_MUST_NOT_BE_NULL);
    this.tags = requireNonNull(tags, TAGS_MUST_NOTE_BE_NULL);
    // init thread pool executor
    this.executorService = new ThreadPoolExecutor(config.getCoreThreadPoolSize(),
        config.getMaxThreadPoolSize(),
        config.getKeepAliveDuration().toMillis(), TimeUnit.MILLISECONDS,
        new ArrayBlockingQueue<>(config.getQueueCapacity()),
        new NamingThreadFactory(name));
    // adding prover jvm executor shutdown
    this.metrics = new FixedThreadPoolBulkhead.BulkheadMetrics();
    this.eventProcessor = new FixedThreadPoolBulkhead.BulkheadEventProcessor();
}
 
Example #4
Source File: SemaphoreBasedRateLimiter.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a RateLimiter.
 *
 * @param name              the name of the RateLimiter
 * @param rateLimiterConfig The RateLimiter configuration.
 * @param scheduler         executor that will refresh permissions
 * @param tags              tags to assign to the RateLimiter
 */
public SemaphoreBasedRateLimiter(String name, RateLimiterConfig rateLimiterConfig,
    @Nullable ScheduledExecutorService scheduler, Map<String, String> tags) {
    this.name = requireNonNull(name, NAME_MUST_NOT_BE_NULL);
    this.rateLimiterConfig = new AtomicReference<>(
        requireNonNull(rateLimiterConfig, CONFIG_MUST_NOT_BE_NULL));

    this.scheduler = Option.of(scheduler).getOrElse(this::configureScheduler);
    this.tags = tags;
    this.semaphore = new Semaphore(this.rateLimiterConfig.get().getLimitForPeriod(), true);
    this.metrics = this.new SemaphoreBasedRateLimiterMetrics();

    this.eventProcessor = new RateLimiterEventProcessor();

    scheduleLimitRefresh();
}
 
Example #5
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMap_whenMapApi_thenCorrect() {
    Map<Integer, List<Integer>> map = List.rangeClosed(0, 10)
      .groupBy(i -> i % 2);
    
    assertEquals(2, map.size());
    assertEquals(6, map.get(0).get().size());
    assertEquals(5, map.get(1).get().size());

    Map<String, String> map1
      = HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");

    Map<String, String> fMap
      = map1.filterKeys(k -> k.contains("1") || k.contains("2"));
    assertFalse(fMap.containsKey("key3"));

    Map<String, String> fMap2
      = map1.filterValues(v -> v.contains("3"));
    assertEquals(fMap2.size(), 1);
    assertTrue(fMap2.containsValue("val3"));

    Map<String, Integer> map2 = map1.map(
      (k, v) -> Tuple.of(k, Integer.valueOf(v.charAt(v.length() - 1) + "") ));
    assertEquals(map2.get("key1").get().intValue(), 1);
}
 
Example #6
Source File: SemaphoreBulkhead.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a bulkhead using a configuration supplied
 *
 * @param name           the name of this bulkhead
 * @param bulkheadConfig custom bulkhead configuration
 * @param tags           the tags to add to the Bulkhead
 */
public SemaphoreBulkhead(String name, @Nullable BulkheadConfig bulkheadConfig,
    Map<String, String> tags) {
    this.name = name;
    this.config = requireNonNull(bulkheadConfig, CONFIG_MUST_NOT_BE_NULL);
    this.tags = requireNonNull(tags, TAGS_MUST_NOTE_BE_NULL);
    // init semaphore
    this.semaphore = new Semaphore(config.getMaxConcurrentCalls(), config.isFairCallHandlingEnabled());

    this.metrics = new BulkheadMetrics();
    this.eventProcessor = new BulkheadEventProcessor();
}
 
Example #7
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
void testJaxbXmlSerialization() throws IOException {
    java.util.Map<String, String> javaInit = new java.util.HashMap<>();
    javaInit.put("key1", "1");
    javaInit.put("key2", "2");
    Map<String, String> slangInit = this.<String, String>emptyMap().put("key1", "1").put("key2", "2");
    ObjectMapper mapper = xmlMapperJaxb();
    String javaJson = mapper.writeValueAsString(new JaxbXmlSerializeJavaUtil().init(javaInit));
    String slangJson = mapper.writeValueAsString(new JaxbXmlSerializeVavr().init(slangInit));
    Assertions.assertEquals(javaJson, slangJson);
    JaxbXmlSerializeVavr restored = mapper.readValue(slangJson, JaxbXmlSerializeVavr.class);
    Assertions.assertEquals(restored.transitTypes.get("key1").get(), "1");
    Assertions.assertEquals(restored.transitTypes.get("key2").get(), "2");
}
 
Example #8
Source File: TimeLimiterImpl.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public TimeLimiterImpl(String name, TimeLimiterConfig timeLimiterConfig,
    io.vavr.collection.Map<String, String> tags) {
    this.name = name;
    this.tags = Objects.requireNonNull(tags, "Tags must not be null");
    this.timeLimiterConfig = timeLimiterConfig;
    this.eventProcessor = new TimeLimiterEventProcessor();
}
 
Example #9
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    Map<Object, Object> vavrObject = emptyMap().put("1", 2);
    java.util.Map<Object, Object> javaObject = new java.util.HashMap<>();
    javaObject.put("1", 2);

    String json = mapper().writer().writeValueAsString(vavrObject);
    Assertions.assertEquals(genJsonMap(javaObject), json);

    Map<?, ?> restored = (Map<?, ?>) mapper().readValue(json, clz());
    Assertions.assertEquals(restored, vavrObject);
}
 
Example #10
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testSerializable() throws IOException {
    ObjectMapper mapper = mapper();
    Map<?, ?> src = emptyMap().put("1", 2);
    Map<?, ?> restored = (Map<?, ?>) mapper.readValue(mapper.writeValueAsString(src), clz());
    checkSerialization(restored);
}
 
Example #11
Source File: ReplicationIntegrationSpec.java    From ts-reaktive with MIT License 5 votes vote down vote up
public DC(final String name, final int httpPort, Map<String,Integer> remotes) {
    this.name = name;
    config = ConfigFactory.parseMap(HashMap.<String,Object>
        of("clustering.port", clusteringPort)
        .put("clustering.seed-port", clusteringPort)
        .put("ts-reaktive.replication.local-datacenter.name", name)
        .put("ts-reaktive.replication.server.host", "localhost")
        .put("ts-reaktive.replication.server.port", httpPort)
        .put("ts-reaktive.replication.cassandra.keyspace", "replication_" + name)
        .put("cassandra-journal.port", CassandraLauncher.randomPort())
        .put("clustering.name", name)
        .put("cassandra-journal.keyspace", name) // each datacenter is in its own cassandra keyspace
        .merge(
            HashMap.ofEntries(remotes.map(r -> Tuple.of("ts-reaktive.replication.remote-datacenters." + r._1 + ".url", "wss://localhost:" + r._2)))
        )
        .toJavaMap()
        ).withFallback(ConfigFactory.parseResources("com/tradeshift/reaktive/replication/ReplicationIntegrationSpec.conf")).withFallback(ConfigFactory.defaultReference()).resolve();
    
    system = ActorSystem.create(config.getString("clustering.name"), config);
    shardRegion = ReplicatedTestActor.sharding.shardRegion(system);
    
    new AkkaPersistence(system).awaitPersistenceInit();
    
    try {
        System.out.println("*** AWAITING (" + name + ")");
        Replication.get(system).start(HashMap.of(TestEvent.class, shardRegion)).toCompletableFuture().get(30, TimeUnit.SECONDS);
        System.out.println("*** DONE (" + name + ")");
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
    
}
 
Example #12
Source File: XMLToJSON.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Map<QName,XSParticle> getValidSubTags(XSElementDeclaration elmt) {
    if (!(elmt.getTypeDefinition() instanceof XSComplexTypeDefinition)) {
        return HashMap.empty();
    }
    
    XSComplexTypeDefinition type = (XSComplexTypeDefinition) elmt.getTypeDefinition();
    if (type.getParticle() == null || !(type.getParticle().getTerm() instanceof XSModelGroup)) {
        return HashMap.empty();
    }
    
    XSModelGroup group = (XSModelGroup) type.getParticle().getTerm();
    if (group.getCompositor() != XSModelGroup.COMPOSITOR_SEQUENCE && group.getCompositor() != XSModelGroup.COMPOSITOR_CHOICE) {
        return HashMap.empty();
    }
    
    // We don't care whether it's SEQUENCE or CHOICE, we only want to know what are the valid sub-elements at this level.
    XSObjectList particles = group.getParticles();
    Map<QName,XSParticle> content = HashMap.empty();
    for (int j = 0; j < particles.getLength(); j++) {
        XSParticle sub = (XSParticle) particles.get(j);
        if (sub.getTerm() instanceof XSElementDeclaration) {
            XSElementDeclaration term = (XSElementDeclaration) sub.getTerm();
            content = content.put(new QName(term.getNamespace(), term.getName()), sub);
        }
    }
    return content;
}
 
Example #13
Source File: AtomicRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public AtomicRateLimiter(String name, RateLimiterConfig rateLimiterConfig,
                         Map<String, String> tags) {
    this.name = name;
    this.tags = tags;

    waitingThreads = new AtomicInteger(0);
    state = new AtomicReference<>(new State(
        rateLimiterConfig, 0, rateLimiterConfig.getLimitForPeriod(), 0
    ));
    eventProcessor = new RateLimiterEventProcessor();
}
 
Example #14
Source File: MaterializerMetrics.java    From ts-reaktive with MIT License 5 votes vote down vote up
public MaterializerMetrics(String name, Map<String, String> additionalTags) {
    baseTags = additionalTags.put("journal-materializer", name);
    java.util.Map<String, String> tags = baseTags.toJavaMap();
    this.events = Kamon.counter("journal-materializer.events");
    this.restarts = Kamon.counter("journal-materializer.restarts").refine(tags);
    this.reimportRemaining = Kamon.gauge("journal-materializer.reimport-remaining", MeasurementUnit.time().milliseconds()).refine(tags);
    this.offset = Kamon.gauge("journal-materializer.offset", MeasurementUnit.time().milliseconds());
    this.delay = Kamon.gauge("journal-materializer.delay", MeasurementUnit.time().milliseconds());
    this.remaining = Kamon.gauge("journal-materializer.remaining", MeasurementUnit.time().milliseconds());
    this.materializationDuration = Kamon.histogram("journal-materializer.materialization-duration", MeasurementUnit.time().milliseconds());
    this.workers = Kamon.gauge("journal-materializer.workers").refine(tags);
    this.streams = Kamon.gauge("journal-materializer.streams").refine(tags);
}
 
Example #15
Source File: NullSafe.java    From paleo with Apache License 2.0 5 votes vote down vote up
static Map<String, String> safeMap(StringStringMap javaMap) {
    if (javaMap == null) {
        return LinkedHashMap.empty();
    } else {
        return LinkedHashMap.ofAll(javaMap);
    }
}
 
Example #16
Source File: ParserTest.java    From paleo with Apache License 2.0 5 votes vote down vote up
private static void assertMetaDataParsedCorrectly(DataFrame df) {
    Map<String, String> dataFrameMetaData = df.getMetaData();
    assertEquals(1, dataFrameMetaData.size());
    assertEquals(Option.of("netzwerg"), dataFrameMetaData.get("author"));

    Map<String, String> columnMetaData = df.getColumn(df.getColumnId(2, ColumnType.DOUBLE)).getMetaData();
    assertEquals(1, columnMetaData.size());
    assertEquals(Option.of("m"), columnMetaData.get("unit"));
}
 
Example #17
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test3() throws IOException {
    ObjectMapper mapper = mapper().addMixIn(clz(), WrapperArray.class);
    Map<?, ?> src = emptyMap().put("1", 2);
    String plainJson = mapper().writeValueAsString(src);
    String wrappedJson = mapper.writeValueAsString(src);
    Assertions.assertEquals(wrappedJson, wrapToArray(clz().getName(), plainJson));
    Map<?, ?> restored = (Map<?, ?>) mapper.readValue(wrappedJson, clz());
    Assertions.assertEquals(src, restored);
    Assertions.assertEquals(src, restored);
}
 
Example #18
Source File: LinkedHashMapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void shouldKeepOrder() throws IOException {
    Map<Object, Object> vavrObject = emptyMap().put("2", 1).put("1", 2);
    java.util.Map<Object, Object> javaObject = new java.util.LinkedHashMap<>();
    javaObject.put("2", 1);
    javaObject.put("1", 2);

    String json = mapper().writer().writeValueAsString(vavrObject);
    Assertions.assertEquals(genJsonMap(javaObject), json);

    Map<?, ?> restored = (Map<?, ?>) mapper().readValue(json, clz());
    Assertions.assertEquals(restored, vavrObject);
}
 
Example #19
Source File: AbstractRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public AbstractRegistry(C defaultConfig, List<RegistryEventConsumer<E>> registryEventConsumers,
                        Map<String, String> tags, RegistryStore<E> registryStore) {
    this.configurations = new ConcurrentHashMap<>();
    this.entryMap = Objects.requireNonNull(registryStore, REGISTRY_STORE_MUST_NOT_BE_NULL);
    this.eventProcessor = new RegistryEventProcessor(
        Objects.requireNonNull(registryEventConsumers, CONSUMER_MUST_NOT_BE_NULL));
    this.registryTags = Objects.requireNonNull(tags, TAGS_MUST_NOT_BE_NULL);
    this.configurations
        .put(DEFAULT_CONFIG, Objects.requireNonNull(defaultConfig, CONFIG_MUST_NOT_BE_NULL));
}
 
Example #20
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeNullValue() throws IOException {
    Map<String, String> stringStringMap = mapper().readValue("{\"1\":null}", new TypeReference<Map<String, String>>() {});
    Map<String, Object> stringObjectMap = mapper().readValue("{\"1\":null}", new TypeReference<Map<String, Object>>() {});

    Assertions.assertEquals(emptyMap().put("1", null), stringStringMap);
    Assertions.assertEquals(emptyMap().put("1", null), stringObjectMap);
}
 
Example #21
Source File: CircuitBreakerStateMachine.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a circuitBreaker.
 *
 * @param name                 the name of the CircuitBreaker
 * @param circuitBreakerConfig The CircuitBreaker configuration.
 * @param clock                A Clock which can be mocked in tests.
 * @param schedulerFactory     A SchedulerFactory which can be mocked in tests.
 */
private CircuitBreakerStateMachine(String name, CircuitBreakerConfig circuitBreakerConfig,
    Clock clock, SchedulerFactory schedulerFactory,
    io.vavr.collection.Map<String, String> tags) {
    this.name = name;
    this.circuitBreakerConfig = Objects
        .requireNonNull(circuitBreakerConfig, "Config must not be null");
    this.eventProcessor = new CircuitBreakerEventProcessor();
    this.clock = clock;
    this.stateReference = new AtomicReference<>(new ClosedState());
    this.schedulerFactory = schedulerFactory;
    this.tags = Objects.requireNonNull(tags, "Tags must not be null");
}
 
Example #22
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testContextualSerialization() throws IOException {
    Map<CustomKey, CustomValue> empty = emptyMap();
    Map<CustomKey, CustomValue> map = empty.put(new CustomKey(123), new CustomValue("test"));

    Model source = new Model(map);
    String json = mapper().writeValueAsString(source);
    assertEquals("{\"map\":{\"123\":\"test\"}}", json);

    Model restored = mapper().readValue(json, Model.class);
    assertEquals(1, restored.map.size());
    assertEquals(123, restored.map.get()._1.id);
    assertEquals("test", restored.map.get()._2.value);
}
 
Example #23
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 4 votes vote down vote up
public JaxbXmlSerializeVavr init(Map<String, String> javaSet) {
    transitTypes = javaSet;
    return this;
}
 
Example #24
Source File: IntColumn.java    From paleo with Apache License 2.0 4 votes vote down vote up
@Override
public Builder putAllMetaData(Map<String, String> metaData) {
    metaDataBuilder.putAllMetaData(metaData);
    return this;
}
 
Example #25
Source File: CategoryColumn.java    From paleo with Apache License 2.0 4 votes vote down vote up
@Override
public Builder putAllMetaData(Map<String, String> metaData) {
    metaDataBuilder.putAllMetaData(metaData);
    return this;
}
 
Example #26
Source File: CategoryColumn.java    From paleo with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, String> getMetaData() {
    return metaData;
}
 
Example #27
Source File: HashMapTest.java    From vavr-jackson with Apache License 2.0 4 votes vote down vote up
@Test
void testDefaultDeserialization() throws IOException {
    Assertions.assertEquals(mapper().readValue("{\"1\":\"2\"}", Map.class), HashMap.empty().put("1", "2"));
}
 
Example #28
Source File: StringColumn.java    From paleo with Apache License 2.0 4 votes vote down vote up
private StringColumn(StringColumnId id, Array<String> values, Map<String, String> metaData) {
    super(id, values, metaData);
}
 
Example #29
Source File: AbstractContentTest.java    From vavr-jackson with Apache License 2.0 4 votes vote down vote up
public void setXs(Map<Integer, AX> xs) {
    this.xs = xs;
}
 
Example #30
Source File: CategoryColumn.java    From paleo with Apache License 2.0 4 votes vote down vote up
private CategoryColumn(CategoryColumnId id, Array<String> categories, Array<Integer> categoryIndexPerRowIndex, Map<String, String> metaData) {
    this.id = id;
    this.categories = categories;
    this.categoryIndexPerRowIndex = categoryIndexPerRowIndex;
    this.metaData = metaData;
}