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

The following examples show how to use java.time.Instant#parse() . 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: TaskController.java    From taskana with Apache License 2.0 6 votes vote down vote up
private void updateTaskQueryWithPlannedOrDueTimeInterval(
    TaskQuery taskQuery,
    MultiValueMap<String, String> params,
    String plannedFromOrDueFrom,
    String plannedToOrDueTo) {

  TimeInterval timeInterval =
      new TimeInterval(
          Instant.parse(params.get(plannedFromOrDueFrom).get(0)),
          Instant.parse(params.get(plannedToOrDueTo).get(0)));

  taskQuery.plannedWithin(timeInterval);

  params.remove(plannedToOrDueTo);
  params.remove(plannedFromOrDueFrom);
}
 
Example 2
Source File: MetricsPublisherImplTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishDurationMetric() {
    final MetricsPublisherImpl providerMetricsPublisher = new MetricsPublisherImpl(providerCloudWatchProvider, loggerProxy,
                                                                                   awsAccountId, resourceTypeName);
    providerMetricsPublisher.refreshClient();

    final Instant instant = Instant.parse("2019-06-04T17:50:00Z");
    providerMetricsPublisher.publishDurationMetric(instant, Action.UPDATE, 123456);

    final ArgumentCaptor<PutMetricDataRequest> argument1 = ArgumentCaptor.forClass(PutMetricDataRequest.class);
    verify(providerCloudWatchClient).putMetricData(argument1.capture());

    final PutMetricDataRequest request = argument1.getValue();
    assertThat(request.namespace())
        .isEqualTo(String.format("%s/%s/%s", "AWS/CloudFormation", awsAccountId, "AWS/Test/TestModel"));

    assertThat(request.metricData()).hasSize(1);
    final MetricDatum metricDatum = request.metricData().get(0);
    assertThat(metricDatum.metricName()).isEqualTo("HandlerInvocationDuration");
    assertThat(metricDatum.unit()).isEqualTo(StandardUnit.MILLISECONDS);
    assertThat(metricDatum.value()).isEqualTo(123456);
    assertThat(metricDatum.timestamp()).isEqualTo(Instant.parse("2019-06-04T17:50:00Z"));
    assertThat(metricDatum.dimensions()).containsExactlyInAnyOrder(Dimension.builder().name("Action").value("UPDATE").build(),
        Dimension.builder().name("ResourceType").value(resourceTypeName).build());
}
 
Example 3
Source File: JibHelper.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
public void prepare(final String artifactId, final String projectVersion, final Properties projectProperties,
        final String fromImage, final String toImage, final String createTime, final String workDir,
        final Supplier<String> fallbackWorkingDir, final Map<String, String> environment,
        final Map<String, String> labels) throws InvalidImageReferenceException {
    if (builder != null) {
        throw new IllegalStateException("prepare had already been called");
    }

    builder = Jib.from(ImageReference.parse(fromImage));
    creationTime = createTime == null || createTime.trim().isEmpty() ? Instant.now() : Instant.parse(createTime);
    builder.setCreationTime(this.creationTime);
    workingDirectory = AbsoluteUnixPath.get(workDir == null ? fallbackWorkingDir.get() : workDir);
    builder.setWorkingDirectory(this.workingDirectory);
    if (environment != null) {
        builder.setEnvironment(environment);
    }

    tag = projectVersion.endsWith("-SNAPSHOT")
            ? projectVersion.replace("-SNAPSHOT", "") + "_"
                    + ofNullable(projectProperties.getProperty("git.branch"))
                            .map(it -> it.replace('/', '_') + '_')
                            .orElse("")
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
            : projectVersion;
    image = toImage == null ? artifactId : toImage;
    imageName = ((repository == null || repository.trim().isEmpty()) ? "" : (repository + '/')) + image + ':' + tag;

    if (labels != null) {
        builder
                .setLabels(labels
                        .entrySet()
                        .stream()
                        .peek(it -> it.setValue(it.getValue().replace("@imageName@", imageName)))
                        .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
    }
}
 
Example 4
Source File: PostgresJdbcTemplateLockProviderIntegrationTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Test
void shouldHonorTimezone() {
    TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");

    Instant lockUntil = Instant.parse("2020-04-10T17:30:00Z");
    ClockProvider.setClock(Clock.fixed(lockUntil.minusSeconds(10), timezone.toZoneId()));

    TimeZone originalTimezone = TimeZone.getDefault();


    DataSource datasource = getDatasource();

    TimeZone.setDefault(timezone);

    try {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
        jdbcTemplate.execute("CREATE TABLE shedlock_tz(name VARCHAR(64), lock_until TIMESTAMP WITH TIME ZONE, locked_at TIMESTAMP WITH TIME ZONE, locked_by  VARCHAR(255), PRIMARY KEY (name))");

        JdbcTemplateLockProvider provider = new JdbcTemplateLockProvider(builder()
            .withJdbcTemplate(new JdbcTemplate(datasource))
            .withTableName("shedlock_tz")
            .withTimeZone(timezone)
            .build());


        provider.lock(new LockConfiguration("timezone_test", lockUntil));
        new JdbcTemplate(datasource).query("SELECT * FROM shedlock_tz where name='timezone_test'", rs -> {
            Timestamp timestamp = rs.getTimestamp("lock_until");
            assertThat(timestamp.getTimezoneOffset()).isEqualTo(7 * 60);
            assertThat(timestamp.toInstant()).isEqualTo(lockUntil);
        });
    } finally {
        TimeZone.setDefault(originalTimezone);
    }
}
 
Example 5
Source File: StashRequestManagerTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testUndoCreateRequestFutureStash() {
    Instant now = Instant.parse("2017-11-20T11:30:00.000Z");
    _stashRequestDAO.requestStash("byrequest-2017-11-20-12-00-00", new StashRequest("requester1", new Date(now.minus(Duration.ofMinutes(1)).toEpochMilli())));
    setClockTo(now);
    _stashRequestManager.undoRequestForStashOnOrAfter("byrequest", now, "requester1");

    assertEquals(_stashRequestDAO.getRequestsForStash("byrequest-2017-11-20-12-00-00"), ImmutableSet.of());
}
 
Example 6
Source File: PsqlReplicationCheckTest.java    From dbeam with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeReplicationDelayedWhenReplicatedUpToPartitionStart() {
  Instant partition = Instant.parse("2027-07-31T00:00:00Z");
  Instant lastReplication = Instant.parse("2027-07-31T00:00:00Z");
  Period partitionPeriod = Period.ofDays(1);

  Assert.assertTrue(
      PsqlReplicationCheck.isReplicationDelayed(partition, lastReplication, partitionPeriod));
}
 
Example 7
Source File: AbstractAccTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
protected Attachment createAttachment(
    String classificationKey,
    ObjectReference objRef,
    String channel,
    String receivedDate,
    Map<String, String> customAttributes)
    throws ClassificationNotFoundException {
  Attachment attachment = taskanaEngine.getTaskService().newAttachment();

  attachment.setClassificationSummary(
      taskanaEngine
          .getClassificationService()
          .getClassification(classificationKey, "DOMAIN_A")
          .asSummary());
  attachment.setObjectReference(objRef);
  attachment.setChannel(channel);
  Instant receivedTimestamp = null;
  if (receivedDate != null && receivedDate.length() < 11) {
    // contains only the date, not the time
    LocalDate date = LocalDate.parse(receivedDate);
    receivedTimestamp = date.atStartOfDay().toInstant(ZoneOffset.UTC);
  } else {
    receivedTimestamp = Instant.parse(receivedDate);
  }
  attachment.setReceived(receivedTimestamp);
  if (customAttributes != null) {
    attachment.setCustomAttributes(customAttributes);
  }

  return attachment;
}
 
Example 8
Source File: ConvertersTest.java    From dropwizard-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromInstant() {
  final Instant instant = Instant.parse("2018-01-12T12:45:32.123Z");

  final Timestamp actual = Converters.toInstantUTC.reverse().convert(instant);
  final Timestamp expected =
      Timestamp.newBuilder().setSeconds(1515761132).setNanos(123000000).build();

  assertThat(actual).isEqualTo(expected);
}
 
Example 9
Source File: BackgroundRunnerTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void schedulesTheFirstExecutionAroundMidnightWhenRequestedJustBeforeMidnight() throws Exception {
  final ScheduledExecutorTester mock = new ScheduledExecutorTester();
  final Instant midnight = Instant.parse("1970-01-01T23:59:59Z");
  BackgroundRunner<String> instance = new BackgroundRunner<>(24, Clock.fixed(midnight, ZoneId.of("Z")), mock);

  instance.start(() -> "");

  assertThat(mock.initialDelay, is(1L));
}
 
Example 10
Source File: InstantFormatter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Instant parse(String text, Locale locale) throws ParseException {
	if (text.length() > 0 && Character.isDigit(text.charAt(0))) {
		// assuming UTC instant a la "2007-12-03T10:15:30.00Z"
		return Instant.parse(text);
	}
	else {
		// assuming RFC-1123 value a la "Tue, 3 Jun 2008 11:05:30 GMT"
		return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(text));
	}
}
 
Example 11
Source File: TCKInstant.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="ParseFailures", expectedExceptions=DateTimeParseException.class)
public void factory_parseFailures(String text) {
    Instant.parse(text);
}
 
Example 12
Source File: TCKInstant.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="Parse")
public void factory_parse(String text, long expectedEpochSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.parse(text);
    assertEquals(t.getEpochSecond(), expectedEpochSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 13
Source File: EntityHydrationTest.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
@BeforeEach
void setUpBeforeMethod() {
  // create referenced entities
  EntityType refEntityType = entityTestHarness.createDynamicRefEntityType();
  List<Entity> refEntities = entityTestHarness.createTestRefEntities(refEntityType, 1);

  entityType = entityTestHarness.createDynamicTestEntityType(refEntityType);

  // create hydrated entity
  hydratedEntity =
      entityTestHarness.createTestEntities(entityType, 1, refEntities).collect(toList()).get(0);

  LocalDate date = LocalDate.parse("2012-12-21");
  Instant dateTime = Instant.parse("1985-08-12T06:12:13Z");

  // create dehydrated entity
  dehydratedEntity = newHashMap();
  dehydratedEntity.put(ATTR_ID, "0");
  dehydratedEntity.put(ATTR_STRING, "string1");
  dehydratedEntity.put(ATTR_BOOL, true);
  dehydratedEntity.put(ATTR_CATEGORICAL, "0");
  dehydratedEntity.put(ATTR_CATEGORICAL_MREF, singletonList("0"));
  dehydratedEntity.put(ATTR_DATE, date);
  dehydratedEntity.put(ATTR_DATETIME, dateTime);
  dehydratedEntity.put(ATTR_EMAIL, "[email protected]");
  dehydratedEntity.put(ATTR_DECIMAL, 0.123);
  dehydratedEntity.put(ATTR_HTML, null);
  dehydratedEntity.put(ATTR_HYPERLINK, "http://www.molgenis.org");
  dehydratedEntity.put(ATTR_LONG, 0L);
  dehydratedEntity.put(ATTR_INT, 10);
  dehydratedEntity.put(ATTR_SCRIPT, "/bin/blaat/script.sh");
  dehydratedEntity.put(ATTR_XREF, "0");
  dehydratedEntity.put(ATTR_MREF, singletonList("0"));
  dehydratedEntity.put(ATTR_COMPOUND_CHILD_INT, 10);
  dehydratedEntity.put(ATTR_ENUM, "option1");

  // mock entity manager
  entityManager =
      when(mock(EntityManager.class).create(entityType, EntityManager.CreationMode.NO_POPULATE))
          .thenReturn(new EntityWithComputedAttributes(new DynamicEntity(entityType)))
          .getMock();
  when(entityManager.getReference(entityTypeArgumentCaptor.capture(), eq("0")))
      .thenReturn(refEntities.get(0));
  when(entityManager.getReferences(entityTypeArgumentCaptor.capture(), eq(newArrayList("0"))))
      .thenReturn(refEntities);
  entityHydration = new EntityHydration(entityManager);
}
 
Example 14
Source File: StashRequestManagerTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Test (expectedExceptions = InvalidStashRequestException.class)
public void testUndoCreateRequestForNoRequestRequiredStash() {
    Instant now = Instant.parse("2017-11-20T23:30:00.000Z");
    setClockTo(now);
    _stashRequestManager.requestStashOnOrAfter("always", now, "requester1");
}
 
Example 15
Source File: ContainerDetails.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public long getCreated() {
    String date = json.get(CREATED).getAsString();
    Instant instant = Instant.parse(date);
    return instant.toEpochMilli();
}
 
Example 16
Source File: OrderAccepted.java    From scalable-coffee-shop with Apache License 2.0 4 votes vote down vote up
public OrderAccepted(JsonObject jsonObject) {
    this(new OrderInfo(jsonObject.getJsonObject("orderInfo")), Instant.parse(jsonObject.getString("instant")));
}
 
Example 17
Source File: TCKInstant.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="Parse")
public void factory_parse(String text, long expectedEpochSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.parse(text);
    assertEquals(t.getEpochSecond(), expectedEpochSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 18
Source File: ExternalWorkerAcquireJobResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = "org/flowable/external/job/rest/service/api/simpleExternalWorkerJob.bpmn20.xml")
void failBpmnJobWithCustomValues() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("simpleExternalWorker");

    assertThat(taskService.createTaskQuery().list()).isEmpty();
    assertThat(runtimeService.getVariables(processInstance.getId())).isEmpty();

    ExternalWorkerJob externalWorkerJob = managementService.createExternalWorkerJobQuery().singleResult();
    assertThat(externalWorkerJob).isNotNull();

    managementService.createExternalWorkerJobAcquireBuilder()
            .topic("simple", Duration.ofMinutes(10))
            .acquireAndLock(1, "testWorker1");

    Instant failTime = Instant.parse("2020-05-12T09:25:45.583Z");
    processEngineConfiguration.getClock().setCurrentTime(Date.from(failTime));

    ObjectNode request = objectMapper.createObjectNode();
    request.put("workerId", "testWorker1");
    request.put("retries", 10);
    request.put("retryTimeout", "PT30M");
    request.put("errorMessage", "Error message");
    request.put("errorDetails", "Error details");

    ResponseEntity<String> response = restTemplate
            .postForEntity("/service/acquire/jobs/{jobId}/fail", request, String.class, externalWorkerJob.getId());

    assertThat(response.getStatusCode()).as(response.toString()).isEqualTo(HttpStatus.NO_CONTENT);
    String body = response.getBody();
    assertThat(body).isNull();

    JobTestHelper.waitForJobExecutorToProcessAllJobs(processEngineConfiguration, managementService, 4000, 300);

    assertThat(taskService.createTaskQuery().list()).isEmpty();

    externalWorkerJob = managementService.createExternalWorkerJobQuery().singleResult();

    assertThat(externalWorkerJob).isNotNull();
    assertThat(externalWorkerJob.getRetries()).isEqualTo(10);
    assertThat(externalWorkerJob.getLockExpirationTime()).isEqualTo(Date.from(Instant.parse("2020-05-12T09:55:45.583Z")));
    assertThat(externalWorkerJob.getLockOwner()).isNull();
    assertThat(externalWorkerJob.getExceptionMessage()).isEqualTo("Error message");
    assertThat(managementService.getExternalWorkerJobErrorDetails(externalWorkerJob.getId())).isEqualTo("Error details");
}
 
Example 19
Source File: CoffeeBrewStarted.java    From scalable-coffee-shop with Apache License 2.0 4 votes vote down vote up
public CoffeeBrewStarted(JsonObject jsonObject) {
    this(new OrderInfo(jsonObject.getJsonObject("orderInfo")), Instant.parse(jsonObject.getString("instant")));
}
 
Example 20
Source File: TCKInstant.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="Parse")
public void factory_parseLowercase(String text, long expectedEpochSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.parse(text.toLowerCase(Locale.ENGLISH));
    assertEquals(t.getEpochSecond(), expectedEpochSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}