List of usage examples for java.time Instant now
public static Instant now()
From source file:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java
@Test public void testDeleteAsync() throws IOException, InterruptedException { final Task responseTask = new Task(); responseTask.setId("12345"); responseTask.setState("QUEUED"); responseTask.setQueuedTime(Date.from(Instant.now())); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(responseTask); setupMocks(serializedTask, HttpStatus.SC_CREATED); ClusterApi clusterApi = new ClusterRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); clusterApi.deleteAsync("foo", new FutureCallback<Task>() { @Override/*from w ww. j av a2 s.c o m*/ public void onSuccess(Task result) { assertEquals(result, responseTask); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:com.blackducksoftware.integration.hub.detect.workflow.project.ProjectNameVersionDecider.java
public NameVersion decideProjectNameVersion(String preferredDetectTools, final List<DetectToolProjectInfo> detectToolProjectInfo) throws DetectUserFriendlyException { Optional<String> decidedProjectName = Optional.empty(); Optional<String> decidedProjectVersion = Optional.empty(); if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectName)) { decidedProjectName = Optional.of(projectVersionOptions.overrideProjectName); }// w ww . ja va2 s . c om if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectVersionName)) { decidedProjectVersion = Optional.of(projectVersionOptions.overrideProjectVersionName); } Optional<DetectToolProjectInfo> chosenTool = decideToolProjectInfo(preferredDetectTools, detectToolProjectInfo); if (chosenTool.isPresent()) { if (!decidedProjectName.isPresent()) { String suggestedName = chosenTool.get().getSuggestedNameVersion().getName(); if (StringUtils.isNotBlank(suggestedName)) { decidedProjectName = Optional.of(suggestedName); } } if (!decidedProjectVersion.isPresent()) { String suggestedVersion = chosenTool.get().getSuggestedNameVersion().getVersion(); if (StringUtils.isNotBlank(suggestedVersion)) { decidedProjectVersion = Optional.of(suggestedVersion); } } } if (!decidedProjectName.isPresent()) { logger.info("A project name could not be decided. Using the name of the source path."); decidedProjectName = Optional.of(projectVersionOptions.sourcePathName); } if (!decidedProjectVersion.isPresent()) { if ("timestamp".equals(projectVersionOptions.defaultProjectVersionScheme)) { logger.info("A project version name could not be decided. Using the current timestamp."); final String timeformat = projectVersionOptions.defaultProjectVersionFormat; final String timeString = DateTimeFormatter.ofPattern(timeformat).withZone(ZoneOffset.UTC) .format(Instant.now().atZone(ZoneOffset.UTC)); decidedProjectVersion = Optional.of(timeString); } else { logger.info("A project version name could not be decided. Using the default version text."); decidedProjectVersion = Optional.of(projectVersionOptions.defaultProjectVersionText); } } return new NameVersion(decidedProjectName.get(), decidedProjectVersion.get()); }
From source file:com.orange.cepheus.broker.persistence.SubscriptionsRepositoryTest.java
@Test public void updateSubscriptionTest() throws URISyntaxException, SubscriptionPersistenceException { SubscribeContext subscribeContext = createSubscribeContextTemperature(); Subscription subscription = new Subscription("12345", Instant.now().plus(1, ChronoUnit.DAYS), subscribeContext);//from w w w . j a v a 2 s.co m subscriptionsRepository.saveSubscription(subscription); Map<String, Subscription> subscriptions = subscriptionsRepository.getAllSubscriptions(); Assert.assertEquals(1, subscriptions.size()); Assert.assertEquals("P1M", subscriptions.get("12345").getSubscribeContext().getDuration()); subscribeContext.setDuration("PT1D"); subscription.setExpirationDate(Instant.now().plus(1, ChronoUnit.DAYS)); subscriptionsRepository.updateSubscription(subscription); subscriptions = subscriptionsRepository.getAllSubscriptions(); Assert.assertEquals(1, subscriptions.size()); Assert.assertEquals("PT1D", subscriptions.get("12345").getSubscribeContext().getDuration()); Assert.assertEquals(subscription.getExpirationDate(), subscriptions.get("12345").getExpirationDate()); }
From source file:org.jimsey.project.turbine.spring.controller.IndicatorControllerTest.java
@Test public void testGetAllStocksGreaterThanDate() throws Exception { Mockito.when(elasticsearch.findIndicatorsByMarketAndSymbolAndNameAndDateGreaterThan(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Long.class))).thenReturn(indicators); String expected = json.writeValueAsString(new Object() { @JsonProperty("indicators") List<IndicatorJson> indicatorz = indicators; });/*from ww w . j a v a2s . c om*/ long date = Instant.now().minus(1, ChronoUnit.MINUTES).toEpochMilli(); String restUri = String.format("%s/%s/%s/%s/%s", TurbineCondenserConstants.REST_ROOT_INDICATORS, "market", "symbol", "testName", date); mvc.perform(MockMvcRequestBuilders.get(restUri).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(content().string(equalTo(expected))); }
From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.java
public void canUploadSmallMultipartString() throws IOException { String[] parts = new String[] { "Hello ", "world ", "Joyent", "!" }; StringBuilder combined = new StringBuilder(); for (String p : parts) { combined.append(p);/*from w w w. j a va 2 s. co m*/ } final String name = uploadName("can-upload-small-multipart-string"); final String path = testPathPrefix + name; final EncryptedMultipartUpload<JobsMultipartUpload> upload = multipart.initiateUpload(path); final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; int partNumber = i + 1; MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part); uploadedParts.add(uploaded); } multipart.validateThatThereAreSequentialPartNumbers(upload); Instant start = Instant.now(); multipart.complete(upload, uploadedParts); multipart.getWrapped().waitForCompletion(upload, (Function<UUID, Void>) uuid -> { fail("Completion operation didn't succeed within timeout"); return null; }); Instant end = Instant.now(); MantaMultipartStatus status = multipart.getStatus(upload); assertEquals(status, MantaMultipartStatus.COMPLETED); assertEquals(mantaClient.getAsString(path), combined.toString(), "Manta combined string doesn't match expectation: " + multipart.getWrapped().findJob(upload)); Duration totalCompletionTime = Duration.between(start, end); LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000); }
From source file:io.gravitee.management.service.impl.InstanceServiceImpl.java
@Override public InstanceEntity findById(String eventId) { EventEntity event = eventService.findById(eventId); Instant nowMinusXMinutes = Instant.now().minus(5, ChronoUnit.MINUTES); Map<String, String> props = event.getProperties(); InstanceEntity instance = new InstanceEntity(props.get("id")); instance.setLastHeartbeatAt(new Date(Long.parseLong(props.get("last_heartbeat_at")))); instance.setStartedAt(new Date(Long.parseLong(props.get("started_at")))); if (event.getPayload() != null) { try {//from w ww.j av a2 s.c o m InstanceInfo info = objectMapper.readValue(event.getPayload(), InstanceInfo.class); instance.setHostname(info.getHostname()); instance.setIp(info.getIp()); instance.setVersion(info.getVersion()); instance.setTags(info.getTags()); instance.setSystemProperties(info.getSystemProperties()); instance.setPlugins(info.getPlugins()); } catch (IOException ioe) { LOGGER.error("Unexpected error while getting instance informations from event payload", ioe); } } if (event.getType() == EventType.GATEWAY_STARTED) { instance.setState(InstanceState.STARTED); // If last heartbeat timestamp is < now - 5m, set as unknown state Instant lastHeartbeat = Instant.ofEpochMilli(instance.getLastHeartbeatAt().getTime()); if (lastHeartbeat.isBefore(nowMinusXMinutes)) { instance.setState(InstanceState.UNKNOWN); } } else { instance.setState(InstanceState.STOPPED); instance.setStoppedAt(new Date(Long.parseLong(props.get("stopped_at")))); } return instance; }
From source file:com.orange.cepheus.broker.Subscriptions.java
/** * find subscriptionID matching the updateContext. * @param searchEntityId the entity id to search * @param searchAttributes the attributes to search * @return list of matching subscription *///w ww.j a v a 2s .com public Iterator<Subscription> findSubscriptions(EntityId searchEntityId, Set<String> searchAttributes) { // Filter out expired subscriptions Predicate<Subscription> filterExpired = subscription -> subscription.getExpirationDate() .isAfter(Instant.now()); // Filter only matching entity ids Predicate<EntityId> filterEntityId = patterns.getFilterEntityId(searchEntityId); // Only filter by attributes if search is looking for them final boolean noAttributes = searchAttributes == null || searchAttributes.size() == 0; // Filter each subscription (remove expired) and return its providing application // if at least one of its listed entities matches the searched context element // and if all searched attributes are defined in the subscription (if any) return subscriptions.values().stream().filter(filterExpired) .filter(subscription -> subscription.getSubscribeContext().getEntityIdList().stream() .filter(filterEntityId).findFirst().isPresent() && (noAttributes || !Collections .disjoint(subscription.getSubscribeContext().getAttributeList(), searchAttributes))) .iterator(); }
From source file:info.archinnov.achilles.it.TestEntityWithComplexTypes.java
@Test public void should_insert() throws Exception { //Given// w ww.j a v a 2 s. c o m final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final TestUDT udt = new TestUDT(); udt.setList(asList("list")); udt.setName("name"); udt.setMap(ImmutableMap.of(1, "1")); UUID timeuuid = UUIDs.timeBased(); java.time.Instant jdkInstant = Instant.now(); java.time.LocalDate jdkLocalDate = java.time.LocalDate.now(); java.time.LocalTime jdkLocalTime = java.time.LocalTime.now(); java.time.ZonedDateTime jdkZonedDateTime = java.time.ZonedDateTime.now(); final EntityWithComplexTypes entity = new EntityWithComplexTypes(); entity.setId(id); entity.setCodecOnClass(new ClassAnnotatedByCodec()); entity.setComplexNestingMap( ImmutableMap.of(udt, ImmutableMap.of(1, Tuple3.of(1, 2, ConsistencyLevel.ALL)))); entity.setConsistencyLevel(ConsistencyLevel.EACH_QUORUM); entity.setInteger(123); entity.setJsonMap(ImmutableMap.of(1, asList(1, 2, 3))); entity.setListNesting(asList(ImmutableMap.of(1, "one"))); entity.setListUdt(asList(udt)); entity.setMapUdt(ImmutableMap.of(1, udt)); entity.setMapWithNestedJson(ImmutableMap.of(1, asList(ImmutableMap.of(1, "one")))); entity.setObjectBoolean(new Boolean(true)); entity.setObjectByte(new Byte("5")); entity.setObjectByteArray(new Byte[] { 7 }); entity.setOkSet(Sets.newHashSet(ConsistencyLevel.LOCAL_ONE, ConsistencyLevel.LOCAL_QUORUM)); entity.setPrimitiveBoolean(true); entity.setPrimitiveByte((byte) 3); entity.setPrimitiveByteArray(new byte[] { 4 }); entity.setSimpleUdt(udt); entity.setTime(buildDate()); entity.setTimeuuid(timeuuid); entity.setTuple1(Tuple1.of(ConsistencyLevel.THREE)); entity.setTuple2(Tuple2.of(ConsistencyLevel.TWO, 2)); entity.setTupleNesting(Tuple2.of(1, asList("1"))); entity.setValue("val"); entity.setWriteTime(1000L); entity.setWriteTimeWithCodec("2000"); entity.setIntWrapper(new IntWrapper(123)); entity.setProtocolVersion(ProtocolVersion.V4); entity.setEncoding(Enumerated.Encoding.ORDINAL); entity.setDoubleArray(new double[] { 1.0, 2.0 }); entity.setFloatArray(new float[] { 3.0f, 4.0f }); entity.setIntArray(new int[] { 5, 6 }); entity.setLongArray(new long[] { 7L, 8L }); entity.setListOfLongArray(Arrays.asList(new long[] { 9L, 10L })); entity.setJdkInstant(jdkInstant); entity.setJdkLocalDate(jdkLocalDate); entity.setJdkLocalTime(jdkLocalTime); entity.setJdkZonedDateTime(jdkZonedDateTime); entity.setProtocolVersionAsOrdinal(ProtocolVersion.V2); entity.setOptionalString(Optional.empty()); entity.setOptionalProtocolVersion(Optional.of(ProtocolVersion.V3)); entity.setOptionalEncodingAsOrdinal(Optional.of(ProtocolVersion.V2)); entity.setListOfOptional(Arrays.asList(Optional.of("1"), Optional.of("2"))); //When manager.crud().insert(entity).execute(); //Then final Metadata metadata = session.getCluster().getMetadata(); final TupleValue tupleValue = metadata.newTupleType(text(), cint(), cint()).newValue("1", 2, 5); final TupleValue nestedTuple2Value = metadata.newTupleType(cint(), list(text())).newValue(1, asList("1")); final Row actual = session.execute("SELECT * FROM entity_complex_types WHERE id = " + id).one(); assertThat(actual).isNotNull(); assertThat(actual.getString("codec_on_class")).isEqualTo("ClassAnnotatedByCodec{}"); final Map<String, Map<Integer, TupleValue>> complexMapNesting = actual.getMap("complex_nesting_map", new TypeToken<String>() { }, new TypeToken<Map<Integer, TupleValue>>() { }); assertThat(complexMapNesting).containsEntry("{\"list\":[\"list\"],\"map\":{\"1\":\"1\"},\"name\":\"name\"}", ImmutableMap.of(1, tupleValue)); assertThat(actual.getString("consistencylevel")).isEqualTo("EACH_QUORUM"); assertThat(actual.getString("integer")).isEqualTo("123"); assertThat(actual.getString("json_map")).isEqualTo("{\"1\":[1,2,3]}"); assertThat(actual.getList("list_nesting", new TypeToken<Map<Integer, String>>() { })).containsExactly(ImmutableMap.of(1, "one")); final UDTValue foundUDT = actual.getUDTValue("simple_udt"); assertThat(foundUDT.getString("name")).isEqualTo("name"); assertThat(foundUDT.getList("list", String.class)).containsExactly("list"); assertThat(foundUDT.getMap("map", String.class, String.class)).containsEntry("1", "1"); assertThat(actual.getList("list_udt", UDTValue.class)).containsExactly(foundUDT); assertThat(actual.getMap("map_udt", Integer.class, UDTValue.class)).containsEntry(1, foundUDT); assertThat(actual.getMap("map_with_nested_json", Integer.class, String.class)).containsEntry(1, "[{\"1\":\"one\"}]"); assertThat(actual.getBool("object_bool")).isTrue(); assertThat(actual.getByte("object_byte")).isEqualTo((byte) 5); assertThat(actual.getBytes("object_byte_array")).isEqualTo(ByteBuffer.wrap(new byte[] { (byte) 7 })); assertThat(actual.getSet("ok_set", Integer.class)).containsExactly(6, 10); assertThat(actual.getBool("primitive_bool")).isTrue(); assertThat(actual.getByte("primitive_byte")).isEqualTo((byte) 3); assertThat(actual.getBytes("primitive_byte_array")).isEqualTo(ByteBuffer.wrap(new byte[] { (byte) 4 })); assertThat(actual.getString("time")).isEqualTo(buildDate().getTime() + ""); assertThat(actual.getUUID("timeuuid")).isEqualTo(timeuuid); assertThat(actual.getTupleValue("tuple1").get(0, String.class)).isEqualTo("\"THREE\""); assertThat(actual.getTupleValue("tuple2").get(0, String.class)).isEqualTo("\"TWO\""); assertThat(actual.getTupleValue("tuple2").get(1, String.class)).isEqualTo("2"); assertThat(actual.getTupleValue("tuple_nesting")).isEqualTo(nestedTuple2Value); assertThat(actual.getString("value")).isEqualTo("val"); assertThat(actual.getInt("intwrapper")).isEqualTo(123); assertThat(actual.getString("protocolversion")).isEqualTo("V4"); assertThat(actual.getInt("encoding")).isEqualTo(1); assertThat(actual.get("doublearray", double[].class)).isEqualTo(new double[] { 1.0, 2.0 }); assertThat(actual.get("floatarray", float[].class)).isEqualTo(new float[] { 3.0f, 4.0f }); assertThat(actual.get("intarray", int[].class)).isEqualTo(new int[] { 5, 6 }); assertThat(actual.get("longarray", long[].class)).isEqualTo(new long[] { 7L, 8L }); assertThat(actual.getList("listoflongarray", long[].class)).containsExactly(new long[] { 9L, 10L }); assertThat(actual.get("jdkinstant", java.time.Instant.class)).isNotNull(); assertThat(actual.get("jdklocaldate", java.time.LocalDate.class)).isNotNull(); assertThat(actual.get("jdklocaltime", java.time.LocalTime.class)).isNotNull(); assertThat(actual.get("jdkzoneddatetime", java.time.ZonedDateTime.class)).isNotNull(); assertThat(actual.getInt("protocolversionasordinal")).isEqualTo(1); assertThat(actual.isNull("optionalstring")).isTrue(); assertThat(actual.getString("optionalprotocolversion")).isEqualTo("V3"); assertThat(actual.getInt("optionalencodingasordinal")).isEqualTo(1); assertThat(actual.getList("listofoptional", String.class)).containsExactly("1", "2"); }
From source file:org.ng200.openolympus.services.ContestService.java
public boolean hasContestStarted(final Contest contest) { if (contest == null) { return false; }//from w w w . jav a 2 s. c o m return !contest.getStartTime().toInstant().isAfter(Instant.now()); }
From source file:co.runrightfast.component.events.impl.ComponentEventImpl.java
public ComponentEventImpl(@NonNull final ComponentId componentId, @NonNull final Event<DATA> event, @NonNull final DATA data, @NonNull final Throwable exception, String... tags) { this(componentId, UUID.randomUUID(), Instant.now(), AppUtils.JVM_ID, event, Optional.of(data), Optional.of(exception), ArrayUtils.isNotEmpty(tags) ? Optional.of(ImmutableSet.copyOf(tags)) : Optional.empty()); }