List of usage examples for java.time Duration ofMillis
public static Duration ofMillis(long millis)
From source file:com.neuronrobotics.bowlerstudio.MainController.java
/** * Initializes the controller class.// w ww .j a v a2 s.c o m * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { ScriptingEngine.setLoginManager(new IGitHubLoginManager() { @Override public String[] prompt(String username) { if (!loginWindowOpen && controller != null) controller.reset(); loginWindowOpen = true; System.err.println("Calling login from BowlerStudio"); // new RuntimeException().printStackTrace(); FXMLLoader fxmlLoader = BowlerStudioResourceFactory.getGithubLogin(); Parent root = fxmlLoader.getRoot(); if (controller == null) { controller = fxmlLoader.getController(); Platform.runLater(() -> { controller.reset(); controller.getUsername().setText(username); Stage stage = new Stage(); stage.setTitle("GitHub Login"); stage.initModality(Modality.APPLICATION_MODAL); controller.setStage(stage, root); stage.centerOnScreen(); stage.show(); }); } // setContent(root); while (!controller.isDone()) { ThreadUtil.wait(100); } String[] creds = controller.getCreds(); loginWindowOpen = false; return creds; } }); jfx3dmanager = new BowlerStudio3dEngine(); setApplication(new BowlerStudioController(jfx3dmanager, this)); Platform.runLater(() -> { editorContainer.getChildren().add(getApplication()); AnchorPane.setTopAnchor(getApplication(), 0.0); AnchorPane.setRightAnchor(getApplication(), 0.0); AnchorPane.setLeftAnchor(getApplication(), 0.0); AnchorPane.setBottomAnchor(getApplication(), 0.0); subScene = jfx3dmanager.getSubScene(); subScene.setFocusTraversable(false); subScene.setOnMouseEntered(mouseEvent -> { // System.err.println("3d window requesting focus"); Scene topScene = BowlerStudio.getScene(); normalKeyPessHandle = topScene.getOnKeyPressed(); jfx3dmanager.handleKeyboard(topScene); }); subScene.setOnMouseExited(mouseEvent -> { // System.err.println("3d window dropping focus"); Scene topScene = BowlerStudio.getScene(); topScene.setOnKeyPressed(normalKeyPessHandle); }); subScene.widthProperty().bind(viewContainer.widthProperty()); subScene.heightProperty().bind(viewContainer.heightProperty()); }); Platform.runLater(() -> { jfx3dControls.getChildren().add(jfx3dmanager.getControlsBox()); viewContainer.getChildren().add(subScene); }); System.out.println("Welcome to BowlerStudio!"); new Thread() { public void run() { setName("Load Haar Thread"); try { HaarFactory.getStream(null); } catch (Exception ex) { } } }.start(); // getAddDefaultRightArm().setOnAction(event -> { // // application.onAddDefaultRightArm(event); // }); // getAddVRCamera().setOnAction(event -> { // if(AddVRCamera.isSelected()) // application.onAddVRCamera(event); // }); FxTimer.runLater(Duration.ofMillis(100), () -> { if (ScriptingEngine.getLoginID() != null) { setToLoggedIn(ScriptingEngine.getLoginID()); } else { setToLoggedOut(); } }); ScriptingEngine.addIGithubLoginListener(new IGithubLoginListener() { @Override public void onLogout(String oldUsername) { setToLoggedOut(); } @Override public void onLogin(String newUsername) { setToLoggedIn(newUsername); } }); cmdLine = new CommandLineWidget(); Platform.runLater(() -> { // logView.resize(250, 300); // after connection manager set up, add scripting widget logViewRef = new TextArea(); logViewRef.prefWidthProperty().bind(logView.widthProperty().divide(2)); logViewRef.prefHeightProperty().bind(logView.heightProperty().subtract(40)); VBox box = new VBox(); box.getChildren().add(logViewRef); box.getChildren().add(cmdLine); VBox.setVgrow(logViewRef, Priority.ALWAYS); box.prefWidthProperty().bind(logView.widthProperty().subtract(10)); logView.getChildren().addAll(box); }); }
From source file:org.ng200.openolympus.services.TestingService.java
private void checkVerdict(final Verdict verdict, final SolutionJudge judge, final List<Path> testFiles, final BigDecimal maximumScore, final Properties properties) throws ExecutionException { if (this.dataProvider == null) { throw new IllegalStateException("Shared data provider is null!"); }/* w ww . j av a2s . c o m*/ final Lock lock = verdict.getSolution().getTask().readLock(); lock.lock(); try { TestingService.logger.info("Scheduling verdict {} for testing.", verdict.getId()); final JPPFJob job = new JPPFJob(); job.setDataProvider(this.dataProvider); job.setName("Check verdict " + verdict.getId()); final int priority = (int) ((verdict.isViewableWhenContestRunning() ? (Integer.MAX_VALUE / 2) : 0) - verdict.getId()); job.getSLA().setMaxNodes(1); job.getSLA().setPriority(priority); job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(60000L)); job.getSLA().setMaxDispatchExpirations(3); TaskContainer taskContainer = taskContainerCache .getTaskContainerForTask(verdict.getSolution().getTask()); Thread.currentThread().setContextClassLoader( new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]), Thread.currentThread().getContextClassLoader())); job.add(new JacksonSerializationDelegatingTask<>( new VerdictCheckingTask(judge, testFiles, maximumScore, properties), taskContainer.getClassLoaderURLs())); job.setBlocking(true); jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid()); this.jppfClient.submitJob(job); @SuppressWarnings("unchecked") final org.jppf.node.protocol.Task<String> task = (org.jppf.node.protocol.Task<String>) job .awaitResults().get(0); if (task.getThrowable() != null) { throw task.getThrowable(); } ObjectMapper objectMapper = JacksonSerializationFactory.createObjectMapper(); final JsonTaskExecutionResult<Pair<SolutionJudge, SolutionResult>> checkingResult = ((JacksonSerializationDelegatingTask<Pair<SolutionJudge, SolutionResult>, VerdictCheckingTask>) job .awaitResults().get(0)).getResultOrThrowable(); if (checkingResult.getError() != null) { throw checkingResult.getError(); } final SolutionResult result = checkingResult.getResult().getSecond(); verdict.setScore(result.getScore()); verdict.setMemoryPeak(result.getMemoryPeak()); verdict.setCpuTime(Duration.ofMillis(result.getCpuTime())); verdict.setRealTime(Duration.ofMillis(result.getRealTime())); verdict.setStatus(result.getResult()); switch (result.getResult()) { case OK: case TIME_LIMIT: case MEMORY_LIMIT: case OUTPUT_LIMIT: case PRESENTATION_ERROR: case WRONG_ANSWER: case RUNTIME_ERROR: break; case INTERNAL_ERROR: result.getErrorMessages() .forEach((stage, message) -> this.internalErrors.put(this.internalErrorCounter++, new Pair<String, String>(verdict.getSolution().getTask().getName(), message))); break; case SECURITY_VIOLATION: verdict.setUnauthorisedSyscall(result.getUnauthorisedSyscall()); break; case COMPILE_ERROR: final String message = result.getErrorMessages().values().stream() .collect(Collectors.joining("\n")); verdict.setAdditionalInformation( HtmlUtils.htmlEscape(message.substring(0, Math.min(128, message.length())))); break; case WAITING: throw new IllegalStateException("Judge returned result \"waiting\"."); } } catch (final Throwable throwable) { verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR); throw new RuntimeException("Couldn't run solution: ", throwable); } finally { lock.unlock(); verdict.setTested(true); if (verdict.getStatus() == SolutionResult.Result.WAITING) { verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR); TestingService.logger.error( "Judge for task {} did not set the result status to an acceptable value: got WAITING instead.", verdict.getSolution().getTask().getId()); } this.solutionService.saveVerdict(verdict); } }
From source file:de.codecentric.boot.admin.server.web.client.InstanceWebClientTest.java
@Test public void should_error_on_timeout() { InstanceWebClient fastTimeoutClient = new InstanceWebClient(headersProvider, Duration.ofMillis(10), Duration.ofMillis(10)); wireMock.stubFor(get("/foo").willReturn(ok().withFixedDelay(100))); Mono<ClientResponse> exchange = fastTimeoutClient.instance(Mono.empty()).get().uri(wireMock.url("/foo")) .exchange();/*from w ww .ja v a 2s . com*/ StepVerifier.create(exchange).verifyError(ReadTimeoutException.class); }
From source file:com.neuronrobotics.bowlerstudio.MainController.java
private void setToLoggedIn(final String name) { // new Exception().printStackTrace(); FxTimer.runLater(Duration.ofMillis(100), () -> { logoutGithub.disableProperty().set(false); logoutGithub.setText("Log out " + name); new Thread() { public void run() { GitHub github = ScriptingEngine.getGithub(); while (github == null) { github = ScriptingEngine.getGithub(); ThreadUtil.wait(20); }/*ww w . java 2 s . c o m*/ try { GHMyself myself = github.getMyself(); PagedIterable<GHGist> gists = myself.listGists(); Platform.runLater(() -> { myGists.getItems().clear(); }); ThreadUtil.wait(20); for (GHGist gist : gists) { String desc = gist.getDescription(); if (desc == null || desc.length() == 0) { desc = gist.getFiles().keySet().toArray()[0].toString(); } Menu tmpGist = new Menu(desc); MenuItem loadWebGist = new MenuItem("Show Web Gist..."); loadWebGist.setOnAction(event -> { String webURL = gist.getHtmlUrl(); try { BowlerStudio.openUrlInNewTab(new URL(webURL)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); MenuItem addFile = new MenuItem("Add file to Gist..."); addFile.setOnAction(event -> { new Thread() { public void run() { } }.start(); }); Platform.runLater(() -> { tmpGist.getItems().addAll(addFile, loadWebGist); }); EventHandler<Event> loadFiles = new EventHandler<Event>() { @Override public void handle(Event ev) { // for(ScriptingEngine.) new Thread() { public void run() { System.out.println("Loading files"); ArrayList<String> listofFiles = ScriptingEngine .filesInGit(gist.getGitPushUrl(), "master", null); for (String s : listofFiles) { MenuItem tmp = new MenuItem(s); tmp.setOnAction(event -> { new Thread() { public void run() { try { File fileSelected = ScriptingEngine .fileFromGit(gist.getGitPushUrl(), s); BowlerStudio.createFileTab(fileSelected); } catch (Exception e) { // TODO // Auto-generated // catch block e.printStackTrace(); } } }.start(); }); Platform.runLater(() -> { tmpGist.getItems().add(tmp); tmpGist.setOnShowing(null); }); } Platform.runLater(() -> { tmpGist.hide(); Platform.runLater(() -> { tmpGist.show(); }); }); } }.start(); } }; tmpGist.setOnShowing(loadFiles); Platform.runLater(() -> { myGists.getItems().add(tmpGist); }); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); }); }
From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java
private void fetchUpdatesIfNeeded() { if (!fetchStateTimer.hasRemaining()) { sync.fetchUpdates();/*from w w w . j a va2 s.com*/ long groupRefreshTimeMillis = sync.getState().getConfig().getGroupRefreshTimeMillis(); fetchStateTimer.reset(Duration.ofMillis(groupRefreshTimeMillis)); } }
From source file:com.netflix.genie.common.dto.JobTest.java
/** * Test to make sure can build a valid Job with optional parameters. *///ww w. j a v a2 s . co m @Test public void canBuildJobWithOptionals() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs(COMMAND_ARGS); 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:org.ulyssis.ipp.reader.Reader.java
/** * Check whether this tag code has been seen at least config.getMinUpdateInterval() * ago. If not, the update should be ignored. *///from w w w . j a v a2 s .c o m private boolean acceptUpdate(Instant now, TagId tag) { lastUpdate = now; boolean result = !lastUpdateForTag.containsKey(tag) || Duration.ofMillis(Config.getCurrentConfig().getMinUpdateInterval()) .minus(Duration.between(lastUpdateForTag.get(tag), now)).isNegative(); if (result) { lastUpdateForTag.put(tag, now); } return result; }
From source file:com.joyent.manta.benchmark.Benchmark.java
/** * Measures the total time to get an object from Manta. * * @param path path of the object to measure * @return two durations - full time in the JVM, server time processing * @throws IOException thrown when we can't access Manta over the network */// www.ja v a 2 s . co m private static Duration[] measureGet(final String path) throws IOException { final Instant start = Instant.now(); final String serverLatencyString; MantaObjectInputStream is = client.getAsInputStream(path); try { copyToTheEther(is); serverLatencyString = is.getHeader("x-response-time").toString(); } finally { IOUtils.closeQuietly(is); } final Instant stop = Instant.now(); Duration serverLatency = Duration.ofMillis(Long.parseLong(serverLatencyString)); Duration fullLatency = Duration.between(start, stop); return new Duration[] { fullLatency, serverLatency }; }
From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java
@Test public void testBatchesRequests() throws InterruptedException { _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> { // Annotations Assert.assertEquals(0, r.getAnnotationsCount()); // Dimensions Assert.assertEquals(0, r.getDimensionsCount()); // Samples assertSample(r.getTimersList(), "timer", 7d); assertSample(r.getCountersList(), "counter", 8d); assertSample(r.getGaugesList(), "gauge", 9d); })).willReturn(WireMock.aResponse().withStatus(200))); final AtomicBoolean assertionResult = new AtomicBoolean(false); final Semaphore semaphore = new Semaphore(0); final Sink sink = new ApacheHttpSink.Builder() .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).setMaxBatchSize(10) .setParallelism(1).setEmptyQueueInterval(Duration.ofMillis(1000)) .setEventHandler(new AttemptCompletedAssertionHandler(assertionResult, 3, 210, true, new CompletionHandler(semaphore))) .build();//w ww. ja va2 s . co m final TsdEvent event = new TsdEvent(Collections.emptyMap(), createQuantityMap("timer", TsdQuantity.newInstance(7d, null)), createQuantityMap("counter", TsdQuantity.newInstance(8d, null)), createQuantityMap("gauge", TsdQuantity.newInstance(9d, null))); for (int x = 0; x < 3; x++) { sink.record(event); } semaphore.acquire(); // Ensure expected handler was invoked Assert.assertTrue(assertionResult.get()); // Request matcher final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH)) .withHeader("Content-Type", WireMock.equalTo("application/octet-stream")); // Assert that data was sent _wireMockRule.verify(1, requestPattern); Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty()); }
From source file:com.joyent.manta.benchmark.Benchmark.java
/** * Measures the total time to put an object to Manta. * * @param length number of bytes to write * @return two durations - full time in the JVM, server time processing * @throws IOException thrown when we can't access Manta over the network *//* w w w.j a v a 2 s . c o m*/ private static Duration[] measurePut(final long length) throws IOException { final String path = String.format("%s/%s", testDirectory, UUID.randomUUID()); final long start = System.nanoTime(); final String serverLatencyString; try (RandomInputStream rand = new RandomInputStream(length)) { MantaHttpHeaders headers = new MantaHttpHeaders(); headers.setDurabilityLevel(2); serverLatencyString = client.put(path, rand, length, headers, null).getHeader("x-response-time") .toString(); } final long stop = System.nanoTime(); Duration serverLatency = Duration.ofMillis(Long.parseLong(serverLatencyString)); Duration fullLatency = Duration.ofNanos(stop - start); return new Duration[] { fullLatency, serverLatency }; }