List of usage examples for java.time Duration ofMillis
public static Duration ofMillis(long millis)
From source file:be.makercafe.apps.makerbench.editors.JFXMillEditor.java
public JFXMillEditor(String tabText, Path path) { super(tabText); this.viewGroup = new Group(); this.editorContainer = new BorderPane(); this.viewContainer = new Pane(); this.caCodeArea = new CodeArea(""); this.caCodeArea.setEditable(true); this.caCodeArea.setParagraphGraphicFactory(LineNumberFactory.get(caCodeArea)); this.caCodeArea.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE); this.caCodeArea.getStylesheets().add(this.getClass().getResource("java-keywords.css").toExternalForm()); this.caCodeArea.richChanges().subscribe(change -> { caCodeArea.setStyleSpans(0, computeHighlighting(caCodeArea.getText())); });/*from w w w.j a v a2 s .c o m*/ addContextMenu(this.caCodeArea); EventStream<Change<String>> textEvents = EventStreams.changesOf(caCodeArea.textProperty()); textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(3000)).subscribe(code -> { if (autoCompile) { compile(code.getNewValue()); } }); try { this.caCodeArea.replaceText(FileUtils.readFileToString(path.toFile())); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error reading file.", ex); } SplitPane editorPane = new SplitPane(caCodeArea, viewContainer); editorPane.setOrientation(Orientation.HORIZONTAL); BorderPane rootPane = new BorderPane(); toolBar = createToolBar(); rootPane.setTop(toolBar); rootPane.setCenter(editorPane); this.getTab().setContent(rootPane); }
From source file:be.makercafe.apps.makerbench.editors.JFXScadEditor.java
public JFXScadEditor(String tabText, Path path) { super(tabText); this.viewGroup = new Group(); this.editorContainer = new BorderPane(); this.viewContainer = new Pane(); this.caCodeArea = new CodeArea(""); this.caCodeArea.setEditable(true); this.caCodeArea.setParagraphGraphicFactory(LineNumberFactory.get(caCodeArea)); this.caCodeArea.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE); this.caCodeArea.getStylesheets().add(this.getClass().getResource("java-keywords.css").toExternalForm()); this.caCodeArea.richChanges().subscribe(change -> { caCodeArea.setStyleSpans(0, computeHighlighting(caCodeArea.getText())); });// w w w.j a v a2s. c o m addContextMenu(this.caCodeArea); EventStream<Change<String>> textEvents = EventStreams.changesOf(caCodeArea.textProperty()); textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(3000)).subscribe(code -> { if (autoCompile) { compile(code.getNewValue()); } }); if (path == null) { this.caCodeArea.replaceText("CSG cube = new Cube(2).toCSG()\n" + "CSG sphere = new Sphere(1.25).toCSG()\n" + "\n" + "cube.difference(sphere)"); } else { try { this.caCodeArea.replaceText(FileUtils.readFileToString(path.toFile())); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error reading file.", ex); } } //editorContainer.setCenter(this.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); SplitPane editorPane = new SplitPane(caCodeArea, viewContainer); editorPane.setOrientation(Orientation.HORIZONTAL); BorderPane rootPane = new BorderPane(); BorderPane pane = (BorderPane) this.getTab().getContent(); toolBar = createToolBar(); rootPane.setTop(toolBar); rootPane.setCenter(editorPane); this.getTab().setContent(rootPane); subScene.setOnScroll(new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { System.out .println(String.format("deltaX: %.3f deltaY: %.3f", event.getDeltaX(), event.getDeltaY())); double z = subSceneCamera.getTranslateZ(); double newZ = z + event.getDeltaY(); subSceneCamera.setTranslateZ(newZ); } }); }
From source file:org.ulyssis.ipp.reader.Reader.java
/** * Run the reader. Reader implements runnable, so that we can * do this in its own thread./*from w ww. j a v a2s . c o m*/ */ @Override public void run() { LOG.info("Spinning up reader!"); ReaderConfig.Type type = Config.getCurrentConfig().getReader(options.getId()).getType(); if (type == ReaderConfig.Type.LLRP) { initSpeedway(); if (!speedwayInitialized) { shutdownHook(); return; } } else if (type == ReaderConfig.Type.SIMULATOR) { initSimulator(); } Thread commandThread = new Thread(commandProcessor); commandThread.start(); statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTED_UP, String.format("Started up reader %s!", options.getId()))); try { while (!Thread.currentThread().isInterrupted()) { Duration maxUpdateInterval = Duration.ofMillis(Config.getCurrentConfig().getMaxUpdateInterval()); if (maxUpdateInterval.minus(Duration.between(lastUpdate, Instant.now())).isNegative()) { lastUpdate = Instant.now(); LOG.warn("No update received in {} seconds!", maxUpdateInterval.getSeconds()); statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NO_UPDATES, String.format("No update received in %s seconds!", maxUpdateInterval.getSeconds()))); } Thread.sleep(1000L); } } catch (InterruptedException e) { // We don't care about this exception } commandProcessor.stop(); commandThread.interrupt(); try { commandThread.join(); } catch (InterruptedException ignored) { } shutdownHook(); }
From source file:com.orange.cepheus.broker.Subscriptions.java
/** * @return the duration in String format * @throws SubscriptionException// w w w. j av a 2 s . c o m */ private Duration convertDuration(String duration) throws SubscriptionException { // Use java.xml.datatype functions as java.time do not handle durations with months and years... try { long longDuration = DatatypeFactory.newInstance().newDuration(duration).getTimeInMillis(new Date()); return Duration.ofMillis(longDuration); } catch (Exception e) { throw new SubscriptionException("bad duration: " + duration, e); } }
From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java
@Override protected Node createView0(OpenedFile file, String path) { CodeArea codeArea = new CodeArea(); if (controller instanceof KrakatauDisassemblerController) { ContextMenu contextMenu = new ContextMenu(); MenuItem save = new MenuItem("Assemble"); save.setOnAction(e -> {/*from w w w.ja v a2s. c o m*/ save(codeArea).whenComplete((res, err) -> { if (err != null) { if (err instanceof KrakatauException) { StringBuilder message = new StringBuilder(); message.append("stdout:\r\n").append(((KrakatauException) err).getStdout()) .append("\r\n\r\nstderr:\r\n").append(((KrakatauException) err).getStderr()); messageHandler.handleLongMessage(Message.ERROR_FAILED_TO_ASSEMBLE_KRAKATAU, message.toString()); } else { messageHandler.handleException(Message.ERROR_UNKNOWN_ERROR.format(), err); } } else { file.putContent(path, res); messageHandler.handleMessage(Message.GENERIC_ASSEMBLED.format()); } }); }); contextMenu.getItems().add(save); codeArea.setContextMenu(contextMenu); } codeArea.setStyle("-fx-font-size: 1em"); codeArea.getProperties().put("fontSize", 1); codeArea.setParagraphGraphicFactory(line -> { Node label = LineNumberFactory.get(codeArea, (digits) -> "%1$" + digits + "d").apply(line); label.styleProperty().bind(codeArea.styleProperty()); return label; }); codeArea.replaceText("Disassembling... this may take a while"); codeArea.getUndoManager().forgetHistory(); codeArea.richChanges().filter(ch -> !ch.getInserted().equals(ch.getRemoved())) // XXX .successionEnds(Duration.ofMillis(500)).supplyTask(() -> computeHighlightingAsync(codeArea)) .awaitLatest(codeArea.richChanges()).filterMap(t -> { if (t.isSuccess()) { return Optional.of(t.get()); } else { t.getFailure().printStackTrace(); return Optional.empty(); } }).subscribe(f -> applyHighlighting(codeArea, f)); codeArea.getStylesheets().add(getClass().getResource("/java-keywords.css").toExternalForm()); codeArea.addEventFilter(ScrollEvent.SCROLL, e -> { if (e.isShortcutDown()) { if (e.getDeltaY() > 0) { int size = (int) codeArea.getProperties().get("fontSize") + 1; codeArea.setStyle("-fx-font-size: " + size + "em"); codeArea.getProperties().put("fontSize", size); } else { int size = (int) codeArea.getProperties().get("fontSize") - 1; if (size > 0) { codeArea.setStyle("-fx-font-size: " + size + "em"); codeArea.getProperties().put("fontSize", size); } } e.consume(); } }); controller.disassemble(file, path, (success, text) -> { Platform.runLater(() -> { codeArea.replaceText(text); codeArea.getUndoManager().forgetHistory(); }); }); return new VirtualizedScrollPane<>(codeArea); }
From source file:be.makercafe.apps.makerbench.editors.GCodeEditor.java
public GCodeEditor(String tabText, Path path) { super(tabText); this.viewGroup = new Group(); this.editorContainer = new BorderPane(); this.viewContainer = new Pane(); this.caCodeArea = new CodeArea(""); this.caCodeArea.setEditable(true); this.caCodeArea.setParagraphGraphicFactory(LineNumberFactory.get(caCodeArea)); this.caCodeArea.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE); // this.caCodeArea.getStylesheets().add(this.getClass().getResource("java-keywords.css").toExternalForm()); // this.caCodeArea.richChanges().subscribe(change -> { // caCodeArea.setStyleSpans(0, // computeHighlighting(caCodeArea.getText())); // });/* w w w .j a v a 2 s .c om*/ addContextMenu(this.caCodeArea); EventStream<Change<String>> textEvents = EventStreams.changesOf(caCodeArea.textProperty()); textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(3000)).subscribe(code -> { if (autoCompile) { compile(code.getNewValue()); } }); if (path == null) { this.caCodeArea.replaceText("#empty"); } else { try { this.caCodeArea.replaceText(FileUtils.readFileToString(path.toFile())); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error reading file.", ex); } } // editorContainer.setCenter(this.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); SplitPane editorPane = new SplitPane(caCodeArea, viewContainer); editorPane.setOrientation(Orientation.HORIZONTAL); BorderPane rootPane = new BorderPane(); BorderPane pane = (BorderPane) this.getTab().getContent(); toolBar = createToolBar(); rootPane.setTop(toolBar); rootPane.setCenter(editorPane); this.getTab().setContent(rootPane); subScene.setOnScroll(new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { System.out .println(String.format("deltaX: %.3f deltaY: %.3f", event.getDeltaX(), event.getDeltaY())); double z = subSceneCamera.getTranslateZ(); double newZ = z + event.getDeltaY(); subSceneCamera.setTranslateZ(newZ); } }); }
From source file:com.orange.cepheus.broker.LocalRegistrations.java
/** * @return the duration of the registration * @throws RegistrationException/*from w ww. j av a 2s . c o m*/ */ private Duration registrationDuration(RegisterContext registerContext) throws RegistrationException { // Use java.xml.datatype functions as java.time do not handle durations with months and years... try { long duration = DatatypeFactory.newInstance().newDuration(registerContext.getDuration()) .getTimeInMillis(new Date()); return Duration.ofMillis(duration); } catch (Exception e) { throw new RegistrationException("bad duration: " + registerContext.getDuration(), e); } }
From source file:com.netflix.genie.common.dto.JobTest.java
/** * Test to make sure can build a valid Job with optional parameters. */// w w w . ja v a 2 s .c o m @Test @SuppressWarnings("deprecation") public void canBuildJobWithOptionalsDeprecated() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); final String archiveLocation = UUID.randomUUID().toString(); builder.withArchiveLocation(archiveLocation); final String clusterName = UUID.randomUUID().toString(); builder.withClusterName(clusterName); final String commandName = UUID.randomUUID().toString(); builder.withCommandName(commandName); final Instant finished = Instant.now(); builder.withFinished(finished); final Instant started = Instant.now(); builder.withStarted(started); builder.withStatus(JobStatus.SUCCEEDED); final String statusMsg = UUID.randomUUID().toString(); builder.withStatusMsg(statusMsg); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final String grouping = UUID.randomUUID().toString(); builder.withGrouping(grouping); final String groupingInstance = UUID.randomUUID().toString(); builder.withGroupingInstance(groupingInstance); final Job job = builder.build(); Assert.assertThat(job.getName(), Matchers.is(NAME)); Assert.assertThat(job.getUser(), Matchers.is(USER)); Assert.assertThat(job.getVersion(), Matchers.is(VERSION)); Assert.assertThat(job.getCommandArgs().orElseThrow(IllegalArgumentException::new), Matchers.is(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE))); Assert.assertThat(job.getArchiveLocation().orElseThrow(IllegalArgumentException::new), Matchers.is(archiveLocation)); Assert.assertThat(job.getClusterName().orElseThrow(IllegalArgumentException::new), Matchers.is(clusterName)); Assert.assertThat(job.getCommandName().orElseThrow(IllegalArgumentException::new), Matchers.is(commandName)); Assert.assertThat(job.getFinished().orElseThrow(IllegalArgumentException::new), Matchers.is(finished)); Assert.assertThat(job.getStarted().orElseThrow(IllegalArgumentException::new), Matchers.is(started)); Assert.assertThat(job.getStatus(), Matchers.is(JobStatus.SUCCEEDED)); Assert.assertThat(job.getStatusMsg().orElseThrow(IllegalArgumentException::new), Matchers.is(statusMsg)); Assert.assertThat(job.getCreated().orElseThrow(IllegalArgumentException::new), Matchers.is(created)); Assert.assertThat(job.getDescription().orElseThrow(IllegalArgumentException::new), Matchers.is(description)); Assert.assertThat(job.getId().orElseThrow(IllegalArgumentException::new), Matchers.is(id)); Assert.assertThat(job.getTags(), Matchers.is(tags)); Assert.assertThat(job.getUpdated().orElseThrow(IllegalArgumentException::new), Matchers.is(updated)); Assert.assertThat(job.getRuntime(), Matchers.is(Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli()))); Assert.assertThat(job.getGrouping().orElseThrow(IllegalArgumentException::new), Matchers.is(grouping)); Assert.assertThat(job.getGroupingInstance().orElseThrow(IllegalArgumentException::new), Matchers.is(groupingInstance)); }
From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandlerTest.java
@Test(timeout = 10000) public void testPostponeEvent() throws InterruptedException, ExecutionException { AtomicInteger postponeS1e1Count = new AtomicInteger(); AtomicInteger postponeS1e2Count = new AtomicInteger(); AtomicBoolean allowCompletion = new AtomicBoolean(false); SerializedRequestHandler<TestEvent> requestHandler = new SerializedRequestHandler<TestEvent>( executorService()) {/*from w w w.ja va 2 s.co m*/ @Override public CompletableFuture<Void> processEvent(TestEvent event) { if (!event.future.isDone()) { return Futures.failedFuture(new TestPostponeException()); } return event.getFuture(); } @Override public boolean toPostpone(TestEvent event, long pickupTime, Throwable exception) { boolean retval = true; if (allowCompletion.get()) { if (event.number == 1) { postponeS1e1Count.incrementAndGet(); retval = exception instanceof TestPostponeException && postponeS1e1Count.get() < 2; } if (event.number == 2) { postponeS1e2Count.incrementAndGet(); retval = exception instanceof TestPostponeException && (System.currentTimeMillis() - pickupTime < Duration.ofMillis(100).toMillis()); } } return retval; } }; List<Pair<TestEvent, CompletableFuture<Void>>> stream1Queue = requestHandler .getEventQueueForKey(getKeyForStream("scope", "stream1")); assertNull(stream1Queue); // post 3 work for stream1 TestEvent s1e1 = new TestEvent("scope", "stream1", 1); CompletableFuture<Void> s1p1 = requestHandler.process(s1e1); TestEvent s1e2 = new TestEvent("scope", "stream1", 2); CompletableFuture<Void> s1p2 = requestHandler.process(s1e2); TestEvent s1e3 = new TestEvent("scope", "stream1", 3); CompletableFuture<Void> s1p3 = requestHandler.process(s1e3); // post events for some more arbitrary streams in background AtomicBoolean stop = new AtomicBoolean(false); runBackgroundStreamProcessing("stream2", requestHandler, stop); runBackgroundStreamProcessing("stream3", requestHandler, stop); runBackgroundStreamProcessing("stream4", requestHandler, stop); s1e3.complete(); // verify that s1p3 completes. assertTrue(Futures.await(s1p3)); // verify that s1e1 and s1e2 are still not complete. assertTrue(!s1e1.getFuture().isDone()); assertTrue(!s1p1.isDone()); assertTrue(!s1e2.getFuture().isDone()); assertTrue(!s1p2.isDone()); // Allow completion allowCompletion.set(true); assertFalse(Futures.await(s1p1)); assertFalse(Futures.await(s1p2)); AssertExtensions.assertThrows("", s1p1::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException); AssertExtensions.assertThrows("", s1p2::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException); assertTrue(postponeS1e1Count.get() == 2); assertTrue(postponeS1e2Count.get() > 0); stop.set(true); }