Example usage for java.time Duration ofSeconds

List of usage examples for java.time Duration ofSeconds

Introduction

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

Prototype

public static Duration ofSeconds(long seconds) 

Source Link

Document

Obtains a Duration representing a number of seconds.

Usage

From source file:org.nuxeo.runtime.AbstractRuntimeService.java

@Override
public synchronized void stop() {
    if (!isStarted) {
        return;//from   w  ww . j  av a  2 s  .c om
    }
    isShuttingDown = true;
    try {
        log.info("Stopping Nuxeo Runtime service " + getName() + "; version: " + getVersion());
        Framework.sendEvent(new RuntimeServiceEvent(RuntimeServiceEvent.RUNTIME_ABOUT_TO_STOP, this));
        ServicePassivator.passivate().withQuietDelay(Duration.ofSeconds(0)).monitor()
                .withTimeout(Duration.ofSeconds(0)).withEnforceMode(false).await().proceed(() -> {
                    try {
                        stopExtensions();
                        doStop();
                        manager.shutdown();
                    } finally {
                        isStarted = false;
                        Framework.sendEvent(new RuntimeServiceEvent(RuntimeServiceEvent.RUNTIME_STOPPED, this));
                        manager = null;
                    }
                });
    } finally {
        JavaUtilLoggingHelper.reset();
        isShuttingDown = false;
    }
}

From source file:org.nuxeo.runtime.api.TestServicePassivation.java

@Test
@LocalDeploy({ "org.nuxeo.runtime:passivation-test-service.xml",
        "org.nuxeo.runtime:passivation-test-provider.xml" })
public void lookupsAreBlocked() throws InterruptedException, ExecutionException {
    abstract class AbstractTask implements Runnable {

        Future<?> future;/*from  ww  w. j  a  v a  2  s .  c  o m*/

        @SuppressWarnings("unchecked")
        <T> T submit() {
            future = executor.submit(this);
            return (T) this;
        }

        void await() {
            try {
                future.get(10, TimeUnit.SECONDS);
            } catch (InterruptedException cause) {
                Thread.currentThread().interrupt();
                throw new AssertionError("Interruped while synching with task", cause);
            } catch (ExecutionException | TimeoutException cause) {
                throw new AssertionError("Cannot synch with task", cause);
            } finally {
                future = null;
            }
        }

    }
    class AwaitThenForward extends AbstractTask {

        final CountDownLatch entered = new CountDownLatch(1);

        final CountDownLatch canProceed = new CountDownLatch(1);

        void unlock() {
            canProceed.countDown();
        }

        void unlockAndAwait() {
            unlock();
            await();
        }

        @Override
        public void run() {
            try {
                Framework.getService(Service.class).awaitThenForward(entered, canProceed);
            } catch (InterruptedException cause) {
                throw new AssertionError("Cannot proceed in service");
            }
        }

        @Override
        <T> T submit() {
            try {
                return super.submit();
            } finally {
                try {
                    entered.await(10, TimeUnit.SECONDS);
                } catch (InterruptedException cause) {
                    Thread.currentThread().interrupt();
                    throw new AssertionError("Timed out while waiting for service entered", cause);
                }
            }
        }

    }

    class EnterQuiet extends AbstractTask {

        @Override
        public void run() {
            Framework.getService(Service.class).enterQuiet();
        }

    }

    AwaitThenForward canProceed = new AwaitThenForward().submit();
    AwaitThenForward wrongAccess = new AwaitThenForward().submit();
    EnterQuiet enterQuiet = new EnterQuiet();

    Termination termination = ServicePassivator.passivate().peek(passivator -> canProceed.unlockAndAwait())
            .withQuietDelay(Duration.ofSeconds(1)).monitor().peek(passivator -> enterQuiet.<EnterQuiet>submit())
            .withTimeout(Duration.ofSeconds(5)).await().proceed(() -> wrongAccess.unlockAndAwait())
            .peek(self -> enterQuiet.await());
    assertThat(termination).isInstanceOf(Failure.class);
}

From source file:org.nuxeo.runtime.osgi.OSGiRuntimeService.java

@Override
public void frameworkEvent(FrameworkEvent event) {
    if (event.getType() != FrameworkEvent.STARTED) {
        return;/*  w w  w . j  av  a  2 s. c  om*/
    }
    ServicePassivator.proceed(Duration.ofSeconds(0), Duration.ofSeconds(0), false,
            this::fireApplicationStarted);
}

From source file:org.nuxeo.runtime.reload.ReloadComponent.java

protected void triggerReloadWithPassivate(String id) {
    log.info("about to passivate for " + id);
    Framework.getLocalService(EventService.class)
            .sendEvent(new Event(RELOAD_TOPIC, BEFORE_RELOAD_EVENT_ID, this, null));
    try {/*from  w  ww .ja  v  a  2 s .  co m*/
        ServicePassivator.proceed(Duration.ofSeconds(5), Duration.ofSeconds(30), true, () -> {
            log.info("about to send " + id);
            Framework.getLocalService(EventService.class).sendEvent(new Event(RELOAD_TOPIC, id, this, null));
        }).onFailure(snapshot -> {
            throw new UnsupportedOperationException(
                    "Detected access, should initiate a reboot " + snapshot.toString());
        });
    } finally {
        Framework.getLocalService(EventService.class)
                .sendEvent(new Event(RELOAD_TOPIC, AFTER_RELOAD_EVENT_ID, this, null));
        log.info("returning from " + id);
    }
}

From source file:org.openhab.binding.airvisualnode.internal.handler.AirVisualNodeHandler.java

private State getChannelState(String channelId, NodeData nodeData) {
    State state = UnDefType.UNDEF;

    // Handle system channel IDs separately, because 'switch/case' expressions must be constant expressions
    if (CHANNEL_BATTERY_LEVEL.equals(channelId)) {
        state = new DecimalType(BigDecimal.valueOf(nodeData.getStatus().getBattery()).longValue());
    } else if (CHANNEL_WIFI_STRENGTH.equals(channelId)) {
        state = new DecimalType(
                BigDecimal.valueOf(Math.max(0, nodeData.getStatus().getWifiStrength() - 1)).longValue());
    } else {/*from   w  w w.  java  2 s . c o  m*/
        // Handle binding-specific channel IDs
        switch (channelId) {
        case CHANNEL_CO2:
            state = new QuantityType<>(nodeData.getMeasurements().getCo2Ppm(), PARTS_PER_MILLION);
            break;
        case CHANNEL_HUMIDITY:
            state = new QuantityType<>(nodeData.getMeasurements().getHumidityRH(), PERCENT);
            break;
        case CHANNEL_AQI_US:
            state = new QuantityType<>(nodeData.getMeasurements().getPm25AQIUS(), ONE);
            break;
        case CHANNEL_PM_25:
            // PM2.5 is in ug/m3
            state = new QuantityType<>(nodeData.getMeasurements().getPm25Ugm3(),
                    MICRO(GRAM).divide(CUBIC_METRE));
            break;
        case CHANNEL_TEMP_CELSIUS:
            state = new QuantityType<>(nodeData.getMeasurements().getTemperatureC(), CELSIUS);
            break;
        case CHANNEL_TIMESTAMP:
            // It seem the Node timestamp is Unix timestamp converted from UTC time plus timezone offset.
            // Not sure about DST though, but it's best guess at now
            Instant instant = Instant.ofEpochMilli(nodeData.getStatus().getDatetime() * 1000L);
            ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
            ZoneId zoneId = ZoneId.of(nodeData.getSettings().getTimezone());
            ZoneRules zoneRules = zoneId.getRules();
            zonedDateTime.minus(Duration.ofSeconds(zoneRules.getOffset(instant).getTotalSeconds()));
            if (zoneRules.isDaylightSavings(instant)) {
                zonedDateTime.minus(Duration.ofSeconds(zoneRules.getDaylightSavings(instant).getSeconds()));
            }
            state = new DateTimeType(zonedDateTime);
            break;
        case CHANNEL_USED_MEMORY:
            state = new DecimalType(BigDecimal.valueOf(nodeData.getStatus().getUsedMemory()).longValue());
            break;
        }
    }

    return state;
}

From source file:org.openhab.binding.smartmeter.internal.SmartMeterHandler.java

/**
 * Get new data the device/*w  ww.j  av  a2 s  . c o  m*/
 *
 */
private void updateOBISValue() {
    cancelRead();

    valueChangeListener = new MeterValueListener() {
        @Override
        public <Q extends @NonNull Quantity<Q>> void valueChanged(MeterValue<Q> value) {
            ThingBuilder thingBuilder = editThing();

            String obis = value.getObisCode();

            String obisChannelString = SmartMeterBindingConstants.getObisChannelId(obis);
            Channel channel = thing.getChannel(obisChannelString);
            ChannelTypeUID channelTypeId = channelTypeProvider.getChannelTypeIdForObis(obis);

            ChannelType channelType = channelTypeProvider.getChannelType(channelTypeId, null);
            if (channelType != null) {
                String itemType = channelType.getItemType();

                State state = getStateForObisValue(value, channel);
                if (channel == null) {
                    logger.debug("Adding channel: {} with item type: {}", obisChannelString, itemType);

                    // channel has not been created yet
                    ChannelBuilder channelBuilder = ChannelBuilder
                            .create(new ChannelUID(thing.getUID(), obisChannelString), itemType)
                            .withType(channelTypeId);

                    Configuration configuration = new Configuration();
                    configuration.put(SmartMeterBindingConstants.CONFIGURATION_CONVERSION, 1);
                    channelBuilder.withConfiguration(configuration);
                    channelBuilder.withLabel(obis);
                    Map<String, String> channelProps = new HashMap<>();
                    channelProps.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis);
                    channelBuilder.withProperties(channelProps);
                    channelBuilder.withDescription(MessageFormat
                            .format("Value for OBIS code: {0} with Unit: {1}", obis, value.getUnit()));
                    channel = channelBuilder.build();
                    ChannelUID channelId = channel.getUID();

                    // add all valid channels to the thing builder
                    List<Channel> channels = new ArrayList<Channel>(getThing().getChannels());
                    if (channels.stream().filter((element) -> element.getUID().equals(channelId))
                            .count() == 0) {
                        channels.add(channel);
                        thingBuilder.withChannels(channels);
                        updateThing(thingBuilder.build());
                    }
                }

                if (!channel.getProperties().containsKey(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS)) {
                    addObisPropertyToChannel(obis, channel);
                }
                updateState(channel.getUID(), state);

                updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
            } else {
                logger.warn("No ChannelType found for OBIS {}", obis);
            }
        }

        private void addObisPropertyToChannel(String obis, Channel channel) {
            String description = channel.getDescription();
            String label = channel.getLabel();
            ChannelBuilder newChannel = ChannelBuilder.create(channel.getUID(), channel.getAcceptedItemType())
                    .withDefaultTags(channel.getDefaultTags()).withConfiguration(channel.getConfiguration())
                    .withDescription(description == null ? "" : description).withKind(channel.getKind())
                    .withLabel(label == null ? "" : label).withType(channel.getChannelTypeUID());
            HashMap<String, String> properties = new HashMap<>(channel.getProperties());
            properties.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis);
            newChannel.withProperties(properties);
            updateThing(editThing().withoutChannel(channel.getUID()).withChannel(newChannel.build()).build());
        }

        @Override
        public <Q extends @NonNull Quantity<Q>> void valueRemoved(MeterValue<Q> value) {
            // channels that are not available are removed
            String obisChannelId = SmartMeterBindingConstants.getObisChannelId(value.getObisCode());
            logger.debug("Removing channel: {}", obisChannelId);
            ThingBuilder thingBuilder = editThing();
            thingBuilder.withoutChannel(new ChannelUID(thing.getUID(), obisChannelId));
            updateThing(thingBuilder.build());
        }

        @Override
        public void errorOccurred(Throwable e) {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage());
        }
    };
    this.smlDevice.addValueChangeListener(valueChangeListener);

    SmartMeterConfiguration config = getConfigAs(SmartMeterConfiguration.class);
    int delay = config.refresh != null ? config.refresh : DEFAULT_REFRESH_PERIOD;
    valueReader = this.smlDevice.readValues(DEFAULT_TIMEOUT, this.scheduler, Duration.ofSeconds(delay));
}

From source file:org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundryAppDeployerTests.java

@SuppressWarnings("unchecked")
@Test/*from w w  w .  j  a v a 2s  . com*/
public void statusWithErrorThrownOnBlocking() throws Exception {
    AtomicInteger i = new AtomicInteger();
    Mono<ApplicationDetail> m = Mono.delay(Duration.ofSeconds(5)).then(Mono.create(s -> {
        i.incrementAndGet();
        s.success(ApplicationDetail.builder().diskQuota(0).id("test-application-id").instances(1).memoryLimit(0)
                .name("test-application").requestedState("RUNNING").runningInstances(1).stack("test-stack")
                .instanceDetail(InstanceDetail.builder().state("UNKNOWN").index("1").build()).build());
    }));
    givenRequestGetApplication("test-application-id", m);
    this.deployer.deploymentProperties.setApiTimeout(1);// Is less than the delay() above

    DeploymentState state = this.deployer.status("test-application-id").getState();
    assertThat(state, is(DeploymentState.error));
    assertThat(i.get(), is(0));
}

From source file:org.springframework.cloud.function.web.source.HttpSupplier.java

private Mono<?> transform(ClientResponse response) {
    HttpStatus status = response.statusCode();
    if (!status.is2xxSuccessful()) {
        if (this.props.isDebug()) {
            logger.info("Delaying supplier based on status=" + response.statusCode());
        }/*w w w  .j a  v a 2 s. c  o  m*/
        return Mono.delay(Duration.ofSeconds(1));
    }
    return response.bodyToMono(this.props.getSource().getType()).map(value -> message(response, value));
}

From source file:org.springframework.cloud.gateway.rsocket.server.GatewayRSocketTests.java

@Test
public void asyncFilter() {

    AsyncFilter filter = new AsyncFilter();

    Payload payload = new TestGatewayRSocket(registry, new TestRoutes(filter)).requestResponse(incomingPayload)
            .block(Duration.ofSeconds(5));

    assertThat(filter.invoked()).isTrue();
    assertThat(payload).isNotNull();/*from  w w w  . j  a v a2  s. c o m*/
}

From source file:org.springframework.cloud.gateway.rsocket.server.GatewayRSocketTests.java

@Test(expected = IllegalStateException.class)
public void handleErrorFromFilter() {

    ExceptionFilter filter = new ExceptionFilter();

    new TestGatewayRSocket(registry, new TestRoutes(filter)).requestResponse(incomingPayload)
            .block(Duration.ofSeconds(5));

    // assertNull(socket);
}