Example usage for java.time Duration ofMillis

List of usage examples for java.time Duration ofMillis

Introduction

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

Prototype

public static Duration ofMillis(long millis) 

Source Link

Document

Obtains a Duration representing a number of milliseconds.

Usage

From source file:org.bremersee.common.spring.autoconfigure.LdaptiveAutoConfiguration.java

private ConnectionConfig connectionConfig() {

    ConnectionConfig cc = new ConnectionConfig();
    cc.setLdapUrl(properties.getLdapUrl());

    if (properties.getConnectTimeout() > 0L) {
        cc.setConnectTimeout(Duration.ofMillis(properties.getConnectTimeout()));
    }//from   w w w  . j  ava 2s.  c  om
    if (properties.getResponseTimeout() > 0L) {
        cc.setResponseTimeout(Duration.ofMillis(properties.getResponseTimeout()));
    }

    cc.setUseSSL(properties.isUseSsl());
    cc.setUseStartTLS(properties.isUseStartTls());

    if (properties.isUseSsl() || properties.isUseStartTls()) {
        cc.setSslConfig(sslConfig());
    }

    // binds all operations to a dn
    if (StringUtils.isNotBlank(properties.getBindDn())) {
        cc.setConnectionInitializer(connectionInitializer());
    }

    return cc;
}

From source file:com.teradata.benchto.driver.execution.ExecutionDriverTest.java

@Test
public void finishWhenTimeLimitEnds() {
    when(benchmarkProperties.getTimeLimit()).thenReturn(Optional.of(Duration.ofMillis(100)));

    sleepOnSecondDuringMacroExecution();

    driver.execute();//from   w  ww  .j  a v  a2 s .  c  om

    verifyNoMoreInteractions(benchmarkExecutionDriver);
}

From source file:com.lleps.jsamp.transition.BodyTransition.java

public BodyTransition play(Body body) {
    Vector3D fromPos = fromPosition, toPos = toPosition;
    Vector3D fromRot = fromRotation, toRot = toRotation;

    if (fromPos != null) {
        if (!body.getPosition().equals(fromPos)) { // Set only if position changed
            body.setPosition(fromPos);//ww  w . j  a  v a  2s.com
        }
    } else {
        fromPos = body.getPosition();
    }

    if (toPos == null) {
        // if ToPos is not specified, position will not change.
        toPos = body.getPosition();
    }

    if (fromRot != null) {
        if (!body.getRotation().equals(fromRot)) {
            body.setRotation(fromRot);
        }
    } else {
        fromRot = body.getRotation();
    }

    if (toRot == null) {
        toRot = body.getRotation();
    }

    float calculatedSpeed = 0;
    float timeToMove = 0;
    if (movementType == MovementType.TYPE_DURATION) {
        float distanceToMove = fromPos.distanceTo(toPos);

        // only rotation changed?  add a little z movement
        if (distanceToMove == 0) {
            SAMPFunctions.SendClientMessageToAll(-1, "dist 2 move is 0");
            float toAdd = (RandomUtils.nextInt(0, 2) == 0) ? -0.01f : 0.01f;
            toPos = toPos.plusZ(toAdd);
            distanceToMove = fromPos.distanceTo(toPos);
        }

        // Calculate speed based on time to move.
        calculatedSpeed = distanceToMove / (duration.toMillis() / 1000f);
    } else {
        calculatedSpeed = speed;
    }

    int msToMove = body.move(toPos, toRot, calculatedSpeed);

    SAMPServer.runLater(Duration.ofMillis(msToMove), () -> {
        if (onFinishListener != null)
            onFinishListener.onFinish(body);
    });
    return this;
}

From source file:com.github.rozidan.springboot.logger.LoggerMsgFormatter.java

private String warnDuration(Loggable loggable) {
    return Duration.ofMillis(loggable.warnUnit().toMillis(loggable.warnOver())).toString();
}

From source file:eu.mihosoft.vrl.fxscad.MainController.java

/**
 * Initializes the controller class./*from ww  w.  jav a2 s  .c  o m*/
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    //
    codeArea.textProperty().addListener((ov, oldText, newText) -> {
        Matcher matcher = KEYWORD_PATTERN.matcher(newText);
        int lastKwEnd = 0;
        StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
        while (matcher.find()) {
            spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
            spansBuilder.add(Collections.singleton("keyword"), matcher.end() - matcher.start());
            lastKwEnd = matcher.end();
        }
        spansBuilder.add(Collections.emptyList(), newText.length() - lastKwEnd);
        codeArea.setStyleSpans(0, spansBuilder.create());
    });

    EventStream<Change<String>> textEvents = EventStreams.changesOf(codeArea.textProperty());

    textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(500)).subscribe(code -> {
        if (autoCompile) {
            compile(code.getNewValue());
        }
    });

    codeArea.replaceText("CSG cube = new Cube(2).toCSG()\n" + "CSG sphere = new Sphere(1.25).toCSG()\n" + "\n"
            + "cube.difference(sphere)");

    editorContainer.setContent(codeArea);

    subScene = new SubScene(viewGroup, 100, 100, true, SceneAntialiasing.BALANCED);

    subScene.widthProperty().bind(viewContainer.widthProperty());
    subScene.heightProperty().bind(viewContainer.heightProperty());

    PerspectiveCamera subSceneCamera = new PerspectiveCamera(false);
    subScene.setCamera(subSceneCamera);

    viewContainer.getChildren().add(subScene);
}

From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java

@Override
public void start(Map<String, String> props) {
    setConfigurationProperties(props);/* w  w w.  j  av  a2 s  .  co m*/

    transferQueue = new LinkedTransferQueue<>();
    opcOperations = new SmartOpcOperations<>(createOpcOperations());
    ConnectionProfile connectionProfile = createConnectionProfile();
    host = connectionProfile.getConnectionUri().getHost();
    tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream()
            .collect(Collectors.toMap(TagInfo::getTagId, Function.identity()));
    minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval)
            .mapToLong(Duration::toMillis).min().getAsLong());
    opcOperations.connect(connectionProfile);
    if (!opcOperations.awaitConnected()) {
        throw new ConnectException("Unable to connect");
    }

    //set up polling source emission
    pollingScheduler = Executors.newSingleThreadScheduledExecutor();
    streamingThread = Executors.newSingleThreadExecutor();
    Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream()
            .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode()))
            .collect(Collectors.groupingBy(TagInfo::getSamplingInterval));
    final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>());
    pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> {
        final Instant now = Instant.now();
        v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull))
                .map(data -> Pair.of(now, data)).forEach(transferQueue::add);

    }, 0, k.toNanos(), TimeUnit.NANOSECONDS));
    //then subscribe for all
    final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration()
            .withDefaultSamplingInterval(Duration.ofMillis(10_000));
    tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration
            .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval()));
    running.set(true);
    streamingThread.submit(() -> {
        while (running.get()) {
            try {
                createSessionIfNeeded();
                if (session == null) {
                    return;
                }

                session.stream(subscriptionConfiguration,
                        tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> {
                            if (tagInfoMap.get(opcData.getTag()).getStreamingMode()
                                    .equals(StreamingMode.SUBSCRIBE)) {
                                transferQueue.add(Pair.of(
                                        hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(),
                                        opcData));
                            } else {
                                lastValues.put(opcData.getTag(), opcData);
                            }
                        });
            } catch (Exception e) {
                if (running.get()) {
                    logger.warn("Stream interrupted while reading from " + host, e);
                    safeCloseSession();
                    lastValues.clear();

                }
            }
        }
    });

}

From source file:com.neuronrobotics.bowlerstudio.MainController.java

public static void updateLog() {
    if (logViewRef != null) {
        String current;//w ww.ja  va 2s  .  co  m
        String finalStr;
        if (getOut().size() == 0) {
            newString = null;
        } else {
            newString = getOut().toString();
            getOut().reset();
        }
        if (newString != null) {
            current = logViewRef.getText() + newString;
            try {
                finalStr = new String(current.substring(current.getBytes().length - sizeOfTextBuffer));
            } catch (StringIndexOutOfBoundsException ex) {
                finalStr = current;
            }
            int strlen = finalStr.length() - 1;
            logViewRef.setText(finalStr);
            Platform.runLater(() -> logViewRef.positionCaret(strlen));
        }

    }
    FxTimer.runLater(Duration.ofMillis(100), () -> {

        updateLog();
    });
}

From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java

/**
 * Add this reader to the reader group so that it is able to acquire segments
 */// w ww .ja v  a2 s . co m
void initializeReader(long initialAllocationDelay) {
    AtomicBoolean alreadyAdded = new AtomicBoolean(false);
    sync.updateState(state -> {
        if (state.getSegments(readerId) == null) {
            return Collections.singletonList(new AddReader(readerId));
        } else {
            alreadyAdded.set(true);
            return null;
        }
    });
    if (alreadyAdded.get()) {
        throw new IllegalStateException("The requested reader: " + readerId
                + " cannot be added to the group because it is already in the group. Perhaps close() was not called?");
    }
    long randomDelay = (long) (RandomUtils.nextFloat()
            * Math.min(initialAllocationDelay, sync.getState().getConfig().getGroupRefreshTimeMillis()));
    acquireTimer.reset(Duration.ofMillis(initialAllocationDelay + randomDelay));
}

From source file:com.github.rozidan.springboot.logger.LoggerMsgFormatter.java

private String durationString(long nano) {
    return Duration.ofMillis(TimeUnit.NANOSECONDS.toMillis(nano)).toString();
}

From source file:org.bremersee.common.spring.autoconfigure.LdaptiveAutoConfiguration.java

private ConnectionPool connectionPool() {
    BlockingConnectionPool pool = new BlockingConnectionPool();
    pool.setConnectionFactory(defaultConnectionFactory(null));
    pool.setPoolConfig(poolConfig());/*w ww  . j  a v  a 2s  .  co  m*/
    pool.setPruneStrategy(pruneStrategy());
    pool.setValidator(searchValidator());
    if (properties.getBlockWaitTime() > 0L) {
        pool.setBlockWaitTime(Duration.ofMillis(properties.getBlockWaitTime()));
    }
    pool.initialize();
    return pool;
}