Example usage for java.time Duration of

List of usage examples for java.time Duration of

Introduction

In this page you can find the example usage for java.time Duration of.

Prototype

public static Duration of(long amount, TemporalUnit unit) 

Source Link

Document

Obtains a Duration representing an amount in the specified unit.

Usage

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java

@Test
public void test_CreateMultipleObjects_JSON_batch() throws InterruptedException, ExecutionException {

    final ElasticsearchCrudService<JsonNode> service = getTestService("testCreateMultipleObjects_json_batch",
            TestBean.class).getRawService();

    @SuppressWarnings("unchecked")
    final ElasticsearchCrudService<JsonNode>.ElasticsearchBatchSubsystem batch_service = service
            .getUnderlyingPlatformDriver(ElasticsearchBatchSubsystem.class, Optional.empty()).get();

    batch_service.setBatchProperties(Optional.empty(), Optional.empty(),
            Optional.of(Duration.of(2, ChronoUnit.SECONDS)), Optional.of(10));

    // 1) Insertion without ids

    assertEquals(0, service.countObjects().get().intValue());

    final List<JsonNode> l = IntStream.rangeClosed(1, 10).boxed().map(
            i -> BeanTemplateUtils.build(TestBean.class).with("test_string", "test_string" + i).done().get())
            .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList());

    batch_service.storeObjects(l, false);

    //Sleep for 5s to let it flush
    try {//from  ww w . ja  v  a 2 s.co  m
        Thread.sleep(5000L);
    } catch (Exception e) {
    }

    assertEquals(10, service.countObjects().get().intValue());

    // Check all the expected objects exist:

    IntStream.rangeClosed(1, 10).boxed().map(i -> "test_string" + i).forEach(Lambdas.wrap_consumer_u(field -> {
        Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)).get();
        assertTrue("NEeds to find: " + field, obj.isPresent());
    }));

    // 2) Insertion with ids

    service.deleteDatastore().get();

    batch_service.setBatchProperties(Optional.of(30), Optional.empty(), Optional.empty(), Optional.of(0));

    final List<JsonNode> l2 = IntStream.rangeClosed(51, 100).boxed()
            .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i)
                    .with("test_string", "test_string" + i).done().get())
            .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList());

    batch_service.storeObjects(l2, false);

    try {
        Thread.sleep(1500L);
    } catch (Exception e) {
    }

    assertEquals(30, service.countObjects().get().intValue());

    //Sleep for total 5s to let it flush
    try {
        Thread.sleep(3500L);
    } catch (Exception e) {
    }

    assertEquals(50, service.countObjects().get().intValue());

    IntStream.rangeClosed(51, 100).boxed().map(i -> "test_string" + i)
            .forEach(Lambdas.wrap_consumer_u(field -> {
                Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field))
                        .get();
                assertTrue("NEeds to find: " + field, obj.isPresent());
            }));

    // 4) Insertion with dups - fail on insert dups

    batch_service.setBatchProperties(Optional.empty(), Optional.of(10000L), Optional.empty(), Optional.of(5));

    final List<JsonNode> l4 = IntStream.rangeClosed(21, 120).boxed()
            .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i)
                    .with("test_string", "test_string2" + i).done().get())
            .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList());

    batch_service.storeObjects(l4, false);

    //Sleep for total 5s to let it flush
    try {
        Thread.sleep(5000L);
    } catch (Exception e) {
    }

    assertEquals(100, service.countObjects().get().intValue());

    // 5) Insertion with dups - overwrite 

    batch_service.setBatchProperties(Optional.of(20), Optional.empty(),
            Optional.of(Duration.of(4, ChronoUnit.SECONDS)), Optional.empty());
    try {
        Thread.sleep(100L);
    } catch (Exception e) {
    }

    final List<JsonNode> l5_1 = IntStream.rangeClosed(21, 59).boxed()
            .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i)
                    .with("test_string", "test_string5" + i).done().get())
            .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList());

    final List<JsonNode> l5_2 = IntStream.rangeClosed(60, 120).boxed()
            .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i)
                    .with("test_string", "test_string5" + i).done().get())
            .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList());

    batch_service.storeObjects(l5_1, true);

    // (wait for it to refresh)
    try {
        Thread.sleep(1100L);
    } catch (Exception e) {
    }

    assertEquals(100, service.countObjects().get().intValue()); // first batch                  

    // Check only some objects are overwritten
    IntStream.rangeClosed(21, 40).boxed().map(i -> "test_string5" + i)
            .forEach(Lambdas.wrap_consumer_u(field -> {
                Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field))
                        .get();
                assertTrue("NEeds to find: " + field, obj.isPresent());
            }));
    IntStream.rangeClosed(41, 50).boxed().map(i -> "test_string2" + i)
            .forEach(Lambdas.wrap_consumer_u(field -> {
                Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field))
                        .get();
                assertTrue("NEeds to find: " + field, obj.isPresent());
            }));
    IntStream.rangeClosed(51, 100).boxed().map(i -> "test_string" + i)
            .forEach(Lambdas.wrap_consumer_u(field -> {
                Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field))
                        .get();
                assertTrue("NEeds to find: " + field, obj.isPresent());
            }));

    batch_service.storeObjects(l5_2, true);

    //Sleep for total 1s to let it flush
    try {
        Thread.sleep(5000L);
    } catch (Exception e) {
    }

    assertEquals(100, service.countObjects().get().intValue());

    // Check all objects are overwritten

    IntStream.rangeClosed(21, 120).boxed().map(i -> "test_string5" + i)
            .forEach(Lambdas.wrap_consumer_u(field -> {
                Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field))
                        .get();
                assertTrue("NEeds to find: " + field, obj.isPresent());
            }));

}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.JWTSecurityHandler.java

@Override
public void init(Configuration config) throws Exception {
    LOG.info("Initializing JWT Security Handler");
    this.config = config;
    jwtEnabled = config.getBoolean(YarnConfiguration.RM_JWT_ENABLED, YarnConfiguration.DEFAULT_RM_JWT_ENABLED);
    jwtAudience = config.getTrimmedStrings(YarnConfiguration.RM_JWT_AUDIENCE,
            YarnConfiguration.DEFAULT_RM_JWT_AUDIENCE);
    renewalExecutorService = rmAppSecurityManager.getRenewalExecutorService();
    String validity = config.get(YarnConfiguration.RM_JWT_VALIDITY_PERIOD,
            YarnConfiguration.DEFAULT_RM_JWT_VALIDITY_PERIOD);
    validityPeriod = rmAppSecurityManager.parseInterval(validity, YarnConfiguration.RM_JWT_VALIDITY_PERIOD);
    String expirationLeewayConf = config.get(YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY,
            YarnConfiguration.DEFAULT_RM_JWT_EXPIRATION_LEEWAY);
    Pair<Long, TemporalUnit> expirationLeeway = rmAppSecurityManager.parseInterval(expirationLeewayConf,
            YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY);
    if (((ChronoUnit) expirationLeeway.getSecond()).compareTo(ChronoUnit.SECONDS) < 0) {
        throw new IllegalArgumentException(
                "Value of " + YarnConfiguration.RM_JWT_EXPIRATION_LEEWAY + " should be at least seconds");
    }/*from ww  w.j  a v a2s . co m*/
    leeway = Duration.of(expirationLeeway.getFirst(), expirationLeeway.getSecond()).getSeconds();
    if (jwtEnabled) {
        rmAppSecurityActions = rmAppSecurityManager.getRmAppCertificateActions();
    }
}

From source file:org.janusgraph.core.util.ManagementUtil.java

private static void awaitIndexUpdate(JanusGraph g, String indexName, String relationTypeName, long time,
        TemporalUnit unit) {//  www . j  ava  2s  . c om
    Preconditions.checkArgument(g != null && g.isOpen(), "Need to provide valid, open graph instance");
    Preconditions.checkArgument(time > 0 && unit != null, "Need to provide valid time interval");
    Preconditions.checkArgument(StringUtils.isNotBlank(indexName), "Need to provide an index name");
    StandardJanusGraph graph = (StandardJanusGraph) g;
    TimestampProvider times = graph.getConfiguration().getTimestampProvider();
    Instant end = times.getTime().plus(Duration.of(time, unit));
    boolean isStable = false;
    while (times.getTime().isBefore(end)) {
        JanusGraphManagement mgmt = graph.openManagement();
        try {
            if (StringUtils.isNotBlank(relationTypeName)) {
                RelationTypeIndex idx = mgmt.getRelationIndex(mgmt.getRelationType(relationTypeName),
                        indexName);
                Preconditions.checkArgument(idx != null, "Index could not be found: %s @ %s", indexName,
                        relationTypeName);
                isStable = idx.getIndexStatus().isStable();
            } else {
                JanusGraphIndex idx = mgmt.getGraphIndex(indexName);
                Preconditions.checkArgument(idx != null, "Index could not be found: %s", indexName);
                isStable = true;
                for (PropertyKey key : idx.getFieldKeys()) {
                    if (!idx.getIndexStatus(key).isStable())
                        isStable = false;
                }
            }
        } finally {
            mgmt.rollback();
        }
        if (isStable)
            break;
        try {
            times.sleepFor(Duration.ofMillis(500));
        } catch (InterruptedException e) {

        }
    }
    if (!isStable)
        throw new JanusGraphException(
                "Index did not stabilize within the given amount of time. For sufficiently long "
                        + "wait periods this is most likely caused by a failed/incorrectly shut down JanusGraph instance or a lingering transaction.");
}

From source file:org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration.java

@Override
public <O> O get(String key, Class<O> datatype) {
    if (!config.containsKey(key))
        return null;

    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class,
                "Only string arrays are supported: %s", datatype);
        return (O) config.getStringArray(key);
    } else if (Number.class.isAssignableFrom(datatype)) {
        // A properties file configuration returns Strings even for numeric
        // values small enough to fit inside Integer (e.g. 5000). In-memory
        // configuration impls seem to be able to store and return actual
        // numeric types rather than String
        ////from  w  ww  .j  a va  2 s .c  o m
        // We try to handle either case here
        Object o = config.getProperty(key);
        if (datatype.isInstance(o)) {
            return (O) o;
        } else {
            return constructFromStringArgument(datatype, o.toString());
        }
    } else if (datatype == String.class) {
        return (O) config.getString(key);
    } else if (datatype == Boolean.class) {
        return (O) new Boolean(config.getBoolean(key));
    } else if (datatype.isEnum()) {
        Enum[] constants = (Enum[]) datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");

        String estr = config.getProperty(key).toString();
        for (Enum ec : constants)
            if (ec.toString().equals(estr))
                return (O) ec;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        return (O) config.getProperty(key);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        Object o = config.getProperty(key);
        if (Duration.class.isInstance(o)) {
            return (O) o;
        } else {
            String[] comps = o.toString().split("\\s");
            TemporalUnit unit = null;
            if (comps.length == 1) {
                //By default, times are in milli seconds
                unit = ChronoUnit.MILLIS;
            } else if (comps.length == 2) {
                unit = Durations.parse(comps[1]);
            } else {
                throw new IllegalArgumentException("Cannot parse time duration from: " + o.toString());
            }
            return (O) Duration.of(Long.valueOf(comps[0]), unit);
        }
        // Lists are deliberately not supported.  List's generic parameter
        // is subject to erasure and can't be checked at runtime.  Someone
        // could create a ConfigOption<List<Number>>; we would instead return
        // a List<String> like we always do at runtime, and it wouldn't break
        // until the client tried to use the contents of the list.
        //
        // We could theoretically get around this by adding a type token to
        // every declaration of a List-typed ConfigOption, but it's just
        // not worth doing since we only actually use String[] anyway.
        //        } else if (List.class.isAssignableFrom(datatype)) {
        //            return (O) config.getProperty(key);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}

From source file:org.janusgraph.graphdb.berkeleyje.BerkeleyGraphTest.java

@Test
public void testIDBlockAllocationTimeout() {
    config.set("ids.authority.wait-time", Duration.of(0L, ChronoUnit.NANOS));
    config.set("ids.renew-timeout", Duration.of(1L, ChronoUnit.MILLIS));
    close();/*from w ww.j a va 2 s . c  om*/
    JanusGraphCleanup.clear(graph);
    open(config);
    try {
        graph.addVertex();
        fail();
    } catch (JanusGraphException e) {

    }

    assertTrue(graph.isOpen());

    close(); // must be able to close cleanly

    // Must be able to reopen
    open(config);

    assertEquals(0L, (long) graph.traversal().V().count().next());
}

From source file:org.lanternpowered.server.world.pregen.LanternChunkPreGenerateTask.java

@Override
public Duration getTotalTime() {
    return Duration.of(
            (isCancelled() ? this.generationEndTime : System.currentTimeMillis()) - this.generationStartTime,
            ChronoUnit.MILLIS);// w w  w  . j a  v a 2 s .  c  om
}

From source file:systems.composable.dropwizard.cassandra.cli.CommandInfo.java

@Override
void run(Namespace namespace, CassandraMigration cassandraMigration, Session session) throws Exception {
    final MigrationInfo[] migrationInfos = cassandraMigration.info(session).all();
    if (migrationInfos.length == 0)
        throw new IllegalStateException("No migration scripts found");

    final Map<String, Integer> widths = new HashMap<>();
    final List<Map<String, String>> rows = new LinkedList<>();

    INFOS.forEach(col -> widths.compute(col, (k, v) -> k.length()));
    Arrays.stream(migrationInfos).forEach(migrationInfo -> {
        final Map<String, String> row = new HashMap<>();
        INFOS.forEach(col -> {/*from   w  w  w.j  a  va  2s .c o m*/
            final String cell;
            switch (col) {
            case INFO_TYPE:
                cell = migrationInfo.getType().toString();
                break;
            case INFO_STATE:
                cell = migrationInfo.getState().getDisplayName();
                break;
            case INFO_VERSION:
                cell = migrationInfo.getVersion().toString();
                break;
            case INFO_DESC:
                cell = migrationInfo.getDescription();
                break;
            case INFO_SCRIPT:
                cell = migrationInfo.getScript();
                break;
            case INFO_CHKSUM:
                cell = String.valueOf(migrationInfo.getChecksum());
                break;
            case INFO_INST_ON:
                final Date d = migrationInfo.getInstalledOn();
                cell = d != null ? d.toInstant().toString() : "";
                break;
            case INFO_EXEC_MS:
                final Integer ms = migrationInfo.getExecutionTime();
                cell = ms != null ? Duration.of(ms, ChronoUnit.MILLIS).toString() : "";
                break;
            default:
                cell = "";
            }
            row.put(col, cell);
            widths.compute(col, (k, v) -> Math.max(cell.length(), v));
        });
        rows.add(row);
    });

    final String separator = "+"
            + INFOS.stream().map(col -> repeat('-', widths.get(col) + 2)).collect(Collectors.joining("+")) + "+"
            + System.lineSeparator();

    final StringBuilder sb = new StringBuilder().append(separator).append('|')
            .append(INFOS.stream().map(col -> " " + center(col, widths.get(col)) + " ")
                    .collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()).append(separator);
    rows.forEach(row -> sb.append('|').append(INFOS.stream()
            .map(col -> " " + leftPad(row.get(col), widths.get(col)) + " ").collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()));
    sb.append(separator);
    System.out.print(sb.toString());
}