Java Code Examples for java.time.Instant#now()

The following examples show how to use java.time.Instant#now() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoginResultLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenAnnotatedLoginResult_whenSameApiToken_thenEqualInstances()
throws MalformedURLException {
    String theSameApiToken = "testapitoken";

    LoginResult loginResult1 = new LoginResult(
            Instant.now(),
            theSameApiToken,
            Duration.ofHours(1),
            new URL("https://api.product.com/token-refresh"));

    LoginResult loginResult2 = new LoginResult(
            Instant.now(),
            theSameApiToken,
            Duration.ofHours(2),
            new URL("https://api.product.com/token-refresh-alt"));

    Assert.assertEquals(loginResult1, loginResult2);
}
 
Example 2
Source File: ContractController.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * query by contract id.
 */
@GetMapping(value = "/{contractId}")
public BaseResponse queryContract(@PathVariable("contractId") Integer contractId)
    throws NodeMgrException, Exception {
    BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
    Instant startTime = Instant.now();
    log.info("start queryContract startTime:{} contractId:{}", startTime.toEpochMilli(),
        contractId);

    TbContract contractRow = contractService.queryByContractId(contractId);
    baseResponse.setData(contractRow);

    log.info("end queryContract useTime:{} result:{}",
        Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse));
    return baseResponse;
}
 
Example 3
Source File: TransportOrder.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a copy of this object, with the given state.
 *
 * @param state The value to be set in the copy.
 * @return A copy of this object, differing in the given value.
 */
public TransportOrder withState(@Nonnull State state) {
  // XXX Finished time should probably not be set implicitly.
  return new TransportOrder(getIdWithoutDeprecationWarning(),
                            getName(),
                            getProperties(),
                            historyForNewState(state),
                            category,
                            driveOrders,
                            currentDriveOrderIndex,
                            creationTime,
                            intendedVehicle,
                            deadline,
                            dispensable,
                            wrappingSequence,
                            dependencies,
                            rejections,
                            processingVehicle,
                            state,
                            state == State.FINISHED ? Instant.now() : finishedTime);
}
 
Example 4
Source File: LoggingOutputStream.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public void write(final byte[] buf, final int offset,
    final int len) throws IOException {
    final Instant start = Instant.now();
    this.origin.write(buf, offset, len);
    final Instant end = Instant.now();
    final long millis = Duration.between(start, end).toMillis();
    this.bytes.getAndAdd(len);
    this.time.getAndAdd(millis);
    final Level level = this.logger.getLevel();
    if (!level.equals(Level.INFO)) {
        this.logger.log(
            level,
            new UncheckedText(
                new FormattedText(
                    "Written %d byte(s) to %s in %dms.",
                    this.bytes.get(),
                    this.destination,
                    this.time.get()
                )
            ).asString()
        );
    }
}
 
Example 5
Source File: TaskControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
/**
 * TSK-926: If Planned and Due Date is provided to create a task and not matching to service level
 * throw an exception One is calculated by other other date +- service level.
 */
@Test
void testCreateWithPlannedAndDueDate() {
  TaskRepresentationModel taskRepresentationModel = getTaskResourceSample();
  Instant now = Instant.now();
  taskRepresentationModel.setPlanned(now);
  taskRepresentationModel.setDue(now);

  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_TASKS),
              HttpMethod.POST,
              new HttpEntity<>(taskRepresentationModel, restHelper.getHeadersUser_1_1()),
              TASK_MODEL_TYPE);
  assertThatThrownBy(httpCall).isInstanceOf(HttpClientErrorException.class);
}
 
Example 6
Source File: TimeSliceCacheTest.java    From swblocks-decisiontree with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTimeSlices() {
    final Instant now = Instant.now();

    final TimeSliceCache timeSliceCache = TimeSliceCache.getInstance();
    final TreeNode node1 = NodeSupplier.createTreeNode(new StringDriver("Test1"),
            NodeSupplier.ROOT_NODE_LEVEL).get();
    final Optional<Range<Instant>> range1 = Optional.of(new Range<>(now.minus(10, ChronoUnit.DAYS),
            now.minus(5, ChronoUnit.DAYS)));
    final TreeNode node2 = NodeSupplier.createTreeNode(new StringDriver("Test2"),
            NodeSupplier.ROOT_NODE_LEVEL).get();
    final Optional<Range<Instant>> range2 = Optional.of(new Range<>(now.plus(1, ChronoUnit.DAYS),
            now.plus(10, ChronoUnit.DAYS)));
    final Optional<Range<Instant>> range3 = Optional.of(new Range<>(now.plus(11, ChronoUnit.DAYS),
            now.plus(20, ChronoUnit.DAYS)));

    timeSliceCache.put(range1.get(), Optional.of(node1));
    timeSliceCache.put(range2.get(), Optional.of(node2));

    assertEquals(node1, timeSliceCache.get(range1).get());
    assertEquals(node2, timeSliceCache.get(range2).get());
    assertFalse(timeSliceCache.get(range3).isPresent());

    final Range<Instant>[] sliceSet = timeSliceCache.keys();
    assertEquals(sliceSet.length, 2);
}
 
Example 7
Source File: CompleteTaskAccTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@WithAccessId(user = "user-1-2")
@Test
void should_CompleteValidTasksEvenIfErrorsExist_When_BulkCompletingTasks() throws Exception {
  String invalid = "invalid-id";
  String validId = "TKI:000000000000000000000000000000000103";
  List<String> taskIdList = Arrays.asList(invalid, validId);

  Instant beforeBulkComplete = Instant.now();
  BulkOperationResults<String, TaskanaException> results = TASK_SERVICE.completeTasks(taskIdList);

  assertThat(results.containsErrors()).isTrue();
  Task completedTask = TASK_SERVICE.getTask(validId);
  assertThat(completedTask.getState()).isEqualTo(TaskState.COMPLETED);
  assertThat(completedTask.getCompleted())
      .isEqualTo(completedTask.getModified())
      .isAfterOrEqualTo(beforeBulkComplete);
  assertThat(completedTask.getOwner()).isEqualTo("user-1-2");
}
 
Example 8
Source File: ScriptCommandContextImpl.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("nls")
@Override
public void logData(final String device, final Object obj) throws Exception
{
    // Check received data
    final NDArray data;
    if (obj instanceof NDArray)
        data = (NDArray) obj;
    else
    {
        try
        {
            data = NDArray.create(obj);
        }
        catch (IllegalArgumentException ex)
        {
            throw new Exception("Cannot log data of type " + obj.getClass().getName(), ex);
        }
    }
    // Log the data
    final Instant timestamp = Instant.now();
    final IteratorNumber iter = data.getIterator();
    long serial = 0;
    while (iter.hasNext())
    {
        final ScanSample sample =
            ScanSampleFactory.createSample(timestamp , serial++, iter.nextDouble());
        context.getDataLog().get().log(device, sample);
    }
}
 
Example 9
Source File: ScaleUpResolverTest.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Test
public void testScaleUpFactorComputation() {
  Instant now = Instant.now();
  Collection<Measurement> result = new ArrayList<>();

  ExecutionContext context = Mockito.mock(ExecutionContext.class);
  when(context.checkpoint()).thenReturn(now);
  when(context.previousCheckpoint()).thenReturn(now);

  ScaleUpResolver resolver = new ScaleUpResolver(null, null, null, eventManager, null);
  resolver.initialize(context);

  result.add(new Measurement("bolt", "i1", METRIC_BACK_PRESSURE.text(), now, 500));
  result.add(new Measurement("bolt", "i2", METRIC_BACK_PRESSURE.text(), now, 0));
  when(context.measurements()).thenReturn(MeasurementsTable.of(result));
  int factor = resolver.computeScaleUpFactor("bolt");
  assertEquals(4, factor);

  result.clear();
  result.add(new Measurement("bolt", "i1", METRIC_BACK_PRESSURE.text(), now, 750));
  result.add(new Measurement("bolt", "i2", METRIC_BACK_PRESSURE.text(), now, 0));
  when(context.measurements()).thenReturn(MeasurementsTable.of(result));
  factor = resolver.computeScaleUpFactor("bolt");
  assertEquals(8, factor);

  result.clear();
  result.add(new Measurement("bolt", "i1", METRIC_BACK_PRESSURE.text(), now, 400));
  result.add(new Measurement("bolt", "i2", METRIC_BACK_PRESSURE.text(), now, 100));
  result.add(new Measurement("bolt", "i3", METRIC_BACK_PRESSURE.text(), now, 0));
  when(context.measurements()).thenReturn(MeasurementsTable.of(result));
  factor = resolver.computeScaleUpFactor("bolt");
  assertEquals(6, factor);
}
 
Example 10
Source File: BqSink.java    From beast with Apache License 2.0 5 votes vote down vote up
private InsertAllResponse insertIntoBQ(Records records) {
    Instant start = Instant.now();
    Builder builder = newBuilder(tableId);
    records.forEach((Record m) -> builder.addRow(recordInserter.of(m)));
    InsertAllRequest rows = builder.build();
    InsertAllResponse response = bigquery.insertAll(rows);
    log.info("Pushing {} records to BQ success?: {}", records.size(), !response.hasErrors());
    statsClient.count("bq.sink.push.records", records.size());
    statsClient.timeIt("bq.sink.push.time", start);
    return response;
}
 
Example 11
Source File: AbstractEventStoreTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Test
public void should_store_events() {
    InstanceEventStore store = createStore(100);
    StepVerifier.create(store.findAll()).verifyComplete();

    Instant now = Instant.now();
    InstanceEvent event1 = new InstanceRegisteredEvent(id, 0L, now, registration);
    InstanceEvent eventOther = new InstanceRegisteredEvent(
        InstanceId.of("other"),
        0L,
        now.plusMillis(10),
        registration
    );
    InstanceEvent event2 = new InstanceDeregisteredEvent(id, 1L, now.plusMillis(20));

    StepVerifier.create(store)
                .expectSubscription()
                .then(() -> StepVerifier.create(store.append(singletonList(event1))).verifyComplete())
                .expectNext(event1)
                .then(() -> StepVerifier.create(store.append(singletonList(eventOther))).verifyComplete())
                .expectNext(eventOther)
                .then(() -> StepVerifier.create(store.append(singletonList(event2))).verifyComplete())
                .expectNext(event2)
                .thenCancel()
                .verify();

    StepVerifier.create(store.find(id)).expectNext(event1, event2).verifyComplete();
    StepVerifier.create(store.find(InstanceId.of("-"))).verifyComplete();
    StepVerifier.create(store.findAll()).expectNext(event1, eventOther, event2).verifyComplete();
}
 
Example 12
Source File: TimeParserTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void parse() {
    Instant now = Instant.now();
    // create time interval using string to define relative start and end
    // times
    TimeRelativeInterval interval = TimeRelativeInterval.of(TimeParser.parseTemporalAmount("1 min"), now);
    assertEquals(now.minusSeconds(60), interval.toAbsoluteInterval().getStart());
    assertEquals(now, interval.toAbsoluteInterval().getEnd());
}
 
Example 13
Source File: Data.java    From Medusa with Apache License 2.0 4 votes vote down vote up
public Data(final double VALUE) {
    value     = VALUE;
    timestamp = Instant.now();
}
 
Example 14
Source File: ChartData.java    From tilesfx with Apache License 2.0 4 votes vote down vote up
public ChartData(final String NAME, final double VALUE ,final Color FILL_COLOR, final java.time.Duration DURATION) {
    this(null, NAME, VALUE, FILL_COLOR, Color.TRANSPARENT, Tile.FOREGROUND, Instant.now(), DURATION, true, 800);
}
 
Example 15
Source File: GetOngoingSessionsActionTest.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
@Override
@Test
protected void testExecute() throws Exception {
    ______TS("Verify no ongoing session");

    String[] params = new String[] {
            Const.ParamsNames.FEEDBACK_SESSION_STARTTIME, "0",
            Const.ParamsNames.FEEDBACK_SESSION_ENDTIME, "1000",
    };

    GetOngoingSessionsAction getOngoingSessionsAction = getAction(params);
    JsonResult r = getJsonResult(getOngoingSessionsAction);

    verifyNoExistingSession(r);

    ______TS("Typical use case");

    InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1");
    String courseId = instructor1OfCourse1.courseId;

    Instant startTime = Instant.now();
    Instant endTime = Instant.now().plus(5, ChronoUnit.DAYS);

    logic.createFeedbackSession(
            FeedbackSessionAttributes.builder("new-session", courseId)
                    .withCreatorEmail(instructor1OfCourse1.email)
                    .withStartTime(startTime)
                    .withEndTime(endTime)
                    .withSessionVisibleFromTime(startTime)
                    .withResultsVisibleFromTime(endTime)
                    .build());

    params = new String[] {
            Const.ParamsNames.FEEDBACK_SESSION_STARTTIME, String.valueOf(startTime.toEpochMilli()),
            Const.ParamsNames.FEEDBACK_SESSION_ENDTIME, String.valueOf(endTime.toEpochMilli()),
    };

    getOngoingSessionsAction = getAction(params);
    r = getJsonResult(getOngoingSessionsAction);

    assertEquals(HttpStatus.SC_OK, r.getStatusCode());
    OngoingSessionsData response = (OngoingSessionsData) r.getOutput();

    assertEquals(0, response.getTotalAwaitingSessions());
    assertEquals(1, response.getTotalOpenSessions());
    assertEquals(0, response.getTotalClosedSessions());
    assertEquals(1, response.getTotalOngoingSessions());
    assertEquals(1, response.getTotalInstitutes());
    assertEquals(1, response.getSessions().size());
}
 
Example 16
Source File: BarChartItem.java    From tilesfx with Apache License 2.0 4 votes vote down vote up
public BarChartItem() {
    this("", 0, Instant.now(), Duration.ZERO, Tile.BLUE);
}
 
Example 17
Source File: Location.java    From OEE-Designer with MIT License 4 votes vote down vote up
public Location() {
    this(0, 0, 0, Instant.now(), "", "", TileColor.BLUE.color);
}
 
Example 18
Source File: SlayerPlugin.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
private void setTask(String name, int amt, int initAmt, boolean isNewAssignment, String location, int lastCertainAmt, boolean addCounter)
{
	currentTask = new TaskData(isNewAssignment ? 0 : currentTask.getElapsedTime(),
		isNewAssignment ? 0 : currentTask.getElapsedKills(),
		isNewAssignment ? 0 : currentTask.getElapsedXp(),
		amt, initAmt, lastCertainAmt, location, name,
		isNewAssignment || currentTask.isPaused());
	if (panel != null)
	{
		panel.updateCurrentTask(true, currentTask.isPaused(), currentTask, isNewAssignment);
	}

	save();
	removeCounter();

	if (addCounter)
	{
		infoTimer = Instant.now();
		addCounter();
	}

	Task task = Task.getTask(name);
	targetNames.clear();
	targetNames = buildTargetNames(task);
	rebuildTargetIds(task);
	rebuildCheckAsTokens(task);
	rebuildTargetList();

	if (task == null)
	{
		return;
	}

	if (!weaknessOverlayAttached && task.getWeaknessItem() != -1 && task.getWeaknessThreshold() != -1)
	{
		overlayManager.add(targetWeaknessOverlay);
		weaknessOverlayAttached = true;
	}
	else if (weaknessOverlayAttached && task.getWeaknessItem() == -1 && task.getWeaknessThreshold() == -1)
	{
		overlayManager.remove(targetWeaknessOverlay);
		weaknessOverlayAttached = false;
	}
}
 
Example 19
Source File: PodcastServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Returns only those podcasts whose DISPLAY_DATE property is today or earlier
 * This version for feed so can pass siteId
 * 
 * @param resourcesList
 *            List of podcasts
 * 
 * @return List 
 * 			List of podcasts whose DISPLAY_DATE is today or before
 */	
public List filterPodcasts(List resourcesList, String siteId) {
	List filteredPodcasts = new ArrayList();

	final Instant now = Instant.now();

	// loop to check if DISPLAY_DATE has been set. If not, set it
	final Iterator podcastIter = resourcesList.iterator();
	ContentResource aResource = null;
	ResourceProperties itsProperties = null;

	// for each bean
	while (podcastIter.hasNext()) {
		// get its properties from ContentHosting
		aResource = (ContentResource) podcastIter.next();
		itsProperties = aResource.getProperties();

		try {
			Instant podcastTime = aResource.getReleaseInstant();
			
			if (podcastTime == null) {
				podcastTime = itsProperties.getInstantProperty(DISPLAY_DATE);
			}

			// has it been published or does user have hidden permission
			if (podcastTime.toEpochMilli() <= now.toEpochMilli() || 
				podcastPermissionsService.hasPerm(PodcastPermissionsService.HIDDEN_PERMISSIONS, 
												  retrievePodcastFolderId(siteId), siteId)) {
				
				// check if there is a retract date and if so, we have not
				// passed it
				final Instant retractDate = aResource.getRetractInstant();
				if (retractDate == null || retractDate.toEpochMilli() >= now.toEpochMilli()) {
					filteredPodcasts.add(aResource);
				}
			}
		} 
		catch (Exception e) {
			// catches EntityPropertyNotDefinedException, EntityPropertyTypeException
			// any problems, skip this one
			log.warn(e.getMessage() + " for podcast item: " + aResource.getId() + ". SKIPPING...", e);
		} 
	}

	return filteredPodcasts;
}
 
Example 20
Source File: WoodcuttingSession.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
void setLastChopping()
{
	lastChopping  = Instant.now();
}